prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>test_urls.py<|end_file_name|><|fim▁begin|>import unittest from django.core.urlresolvers import resolve, reverse, NoReverseMatch from pulp.server.webservices.urls import handler404 def assert_url_match(expected_url, url_name, *args, **kwargs): """ Generate a url given args and kwargs and pass it through Django's reverse and resolve functions. Example use to match a url /v2/tasks/<task_argument>/: assert_url_match('/v2/tasks/example_arg/', 'tasks', task_argument='example_arg') :param expected_url: the url that should be generated given a url_name and args :type expected_url: str :param url_name : name given to a url as defined in the urls.py :type url_name : str :param args : optional positional arguments to place into a url's parameters as specified by urls.py :type args : tuple :param kwargs : optional named arguments to place into a url's parameters as specified by urls.py :type kwargs : dict """ try: # Invalid arguments will cause a NoReverseMatch. url = reverse(url_name, args=args, kwargs=kwargs) except NoReverseMatch: raise AssertionError( "Name: '{0}' could match a url with args '{1}'" "and kwargs '{2}'".format(url_name, args, kwargs) ) else: # If the url exists but is not the expected url. if url != expected_url: raise AssertionError( 'url {0} not equal to expected url {1}'.format(url, expected_url)) # Run this url back through resolve and ensure that it matches the url_name. matched_view = resolve(url) if matched_view.url_name != url_name: raise AssertionError('Url name {0} not equal to expected url name {1}'.format( matched_view.url_name, url_name) ) class TestNotFoundHandler(unittest.TestCase): def test_not_found_handler(self): """ Test that the handler404 module attribute is set as expected. """ self.assertEqual(handler404, 'pulp.server.webservices.views.util.page_not_found') class TestDjangoContentUrls(unittest.TestCase): """ Test the matching of the content urls """ def test_match_content_catalog_resource(self): """ Test url matching for content_catalog_resource. """ url = '/v2/content/catalog/mock-source/' url_name = 'content_catalog_resource' assert_url_match(url, url_name, source_id='mock-source') def test_match_content_orphan_collection(self): """ Test url matching for content_orphan_collection. """ url = '/v2/content/orphans/' url_name = 'content_orphan_collection' assert_url_match(url, url_name) def test_match_content_units_collection(self): """ Test the url matching for content_units_collection. """ url = '/v2/content/units/mock-type/' url_name = 'content_units_collection' assert_url_match(url, url_name, type_id='mock-type') def test_match_content_unit_search(self): """ Test the url matching for content_unit_search. """ url = '/v2/content/units/mock-type/search/' url_name = 'content_unit_search' assert_url_match(url, url_name, type_id='mock-type') def test_match_content_unit_resource(self): """ Test url matching for content_unit_resource. """ url = '/v2/content/units/mock-type/mock-unit/' url_name = 'content_unit_resource' assert_url_match(url, url_name, type_id='mock-type', unit_id='mock-unit') def test_match_content_unit_user_metadata_resource(self): """ Test url matching for content_unit_user_metadata_resource. """ url = '/v2/content/units/mock-type/mock-unit/pulp_user_metadata/' url_name = 'content_unit_user_metadata_resource' assert_url_match(url, url_name, type_id='mock-type', unit_id='mock-unit') def test_match_content_upload_resource(self): """ Test url matching for content_upload_resource. """ url = '/v2/content/uploads/mock-upload/' url_name = 'content_upload_resource' assert_url_match(url, url_name, upload_id='mock-upload') def test_match_content_upload_segment_resource(self): """ Test Url matching for content_upload_segment_resource. """ url = '/v2/content/uploads/mock-upload-id/8/' url_name = 'content_upload_segment_resource' assert_url_match(url, url_name, upload_id='mock-upload-id', offset='8') def test_match_content_actions_delete_orphans(self): """ Test url matching for content_actions_delete_orphans. """ url = '/v2/content/actions/delete_orphans/' url_name = 'content_actions_delete_orphans' assert_url_match(url, url_name) def test_match_content_orphan_resource(self): """ Test url matching for content_orphan_resource. """ url = '/v2/content/orphans/mock-type/mock-unit/' url_name = 'content_orphan_resource' assert_url_match(url, url_name, content_type='mock-type', unit_id='mock-unit') def test_match_content_orphan_type_subcollection(self): """ Test url matching for content_orphan_type_subcollection. """ url = '/v2/content/orphans/mock_type/' url_name = 'content_orphan_type_subcollection' assert_url_match(url, url_name, content_type='mock_type') def test_match_content_uploads(self): """ Test url matching for content_uploads. """ url = '/v2/content/uploads/' url_name = 'content_uploads' assert_url_match(url, url_name) class TestDjangoPluginsUrls(unittest.TestCase): """ Test url matching for plugins urls. """ def test_match_distributor_resource_view(self): """ Test the url matching for the distributor resource view. """ url = '/v2/plugins/distributors/mock_distributor/' url_name = 'plugin_distributor_resource' assert_url_match(url, url_name, distributor_id='mock_distributor') def test_match_distributors_view(self): """ Test the url matching for the Distributors view. """ url = '/v2/plugins/distributors/' url_name = 'plugin_distributors' assert_url_match(url, url_name) def test_match_importer_resource_view(self): """ Test the url matching for plugin_importer_resource """ url = '/v2/plugins/importers/mock_importer_id/' url_name = 'plugin_importer_resource' assert_url_match(url, url_name, importer_id='mock_importer_id') def test_match_importers_view(self): """ Test the url matching for the Importers view """ url = '/v2/plugins/importers/' url_name = 'plugin_importers' assert_url_match(url, url_name) def test_match_type_resource_view(self): """ Test the url matching for the TypeResourceView. """ url = '/v2/plugins/types/type_id/' url_name = 'plugin_type_resource' assert_url_match(url, url_name, type_id='type_id') def test_match_types_view(self): """ Test url matching for plugin_types. """ url = '/v2/plugins/types/' url_name = 'plugin_types' assert_url_match(url, url_name) class TestDjangoLoginUrls(unittest.TestCase): """ Tests for root_actions urls. """ def test_match_login_view(self): """ Test url match for login. """ url = '/v2/actions/login/' url_name = 'login' assert_url_match(url, url_name) class TestDjangoConsumerGroupsUrls(unittest.TestCase): """ Tests for consumer_groups urls """ def test_match_consumer_group_view(self): """ Test url matching for consumer_groups """ url = '/v2/consumer_groups/' url_name = 'consumer_group' assert_url_match(url, url_name) def test_match_consumer_group_search_view(self): """ Test url matching for consumer_group_search """ url = '/v2/consumer_groups/search/' url_name = 'consumer_group_search' assert_url_match(url, url_name) def test_match_consumer_group_resource_view(self): """ Test url matching for single consumer_group """ url = '/v2/consumer_groups/test-group/' url_name = 'consumer_group_resource' assert_url_match(url, url_name, consumer_group_id='test-group') def test_match_consumer_group_associate_action_view(self): """ Test url matching for consumer_groups association """ url = '/v2/consumer_groups/test-group/actions/associate/' url_name = 'consumer_group_associate' assert_url_match(url, url_name, consumer_group_id='test-group') def test_match_consumer_group_unassociate_action_view(self): """ Test url matching for consumer_groups unassociation """ url = '/v2/consumer_groups/test-group/actions/unassociate/' url_name = 'consumer_group_unassociate' assert_url_match(url, url_name, consumer_group_id='test-group') def test_match_consumer_group_content_action_install_view(self): """ Test url matching for consumer_groups content installation """ url = '/v2/consumer_groups/test-group/actions/content/install/' url_name = 'consumer_group_content' assert_url_match(url, url_name, consumer_group_id='test-group', action='install') def test_match_consumer_group_content_action_update_view(self): """ Test url matching for consumer_groups content update """ url = '/v2/consumer_groups/test-group/actions/content/update/' url_name = 'consumer_group_content' assert_url_match(url, url_name, consumer_group_id='test-group', action='update') def test_match_consumer_group_content_action_uninstall_view(self): """ Test url matching for consumer_groups content uninstall """ url = '/v2/consumer_groups/test-group/actions/content/uninstall/' url_name = 'consumer_group_content' assert_url_match(url, url_name, consumer_group_id='test-group', action='uninstall') def test_match_consumer_group_bindings_view(self): """ Test url matching for consumer_groups bindings """ url = '/v2/consumer_groups/test-group/bindings/' url_name = 'consumer_group_bind' assert_url_match(url, url_name, consumer_group_id='test-group') def test_match_consumer_group_binding_view(self): """ Test url matching for consumer_groups binding removal """ url = '/v2/consumer_groups/test-group/bindings/repo1/dist1/' url_name = 'consumer_group_unbind' assert_url_match(url, url_name, consumer_group_id='test-group', repo_id='repo1', distributor_id='dist1') class TestDjangoRepositoriesUrls(unittest.TestCase): """ Test url matching for repositories urls. """ def test_match_repos(self): """ Test url matching for repos. """ url = '/v2/repositories/' url_name = 'repos' assert_url_match(url, url_name) def test_match_repo_search(self): """ Test url matching for repo_search. """ url = '/v2/repositories/search/' url_name = 'repo_search' assert_url_match(url, url_name) def test_match_repo_content_app_regen(self): """ Test url matching for repo_content_app_regen. """ url_name = 'repo_content_app_regen' url = '/v2/repositories/actions/content/regenerate_applicability/' assert_url_match(url, url_name) def test_match_repo_resource(self): """ Test url matching for repo_resource. """ url_name = 'repo_resource' url = '/v2/repositories/mock_repo/' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_unit_search(self): """ Test url matching for repo_unit_search. """ url_name = 'repo_unit_search' url = '/v2/repositories/mock_repo/search/units/' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_importers(self): """ Test url matching for repo_importers. """ url_name = 'repo_importers' url = '/v2/repositories/mock_repo/importers/' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_importer_resource(self): """ Test url matching for repo_importer_resource. """ url = '/v2/repositories/mock_repo/importers/mock_importer/' url_name = 'repo_importer_resource' assert_url_match(url, url_name, repo_id='mock_repo', importer_id='mock_importer') def test_match_repo_sync_schedule_collection(self): """ Test url matching for repo_sync_schedules. """ url = '/v2/repositories/mock_repo/importers/mock_importer/schedules/sync/' url_name = 'repo_sync_schedules' assert_url_match(url, url_name, repo_id='mock_repo', importer_id='mock_importer') def test_match_repo_sync_schedule_resource(self): """ Test url matching for repo_sync_schedule_resource. """ url = '/v2/repositories/mock_repo/importers/mock_importer/schedules/sync/mock_schedule/' url_name = 'repo_sync_schedule_resource' assert_url_match(url, url_name, repo_id='mock_repo', importer_id='mock_importer', schedule_id='mock_schedule') def test_match_repo_distributors(self): """ Test url matching for repo_distributors. """ url = '/v2/repositories/mock_repo/distributors/' url_name = 'repo_distributors' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_distributor_resource(self): """ Test url matching for repo_distributor_resource. """ url = '/v2/repositories/mock_repo/distributors/mock_distributor/' url_name = 'repo_distributor_resource' assert_url_match(url, url_name, repo_id='mock_repo', distributor_id='mock_distributor') def test_match_repo_publish_schedules(self): """ Test url matching for repo_publish_schedules. """ url = '/v2/repositories/mock_repo/distributors/mock_distributor/schedules/publish/' url_name = 'repo_publish_schedules' assert_url_match(url, url_name, repo_id='mock_repo', distributor_id='mock_distributor') def test_match_repo_publish_schedule_resource(self): """ Test url matching for repo_publish_schedule_resource. """<|fim▁hole|> url_name = 'repo_publish_schedule_resource' assert_url_match(url, url_name, repo_id='mock_repo', distributor_id='mock_distributor', schedule_id='mock_schedule') def test_match_repo_sync_history(self): """ Test url matching for repo_sync_history. """ url = '/v2/repositories/mock_repo/history/sync/' url_name = 'repo_sync_history' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_sync(self): """ Test url matching for repo_sync. """ url = '/v2/repositories/mock_repo/actions/sync/' url_name = 'repo_sync' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_download(self): """ Test url matching for repo_download. """ url = '/v2/repositories/mock_repo/actions/download/' url_name = 'repo_download' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_publish_history(self): """ Test url matching for repo_publish_history. """ url = '/v2/repositories/mock_repo/history/publish/mock_dist/' url_name = 'repo_publish_history' assert_url_match(url, url_name, repo_id='mock_repo', distributor_id='mock_dist') def test_match_repo_publish(self): """ Test url matching for repo_publish. """ url = '/v2/repositories/mock_repo/actions/publish/' url_name = 'repo_publish' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_associate(self): """ Test url matching for repo_associate. """ url = '/v2/repositories/mock_repo/actions/associate/' url_name = 'repo_associate' assert_url_match(url, url_name, dest_repo_id='mock_repo') def test_match_repo_unassociate(self): """ Test url matching for repo_unassociate. """ url = '/v2/repositories/mock_repo/actions/unassociate/' url_name = 'repo_unassociate' assert_url_match(url, url_name, repo_id='mock_repo') def test_match_repo_import_upload(self): """ Test url matching for repo_import_upload. """ url = '/v2/repositories/mock_repo/actions/import_upload/' url_name = 'repo_import_upload' assert_url_match(url, url_name, repo_id='mock_repo') class TestDjangoRepoGroupsUrls(unittest.TestCase): """ Test url matching for repo_groups urls """ def test_match_repo_groups(self): """Test url matching for repo_groups.""" url = '/v2/repo_groups/' url_name = 'repo_groups' assert_url_match(url, url_name) def test_match_repo_group_search(self): """Test url matching for repo_group_search.""" url = '/v2/repo_groups/search/' url_name = 'repo_group_search' assert_url_match(url, url_name) def test_match_repo_group_resource(self): url = '/v2/repo_groups/test-group-id/' url_name = 'repo_group_resource' assert_url_match(url, url_name, repo_group_id='test-group-id') def test_match_repo_group_associate(self): url = '/v2/repo_groups/test-group-id/actions/associate/' url_name = 'repo_group_associate' assert_url_match(url, url_name, repo_group_id='test-group-id') def test_match_repo_group_unassociate(self): url = '/v2/repo_groups/test-group-id/actions/unassociate/' url_name = 'repo_group_unassociate' assert_url_match(url, url_name, repo_group_id='test-group-id') def test_match_repo_group_distributors(self): url = '/v2/repo_groups/test-group-id/distributors/' url_name = 'repo_group_distributors' assert_url_match(url, url_name, repo_group_id='test-group-id') def test_match_repo_group_distributor_resource(self): url = '/v2/repo_groups/test-group-id/distributors/test-distributor/' url_name = 'repo_group_distributor_resource' assert_url_match(url, url_name, repo_group_id='test-group-id', distributor_id='test-distributor') def test_repo_group_publish(self): url = '/v2/repo_groups/test-group-id/actions/publish/' url_name = 'repo_group_publish' assert_url_match(url, url_name, repo_group_id='test-group-id') class TestDjangoTasksUrls(unittest.TestCase): """ Test the matching for tasks urls. """ def test_match_task_collection(self): """ Test the matching for task_collection. """ url = '/v2/tasks/' url_name = 'task_collection' assert_url_match(url, url_name) def test_match_task_resource(self): """ Test the matching for task_resource. """ url = '/v2/tasks/test-task/' url_name = 'task_resource' assert_url_match(url, url_name, task_id='test-task') def test_match_task_search(self): """ Test the matching for task_resource. """ url = '/v2/tasks/search/' url_name = 'task_search' assert_url_match(url, url_name) class TestDjangoRolesUrls(unittest.TestCase): """ Tests for roles urls. """ def test_match_roles_view(self): """ Test url match for roles. """ url = '/v2/roles/' url_name = 'roles' assert_url_match(url, url_name) def test_match_role_resource_view(self): """ Test url matching for single role. """ url = '/v2/roles/test-role/' url_name = 'role_resource' assert_url_match(url, url_name, role_id='test-role') def test_match_role_users_view(self): """ Test url matching for role's users. """ url = '/v2/roles/test-role/users/' url_name = 'role_users' assert_url_match(url, url_name, role_id='test-role') def test_match_role_user_view(self): """ Test url matching for role's user. """ url = '/v2/roles/test-role/users/test-login/' url_name = 'role_user' assert_url_match(url, url_name, role_id='test-role', login='test-login') class TestDjangoPermissionsUrls(unittest.TestCase): """ Tests for permissions urls """ def test_match_permissions_view(self): """ Test url matching for permissions """ url = '/v2/permissions/' url_name = 'permissions' assert_url_match(url, url_name) def test_match_permission_grant_to_role_view(self): """ Test url matching for grant permissions to a role """ url = '/v2/permissions/actions/grant_to_role/' url_name = 'grant_to_role' assert_url_match(url, url_name) def test_match_permission_grant_to_user_view(self): """ Test url matching for grant permissions to a user """ url = '/v2/permissions/actions/grant_to_user/' url_name = 'grant_to_user' assert_url_match(url, url_name) def test_match_permission_revoke_from_role_view(self): """ Test url matching for revoke permissions from a role """ url = '/v2/permissions/actions/revoke_from_role/' url_name = 'revoke_from_role' assert_url_match(url, url_name) def test_match_permission_revoke_from_userview(self): """ Test url matching for revoke permissions from a user """ url = '/v2/permissions/actions/revoke_from_user/' url_name = 'revoke_from_user' assert_url_match(url, url_name) class TestDjangoEventListenersUrls(unittest.TestCase): """ Tests for events urls """ def test_match_event_listeners_view(self): """ Test url matching for event_listeners """ url = '/v2/events/' url_name = 'events' assert_url_match(url, url_name) def test_match_event_listeners_resource_view(self): """ Test url matching for single event_listener """ url = '/v2/events/12345/' url_name = 'event_resource' assert_url_match(url, url_name, event_listener_id='12345') class TestDjangoUsersUrls(unittest.TestCase): """ Tests for userss urls """ def test_match_users_view(self): """ Test url matching for users """ url = '/v2/users/' url_name = 'users' assert_url_match(url, url_name) def test_match_user_search_view(self): """ Test url matching for user search. """ url = '/v2/users/search/' url_name = 'user_search' assert_url_match(url, url_name) def test_match_user_resource(self): """ Test the matching for user resource. """ url = '/v2/users/user_login/' url_name = 'user_resource' assert_url_match(url, url_name, login='user_login') class TestStatusUrl(unittest.TestCase): """ Tests for server status url """ def test_match_status_view(self): """ Test url matching for status """ url = '/v2/status/' url_name = 'status' assert_url_match(url, url_name) class TestDjangoConsumersUrls(unittest.TestCase): """ Tests for consumers urls """ def test_match_consumers_view(self): """ Test url matching for consumer """ url = '/v2/consumers/' url_name = 'consumers' assert_url_match(url, url_name) def test_match_consumer_search(self): """ Test url matching for consumer_search. """ url = '/v2/consumers/search/' url_name = 'consumer_search' assert_url_match(url, url_name) def test_match_consumer_resource_view(self): """ Test url matching for consumer resource. """ url = '/v2/consumers/test-consumer/' url_name = 'consumer_resource' assert_url_match(url, url_name, consumer_id='test-consumer') def test_match_consumer_search_view(self): """ Test url matching for consumer search. """ url = '/v2/consumers/search/' url_name = 'consumer_search' assert_url_match(url, url_name) def test_match_consumer_binding_search_view(self): """ Test url matching for consumer binding search. """ url = '/v2/consumers/binding/search/' url_name = 'consumer_binding_search' assert_url_match(url, url_name) def test_match_consumer_profile_search_view(self): """ Test url matching for consumer profile search. """ url = '/v2/consumers/profile/search/' url_name = 'consumer_profile_search' assert_url_match(url, url_name) def test_match_consumer_profiles_view(self): """ Test url matching for consumer profiles """ url = '/v2/consumers/test-consumer/profiles/' url_name = 'consumer_profiles' assert_url_match(url, url_name, consumer_id='test-consumer') def test_match_consumer_profile_resource_view(self): """ Test url matching for consumer profile resource """ url = '/v2/consumers/test-consumer/profiles/some-profile/' url_name = 'consumer_profile_resource' assert_url_match(url, url_name, consumer_id='test-consumer', content_type='some-profile') def test_match_consumer_bindings_view(self): """ Test url matching for consumer bindings """ url = '/v2/consumers/test-consumer/bindings/' url_name = 'bindings' assert_url_match(url, url_name, consumer_id='test-consumer') def test_match_consumer_binding_resource_view(self): """ Test url matching for consumer binding resource """ url = '/v2/consumers/test-consumer/bindings/some-repo/some-dist/' url_name = 'consumer_binding_resource' assert_url_match(url, url_name, consumer_id='test-consumer', repo_id='some-repo', distributor_id='some-dist') def test_match_consumer_binding_repo_view(self): """ Test url matching for consumer and repo binding """ url = '/v2/consumers/test-consumer/bindings/some-repo/' url_name = 'bindings_repo' assert_url_match(url, url_name, consumer_id='test-consumer', repo_id='some-repo') def test_match_consumer_appicability_regen_view(self): """ Test url matching for consumer applicability renegeration """ url = '/v2/consumers/test-consumer/actions/content/regenerate_applicability/' url_name = 'consumer_appl_regen' assert_url_match(url, url_name, consumer_id='test-consumer') def test_match_consumer_content_action_install_view(self): """ Test url matching for consumer content installation """ url = '/v2/consumers/test-consumer/actions/content/install/' url_name = 'consumer_content' assert_url_match(url, url_name, consumer_id='test-consumer', action='install') def test_match_consumer_content_action_update_view(self): """ Test url matching for consumer content update """ url = '/v2/consumers/test-consumer/actions/content/update/' url_name = 'consumer_content' assert_url_match(url, url_name, consumer_id='test-consumer', action='update') def test_match_consumer_content_action_uninstall_view(self): """ Test url matching for consumer content uninstall """ url = '/v2/consumers/test-consumer/actions/content/uninstall/' url_name = 'consumer_content' assert_url_match(url, url_name, consumer_id='test-consumer', action='uninstall') def test_match_consumers_appicability_regen_view(self): """ Test url matching for consumers applicability renegeration """ url = '/v2/consumers/actions/content/regenerate_applicability/' url_name = 'appl_regen' assert_url_match(url, url_name) def test_match_consumer_query_appicability_view(self): """ Test url matching for consumer query applicability """ url = '/v2/consumers/content/applicability/' url_name = 'consumer_query_appl' assert_url_match(url, url_name) def test_match_consumer_schedule_content_action_install_view(self): """ Test url matching for consumer schedule content installation """ url = '/v2/consumers/test-consumer/schedules/content/install/' url_name = 'schedule_content_install' assert_url_match(url, url_name, consumer_id='test-consumer') def test_match_consumer_schedule_content_action_update_view(self): """ Test url matching for consumer schedule content update """ url = '/v2/consumers/test-consumer/schedules/content/update/' url_name = 'schedule_content_update' assert_url_match(url, url_name, consumer_id='test-consumer') def test_match_consumer_schedule_content_action_uninstall_view(self): """ Test url matching for consumer schedule content uninstall """ url = '/v2/consumers/test-consumer/schedules/content/uninstall/' url_name = 'schedule_content_uninstall' assert_url_match(url, url_name, consumer_id='test-consumer') def test_match_consumer_schedule_content_action_install_resource_view(self): """ Test url matching for consumer schedule content resource installation """ url = '/v2/consumers/test-consumer/schedules/content/install/12345/' url_name = 'schedule_content_install_resource' assert_url_match(url, url_name, consumer_id='test-consumer', schedule_id='12345') def test_match_consumer_schedule_content_action_update_resource_view(self): """ Test url matching for consumer schedule content resource update """ url = '/v2/consumers/test-consumer/schedules/content/update/12345/' url_name = 'schedule_content_update_resource' assert_url_match(url, url_name, consumer_id='test-consumer', schedule_id='12345') def test_match_consumer_schedule_content_action_uninstall_resource_view(self): """ Test url matching for consumer schedule content resource uninstall """ url = '/v2/consumers/test-consumer/schedules/content/uninstall/12345/' url_name = 'schedule_content_uninstall_resource' assert_url_match(url, url_name, consumer_id='test-consumer', schedule_id='12345') def test_match_consumer_history_view(self): """ Test url matching for consumer history """ url = '/v2/consumers/test-consumer/history/' url_name = 'consumer_history' assert_url_match(url, url_name, consumer_id='test-consumer') class TestDjangoContentSourcesUrls(unittest.TestCase): """ Tests for content sources. """ def test_match_content_sources_view(self): """ Test url matching for content sources. """ url = '/v2/content/sources/' url_name = 'content_sources' assert_url_match(url, url_name) def test_match_content_sources_resource(self): """ Test the matching for content sources resource. """ url = '/v2/content/sources/some-source/' url_name = 'content_sources_resource' assert_url_match(url, url_name, source_id='some-source') def test_match_content_sources_refresh_view(self): """ Test url matching for content sources refresh. """ url = '/v2/content/sources/action/refresh/' url_name = 'content_sources_action' assert_url_match(url, url_name, action='refresh') def test_match_content_sources_resource_refresh(self): """ Test the matching for content sources resource refresh. """ url = '/v2/content/sources/some-source/action/refresh/' url_name = 'content_sources_resource_action' assert_url_match(url, url_name, source_id='some-source', action='refresh')<|fim▁end|>
url = '/v2/repositories/mock_repo/distributors/'\ 'mock_distributor/schedules/publish/mock_schedule/'
<|file_name|>generic_modulator.py<|end_file_name|><|fim▁begin|>import numpy as np import fir_filter import gauss_pulse import comms_filters class generic_modulator: def __init__(self, modulation_type, samples_per_symbol, pulse_factor, pulse_length, config): """ Create the generic modulator object and specify the modulation parameters. Supported modulation types are: BPSK GMSK QPSK OQPSK 8PSK 8APSK 16APSK 32APSK 64APSK 128APSK 256APSK """ # save the input parameters internally self.modulation_type = modulation_type self.samples_per_symbol = samples_per_symbol self.pulse_factor = pulse_factor self.pulse_length = pulse_length self.config = config # set the spectral density and offset characteristics if self.modulation_type == "BPSK": self.spectral_density = 2 self.period_offset = 0 elif self.modulation_type == "GMSK": self.spectral_density = 2 self.period_offset = 1 elif self.modulation_type == "QPSK": self.spectral_density = 4 self.period_offset = 0 elif self.modulation_type == "OQPSK": self.spectral_density = 4 self.period_offset = 1 elif self.modulation_type == "8PSK": self.spectral_density = 8 self.period_offset = 0 elif self.modulation_type == "8APSK": self.spectral_density = 8 self.period_offset = 0 elif self.modulation_type == "16APSK": self.spectral_density = 16 self.period_offset = 0 elif self.modulation_type == "32APSK": self.spectral_density = 32 self.period_offset = 0 elif self.modulation_type == "64APSK": self.spectral_density = 64 self.period_offset = 0 elif self.modulation_type == "128APSK": self.spectral_density = 128 self.period_offset = 0 elif self.modulation_type == "256APSK": self.spectral_density = 256 self.period_offset = 0 else: assert False, "Unsupported modulation type supplied." # create the pulse coefficients if(self.modulation_type == "GMSK"): self.pulse_coefficients = gauss_pulse.gauss_pulse( sps = 2*self.samples_per_symbol, BT = self.pulse_factor) else: self.pulse_coefficients = comms_filters.rrcosfilter(N = self.pulse_length*self.samples_per_symbol, alpha = self.pulse_factor, Ts = 1, Fs = self.samples_per_symbol)[1] # normalise the pulse energy pulse_energy = np.sum(np.square(abs(self.pulse_coefficients)))/self.samples_per_symbol self.pulse_coefficients = [_/pulse_energy for _ in self.pulse_coefficients] self.pulse_coefficients = np.append(self.pulse_coefficients, self.pulse_coefficients[0]) def modulate(self, data, carrier_phase_offset): """ Modulate the supplied data with the previously setup modulator """ # deinterleave, convert to NRZ and interpolate if self.modulation_type == "BPSK": # determine the number of samples number_of_bits = len(data) number_of_samples = number_of_bits*self.samples_per_symbol # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # loop through each sample modulate the in-phase arm for n in range(number_of_bits): i_data[n*self.samples_per_symbol] = 2*data[n]-1 # the quadrature arm is all zeros q_data = np.zeros(number_of_samples) # essentially OQPSK with half the frequency elif self.modulation_type == "GMSK": # determine the number of samples number_of_bits = len(data) number_of_samples = number_of_bits*self.samples_per_symbol # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # modulate two bit period with data for n in range(number_of_bits/2): i_data[2*n*self.samples_per_symbol] = 2*data[2*n]-1 # module two bit periods offset by a bit period with data for n in range(number_of_bits/2-1): q_data[2*n*self.samples_per_symbol + self.samples_per_symbol/2] = 2*data[2*n+1]-1 # map the signal to four constellation points on the complex plane elif self.modulation_type == "QPSK": # determine the number of samples number_of_bits = len(data) number_of_samples = number_of_bits*self.samples_per_symbol/2 # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # map every odd bit to the in-phase arm for n in range(number_of_bits/2): i_data[n*self.samples_per_symbol] = 2*data[2*n]-1 # map every even bit to the quadarature arm for n in range(number_of_bits/2): q_data[n*self.samples_per_symbol] = 2*data[2*n+1]-1 # like QPSK with a half bit period offset on the quadarature arm elif self.modulation_type == "OQPSK": # determine the number of samples number_of_bits = len(data) number_of_samples = number_of_bits*self.samples_per_symbol/2 # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # map every odd bit to the in-phase arm for n in range(number_of_bits/2): i_data[n*self.samples_per_symbol] = 2*data[2*n]-1 # map every even bit to the quadarature arm with a half bit period offset for n in range(number_of_bits/2-1): q_data[n*self.samples_per_symbol + self.samples_per_symbol/2] = 2*data[2*n+1]-1 # split three bits across a even eight point on the circle # according to EN 302 307-1 elif self.modulation_type == "8PSK": # determine the number of samples bits_per_symbol = 3 number_of_bits = len(data) number_of_samples = int(np.ceil(number_of_bits*self.samples_per_symbol/bits_per_symbol)) # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # set the bit mapping table bit_map = [[1, np.pi/4], [1, 0], [1, 4*np.pi/4], [1, 5*np.pi/4], [1, 2*np.pi/4], [1, 7*np.pi/4], [1, 3*np.pi/4], [1, 6*np.pi/4]] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int][0] * np.exp(1j*bit_map[symbol_int][1]) # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) # split three bits across a complex amplitudde and phase mapping elif self.modulation_type == "8APSK": # determine the number of samples bits_per_symbol = 3 number_of_bits = len(data) number_of_samples = int(np.ceil(number_of_bits*self.samples_per_symbol/bits_per_symbol)) # prepopulate the output vector i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # different mapping for different LDPC codes # calculate the symbol radiuses if self.config == "100/180": R1 = 1.0/6.8 R2 = 5.32/6.8 elif self.config == "104/180": R1 = 1.0/8.0 R2 = 6.39/8.0 else: print("No LDPC code specified. Using 100/180") R1 = 1.0/6.8 R2 = 5.32/6.8 # set the bit mapping table bit_map = [[R1, 0], [R2, 1.352*np.pi], [R2, 0.648*np.pi], [1.0, 0], [R1, np.pi], [R2, -0.352*np.pi], [R2, 0.352*np.pi], [1.0, np.pi]] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int][0] * np.exp(1j*bit_map[symbol_int][1]) # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) # split four bits across a complex amplitudde and phase mapping elif self.modulation_type == "16APSK": # determine the number of samples bits_per_symbol = 4 number_of_bits = len(data) number_of_samples = int(np.ceil(number_of_bits*self.samples_per_symbol/bits_per_symbol)) # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # for some codes the mapping is performed with a lookup table if self.config in ["18/30", "20/30"]: if self.config == "18/30": # map values to symbols on the complex plane bit_map = [0.4718 + 0.2606*1j, 0.2606 + 0.4718*1j, -0.4718 + 0.2606*1j, -0.2606 + 0.4718*1j, 0.4718 - 0.2606*1j, 0.2606 - 0.4718*1j, -0.4718 - 0.2606*1j, -0.2606 - 0.4718*1j, 1.2088 + 0.4984*1j, 0.4984 + 1.2088*1j, -1.2088 + 0.4984*1j, -0.4984 + 1.2088*1j, 1.2088 - 0.4984*1j, 0.4984 - 1.2088*1j, -1.2088 - 0.4984*1j, -0.4984 - 1.2088*1j] elif self.config == "20/30": # map values to symbols on the complex plane bit_map = [0.5061 + 0.2474*1j, 0.2474 + 0.5061*1j, -0.5061 + 0.2474*1j, -0.2474 + 0.5061*1j, 0.5061 - 0.2474*1j, 0.2474 - 0.5061*1j, -0.5061 - 0.2474*1j, -0.2474 - 0.5061*1j, 1.2007 + 0.4909*1j, 0.4909 + 1.2007*1j, -1.2007 + 0.4909*1j, -0.4909 + 1.2007*1j, 1.2007 - 0.4909*1j, 0.4909 - 1.2007*1j, -1.2007 - 0.4909*1j, -0.4909 - 1.2007*1j] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int] # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) else: # 8 + 8 modulation if self.config in ["90/180", "96/180", "100/180"]: # all of these codes use the same R1 radius R1 = 1.0/3.7 # set the bit mapping table bit_map = [[R1, 1*np.pi/8], [R1, 3*np.pi/8], [R1, 7*np.pi/8], [R1, 5*np.pi/8], [R1, 15*np.pi/8], [R1, 13*np.pi/8], [R1, 9*np.pi/8], [R1, 11*np.pi/8], [1.0, 1*np.pi/8], [1.0, 3*np.pi/8], [1.0, 7*np.pi/8], [1.0, 5*np.pi/8], [1.0, 15*np.pi/8], [1.0, 13*np.pi/8], [1.0, 9*np.pi/8], [1.0, 11*np.pi/8]] # 4 + 12 modulation else: # different mapping for different LDPC codes # calculate the symbol radiuses if self.config == "26/45": R1 = 1.0/3.7 elif self.config == "3/5": R1 = 1.0/3.7 elif self.config == "28/45": R1 = 1.0/3.5 elif self.config == "23/36": R1 = 1.0/3.1 elif self.config == "25/36": R1 = 1.0/3.1 elif self.config == "13/18": R1 = 1.0/2.85 elif self.config == "140/180": R1 = 1.0/3.6 elif self.config == "154/180": R1 = 1.0/3.2 elif self.config == "7/15": R1 = 1.0/3.32 elif self.config == "8/15": R1 = 1.0/3.5 elif self.config == "26/45": R1 = 1.0/3.7 elif self.config == "3/5": R1 = 1.0/3.7 elif self.config == "32/45": R1 = 1.0/2.85 else: print("No LDPC code specified. Using 3/5") R1 = 1.0/3.7 # set the bit mapping table bit_map = [[1.0, 3*np.pi/12], [1.0, 21*np.pi/12], [1.0, 9*np.pi/12], [1.0, 15*np.pi/12], [1.0, 1*np.pi/12], [1.0, 23*np.pi/12], [1.0, 11*np.pi/12], [1.0, 13*np.pi/12], [1.0, 5*np.pi/12], [1.0, 19*np.pi/12], [1.0, 7*np.pi/12], [1.0, 17*np.pi/12], [R1, 3*np.pi/12], [R1, 21*np.pi/12], [R1, 9*np.pi/12], [R1, 15*np.pi/12]] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int][0] * np.exp(1j*bit_map[symbol_int][1]) # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) # split five bits across a complex amplitudde and phase mapping elif self.modulation_type == "32APSK": # determine the number of samples bits_per_symbol = 5 number_of_bits = len(data) number_of_samples = int(np.ceil(number_of_bits*self.samples_per_symbol/bits_per_symbol)) # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) if self.config in ["2/3", "2/3S", "32/45S"]: # different mapping for different LDPC codes # calculate the symbol radiuses if self.config == "2/3": R1 = 1.0/5.55 R2 = 2.85/5.55 elif self.config == "2/3S": R1 = 1.0/5.54 R2 = 2.84/5.54 elif self.config == "32/45S": R1 = 1.0/5.26 R2 = 2.84/5.26 # set the bit mapping table bit_map = [[1, 11*np.pi/16], [1, 9*np.pi/16], [1, 5*np.pi/16], [1, 7*np.pi/16], [R2, 9*np.pi/12], [R2, 7*np.pi/12], [R2, 3*np.pi/12], [R2, 5*np.pi/12], [1, 13*np.pi/16], [1, 15*np.pi/16], [1, 3*np.pi/16], [1, 1*np.pi/16], [R2, 11*np.pi/12], [R1, 3*np.pi/4], [R2, 1*np.pi/12], [R1, 1*np.pi/4], [1, 21*np.pi/16], [1, 23*np.pi/16], [1, 27*np.pi/16], [1, 25*np.pi/16], [R2, 15*np.pi/12], [R2, 17*np.pi/12], [R2, 21*np.pi/12], [R2, 19*np.pi/12], [1, 19*np.pi/16], [1, 17*np.pi/16], [1, 29*np.pi/16], [1, 31*np.pi/16], [R2, 13*np.pi/12], [R1, 5*np.pi/4], [R2, 23*np.pi/12], [R1, 7*np.pi/4]] else: # different mapping for different LDPC codes # calculate the symbol radiuses if self.config == "128/180": R1 = 1.0/5.6 R2 = 2.6/5.6 R3 = 2.99/5.6 elif self.config == "132/180": R1 = 1/5.6 R2 = 2.6/5.6 R3 = 2.86/5.6 elif self.config == "140/180": R1 = 1/5.6 R2 = 2.8/5.6 R3 = 3.08/5.6 else: print("No LDPC code specified. Using 128/180") R1 = 1/5.6 R2 = 2.6/5.6 R3 = 2.99/5.6 # set the bit mapping table bit_map = [[R1, 1*np.pi/4], [1.0, 7*np.pi/16], [R1, 7*np.pi/4], [1.0, 25*np.pi/16], [R1, 3*np.pi/4], [1.0, 9*np.pi/16], [R1, 5*np.pi/4], [1.0, 23*np.pi/16], [R2, 1*np.pi/12], [1.0, 1*np.pi/16], [R2, 23*np.pi/12], [1.0, 31*np.pi/16], [R2, 11*np.pi/12], [1.0, 15*np.pi/16], [R2, 13*np.pi/12], [1.0, 17*np.pi/16], [R2, 5*np.pi/12], [1.0, 5*np.pi/16], [R2, 19*np.pi/12], [1.0, 27*np.pi/16], [R2, 7*np.pi/12], [1.0, 11*np.pi/16], [R2, 17*np.pi/12], [1.0, 21*np.pi/16], [R3, 1*np.pi/4], [1.0, 3*np.pi/16], [R3, 7*np.pi/4], [1.0, 29*np.pi/16], [R3, 3*np.pi/4], [1.0, 13*np.pi/16], [R3, 5*np.pi/4], [1.0, 19*np.pi/16]] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int][0] * np.exp(1j*bit_map[symbol_int][1]) # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) # split six bits across a complex amplitudde and phase mapping elif self.modulation_type == "64APSK": # determine the number of samples bits_per_symbol = 6 number_of_bits = len(data) number_of_samples = int(np.ceil(number_of_bits*self.samples_per_symbol/bits_per_symbol)) # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) if self.config in ["128/180"]: # different mapping for different LDPC codes # calculate the symbol radiuses R1 = 1.0/3.95 R2 = 1.88/3.95 R3 = 2.72/3.95 R4 = 1.0 # set the bit mapping table bit_map = [R1, 1*np.pi/16, R1, 3*np.pi/16, R1, 7*np.pi/16, R1, 5*np.pi/16, R1, 15*np.pi/16, R1, 13*np.pi/16, R1, 9*np.pi/16, R1, 11*np.pi/16, R1, 31*np.pi/16, R1, 29*np.pi/16, R1, 25*np.pi/16, R1, 27*np.pi/16, R1, 17*np.pi/16, R1, 19*np.pi/16, R1, 23*np.pi/16, R1, 21*np.pi/16, R2, 1*np.pi/16, R2, 3*np.pi/16, R2, 7*np.pi/16, R2, 5*np.pi/16, R2, 15*np.pi/16, R2, 13*np.pi/16, R2, 9*np.pi/16, R2, 11*np.pi/16, R2, 31*np.pi/16, R2, 29*np.pi/16, R2, 25*np.pi/16, R2, 27*np.pi/16, R2, 17*np.pi/16, R2, 19*np.pi/16, R2, 23*np.pi/16, R2, 21*np.pi/16, R4, 1*np.pi/16, R4, 3*np.pi/16, R4, 7*np.pi/16, R4, 5*np.pi/16, R4, 15*np.pi/16, R4, 13*np.pi/16, R4, 9*np.pi/16, R4, 11*np.pi/16, R4, 31*np.pi/16, R4, 29*np.pi/16, R4, 25*np.pi/16, R4, 27*np.pi/16, R4, 17*np.pi/16, R4, 19*np.pi/16, R4, 23*np.pi/16, R4, 21*np.pi/16, R3, 1*np.pi/16, R3, 3*np.pi/16, R3, 7*np.pi/16, R3, 5*np.pi/16, R3, 15*np.pi/16, R3, 13*np.pi/16, R3, 9*np.pi/16, R3, 11*np.pi/16, R3, 31*np.pi/16, R3, 29*np.pi/16, R3, 25*np.pi/16, R3, 27*np.pi/16, R3, 17*np.pi/16, R3, 19*np.pi/16, R3, 23*np.pi/16, R3, 21*np.pi/16] elif self.config in ["7/9", "4/5", "5/6"]: # different mapping for different LDPC codes # calculate the symbol radiuses if self.config == "7/9": R1 = 1.0/5.2 R2 = 2.2/5.2 R3 = 3.6/5.2 R4 = 1.0 elif self.config == "4/5": R1 = 1.0/5.2 R2 = 2.2/5.2 R3 = 3.6/5.2 R4 = 1.0 elif self.config == "5/6": R1 = 1.0/5.0 R2 = 2.2/5.0 R3 = 3.5/5.0 R4 = 1.0 # set the bit mapping table bit_map = [R2, 25*np.pi/16, R4, 7*np.pi/4, R2, 27*np.pi/16, R3, 7*np.pi/4, R4, 31*np.pi/20, R4, 33*np.pi/20, R3, 31*np.pi/20, R3, 33*np.pi/20, R2, 23*np.pi/16, R4, 5*np.pi/4, R2, 21*np.pi/16, R3, 5*np.pi/4, R4, 29*np.pi/20, R4, 27*np.pi/20, R3, 29*np.pi/20, R3, 27*np.pi/20, R1, 13*np.pi/8, R4, 37*np.pi/20, R2, 29*np.pi/16, R3, 37*np.pi/20, R1, 15*np.pi/8, R4, 39*np.pi/20, R2, 31*np.pi/16, R3, 39*np.pi/20, R1, 11*np.pi/8, R4, 23*np.pi/20, R2, 19*np.pi/16, R3, 23*np.pi/20, R1, 9*np.pi/8, R4, 21*np.pi/20, R2, 17*np.pi/16, R3, 21*np.pi/20, R2, 7*np.pi/6, R4, 1*np.pi/4, R2, 5*np.pi/6, R3, 1*np.pi/4, R4, 9*np.pi/0, R4, 7*np.pi/0, R3, 9*np.pi/0, R3, 7*np.pi/0, R2, 9*np.pi/6, R4, 3*np.pi/4, R2, 11*np.pi/16, R3, 3*np.pi/4, R4, 11*np.pi/20, R4, 13*np.pi/20, R3, 11*np.pi/20, R3, 13*np.pi/20, R1, 3*np.pi/8, R4, 3*np.pi/0, R2, 3*np.pi/6, R3, 3*np.pi/0, R1, 1*np.pi/8, R4, 1*np.pi/0, R2, 1*np.pi/6, R3, 1*np.pi/0, R1, 5*np.pi/8, R4, 17*np.pi/20, R2, 13*np.pi/16, R3, 17*np.pi/20, R1, 7*np.pi/8, R4, 19*np.pi/20, R2, 15*np.pi/16, R3, 19*np.pi/20] <|fim▁hole|> # calculate the symbol radiuses R1 = 1.0/7.0 R2 = 2.4/7.0 R3 = 4.3/7.0 R4 = 1.0 # set the bit mapping table bit_map = [R4, 1*np.pi/4, R4, 7*np.pi/4, R4, 3*np.pi/4, R4, 5*np.pi/4, R4, 13*np.pi/28, R4, 43*np.pi/28, R4, 15*np.pi/28, R4, 41*np.pi/28, R4, 1*np.pi/8, R4, 55*np.pi/28, R4, 27*np.pi/28, R4, 29*np.pi/28, R1, 1*np.pi/4, R1, 7*np.pi/4, R1, 3*np.pi/4, R1, 5*np.pi/4, R4, 9*np.pi/8, R4, 47*np.pi/28, R4, 19*np.pi/28, R4, 37*np.pi/28, R4, 11*np.pi/28, R4, 45*np.pi/28, R4, 17*np.pi/28, R4, 39*np.pi/28, R3, 1*np.pi/0, R3, 39*np.pi/20, R3, 19*np.pi/20, R3, 21*np.pi/20, R2, 1*np.pi/2, R2, 23*np.pi/12, R2, 11*np.pi/12, R2, 13*np.pi/12, R4, 5*np.pi/8, R4, 51*np.pi/28, R4, 23*np.pi/28, R4, 33*np.pi/28, R3, 9*np.pi/0, R3, 31*np.pi/20, R3, 11*np.pi/20, R3, 29*np.pi/20, R4, 3*np.pi/8, R4, 53*np.pi/28, R4, 25*np.pi/28, R4, 31*np.pi/28, R2, 9*np.pi/0, R2, 19*np.pi/12, R2, 7*np.pi/2, R2, 17*np.pi/12, R3, 1*np.pi/4, R3, 7*np.pi/4, R3, 3*np.pi/4, R3, 5*np.pi/4, R3, 7*np.pi/0, R3, 33*np.pi/20, R3, 13*np.pi/20, R3, 27*np.pi/20, R3, 3*np.pi/0, R3, 37*np.pi/20, R3, 17*np.pi/20, R3, 23*np.pi/20, R2, 1*np.pi/4, R2, 7*np.pi/4, R2, 3*np.pi/4, R2, 5*np.pi/4] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int][0] * np.exp(1j*bit_map[symbol_int][1]) # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) # split seven bits across a complex amplitudde and phase mapping elif self.modulation_type == "128APSK": # determine the number of samples bits_per_symbol = 7 number_of_bits = len(data) number_of_samples = int(np.ceil(number_of_bits*self.samples_per_symbol/bits_per_symbol)) # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # select the LDPC codes if self.config in ["135/180", "140/180"]: # different mapping for different LDPC codes # calculate the symbol radiuses R1 = 1.0/3.819 R2 = 1.715/3.819 R3 = 2.118/3.819 R4 = 2.681/3.819 R5 = 2.75/3.819 R6 = 1.0 # set the bit mapping table bit_map = [R1, 83*np.pi/60, R6, 11*np.pi/05, R6, 37*np.pi/80, R6, 11*np.pi/68, R2, 121*np.pi/520, R3, 23*np.pi/80, R5, 19*np.pi/20, R4, 61*np.pi/20, R1, 103*np.pi/560, R6, 61*np.pi/20, R6, 383*np.pi/680, R6, 61*np.pi/20, R2, 113*np.pi/560, R3, 169*np.pi/008, R5, 563*np.pi/520, R4, 139*np.pi/840, R1, 243*np.pi/560, R6, 1993*np.pi/5040, R6, 43*np.pi/90, R6, 73*np.pi/68, R2, 1139*np.pi/2520, R3, 117*np.pi/280, R5, 341*np.pi/720, R4, 349*np.pi/840, R1, 177*np.pi/560, R6, 1789*np.pi/5040, R6, 49*np.pi/80, R6, 1789*np.pi/5040, R2, 167*np.pi/560, R3, 239*np.pi/720, R5, 199*np.pi/720, R4, 281*np.pi/840, R1, 1177*np.pi/1260, R6, 94*np.pi/05, R6, 1643*np.pi/1680, R6, 157*np.pi/168, R2, 2399*np.pi/2520, R3, 257*np.pi/280, R5, 701*np.pi/720, R4, 659*np.pi/720, R1, 457*np.pi/560, R6, 359*np.pi/420, R6, 1297*np.pi/1680, R6, 4111*np.pi/5040, R2, 447*np.pi/560, R3, 839*np.pi/008, R5, 1957*np.pi/2520, R4, 701*np.pi/840, R1, 317*np.pi/560, R6, 3047*np.pi/5040, R6, 47*np.pi/90, R6, 95*np.pi/68, R2, 1381*np.pi/2520, R3, 163*np.pi/280, R5, 379*np.pi/720, R4, 491*np.pi/840, R1, 383*np.pi/560, R6, 3251*np.pi/5040, R6, 131*np.pi/180, R6, 115*np.pi/168, R2, 393*np.pi/560, R3, 481*np.pi/720, R5, 521*np.pi/720, R4, 559*np.pi/840, R1, 2437*np.pi/1260, R6, 199*np.pi/105, R6, 3323*np.pi/1680, R6, 325*np.pi/168, R2, 4919*np.pi/2520, R3, 537*np.pi/280, R5, 1421*np.pi/720, R4, 1379*np.pi/720, R1, 1017*np.pi/560, R6, 779*np.pi/420, R6, 2977*np.pi/1680, R6, 9151*np.pi/5040, R2, 1007*np.pi/560, R3, 1847*np.pi/1008, R5, 4477*np.pi/2520, R4, 1541*np.pi/840, R1, 877*np.pi/560, R6, 8087*np.pi/5040, R6, 137*np.pi/90, R6, 263*np.pi/168, R2, 3901*np.pi/2520, R3, 443*np.pi/280, R5, 1099*np.pi/720, R4, 1331*np.pi/840, R1, 943*np.pi/560, R6, 8291*np.pi/5040, R6, 311*np.pi/180, R6, 283*np.pi/168, R2, 953*np.pi/560, R3, 1201*np.pi/720, R5, 1241*np.pi/720, R4, 1399*np.pi/840, R1, 1343*np.pi/1260, R6, 116*np.pi/105, R6, 1717*np.pi/1680, R6, 179*np.pi/168, R2, 2641*np.pi/2520, R3, 303*np.pi/280, R5, 739*np.pi/720, R4, 781*np.pi/720, R1, 663*np.pi/560, R6, 481*np.pi/420, R6, 2063*np.pi/1680, R6, 5969*np.pi/5040, R2, 673*np.pi/560, R3, 1177*np.pi/1008, R5, 3083*np.pi/2520, R4, 979*np.pi/840, R1, 803*np.pi/560, R6, 7033*np.pi/5040, R6, 133*np.pi/90, R6, 241*np.pi/168, R2, 3659*np.pi/2520, R3, 397*np.pi/280, R5, 1061*np.pi/720, R4, 1189*np.pi/840, R1, 737*np.pi/560, R6, 6829*np.pi/5040, R6, 229*np.pi/180, R6, 221*np.pi/168, R2, 727*np.pi/560, R3, 959*np.pi/720, R5, 919*np.pi/720, R4, 1121*np.pi/840] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int][0] * np.exp(1j*bit_map[symbol_int][1]) # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) # split eight bits across a complex amplitudde and phase mapping elif self.modulation_type == "256APSK": # determine the number of samples bits_per_symbol = 8 number_of_bits = len(data) number_of_samples = int(np.ceil(number_of_bits*self.samples_per_symbol/bits_per_symbol)) # prepopulate the output vectors i_data = np.zeros(number_of_samples) q_data = np.zeros(number_of_samples) # select the coding based on the LDPC code if self.config in ["116/180", "124/180", "128/180", "135/180"]: # different mapping for different LDPC codes # calculate the symbol radiuses if self.config in ["116/180", "124/180"]: R1 = 1.0/6.536 R2 = 1.791/6.536 R3 = 2.405/6.536 R4 = 2.980/6.536 R5 = 3.569/6.536 R6 = 4.235/6.536 R7 = 5.078/6.536 R8 = 1.0 elif self.config == "128/180": R1 = 1.0/5.4 R2 = 1.794/5.4 R3 = 2.409/5.4 R4 = 2.986/5.4 R5 = 3.579/5.4 R6 = 4.045/5.4 R7 = 4.6/5.4 R8 = 1.0 else: R1 = 1.0/5.2 R2 = 1.794/5.2 R3 = 2.409/5.2 R4 = 2.986/5.2 R5 = 3.579/5.2 R6 = 4.045/5.2 R7 = 4.5/5.2 R8 = 1.0 # set the bit mapping table bit_map = [R1, 1*np.pi/32, R1, 3*np.pi/32, R1, 7*np.pi/32, R1, 5*np.pi/32, R1, 15*np.pi/32, R1, 13*np.pi/32, R1, 9*np.pi/32, R1, 11*np.pi/32, R1, 31*np.pi/32, R1, 29*np.pi/32, R1, 25*np.pi/32, R1, 27*np.pi/32, R1, 17*np.pi/32, R1, 19*np.pi/32, R1, 23*np.pi/32, R1, 21*np.pi/32, R1, 63*np.pi/32, R1, 61*np.pi/32, R1, 57*np.pi/32, R1, 59*np.pi/32, R1, 49*np.pi/32, R1, 51*np.pi/32, R1, 55*np.pi/32, R1, 53*np.pi/32, R1, 33*np.pi/32, R1, 35*np.pi/32, R1, 39*np.pi/32, R1, 37*np.pi/32, R1, 47*np.pi/32, R1, 45*np.pi/32, R1, 41*np.pi/32, R1, 43*np.pi/32, R2, 1*np.pi/32, R2, 3*np.pi/32, R2, 7*np.pi/32, R2, 5*np.pi/32, R2, 15*np.pi/32, R2, 13*np.pi/32, R2, 9*np.pi/32, R2, 11*np.pi/32, R2, 31*np.pi/32, R2, 29*np.pi/32, R2, 25*np.pi/32, R2, 27*np.pi/32, R2, 17*np.pi/32, R2, 19*np.pi/32, R2, 23*np.pi/32, R2, 21*np.pi/32, R2, 63*np.pi/32, R2, 61*np.pi/32, R2, 57*np.pi/32, R2, 59*np.pi/32, R2, 49*np.pi/32, R2, 51*np.pi/32, R2, 55*np.pi/32, R2, 53*np.pi/32, R2, 33*np.pi/32, R2, 35*np.pi/32, R2, 39*np.pi/32, R2, 37*np.pi/32, R2, 47*np.pi/32, R2, 45*np.pi/32, R2, 41*np.pi/32, R2, 43*np.pi/32, R4, 1*np.pi/32, R4, 3*np.pi/32, R4, 7*np.pi/32, R4, 5*np.pi/32, R4, 15*np.pi/32, R4, 13*np.pi/32, R4, 9*np.pi/32, R4, 11*np.pi/32, R4, 31*np.pi/32, R4, 29*np.pi/32, R4, 25*np.pi/32, R4, 27*np.pi/32, R4, 17*np.pi/32, R4, 19*np.pi/32, R4, 23*np.pi/32, R4, 21*np.pi/32, R4, 63*np.pi/32, R4, 61*np.pi/32, R4, 57*np.pi/32, R4, 59*np.pi/32, R4, 49*np.pi/32, R4, 51*np.pi/32, R4, 55*np.pi/32, R4, 53*np.pi/32, R4, 33*np.pi/32, R4, 35*np.pi/32, R4, 39*np.pi/32, R4, 37*np.pi/32, R4, 47*np.pi/32, R4, 45*np.pi/32, R4, 41*np.pi/32, R4, 43*np.pi/32, R3, 1*np.pi/32, R3, 3*np.pi/32, R3, 7*np.pi/32, R3, 5*np.pi/32, R3, 15*np.pi/32, R3, 13*np.pi/32, R3, 9*np.pi/32, R3, 11*np.pi/32, R3, 31*np.pi/32, R3, 29*np.pi/32, R3, 25*np.pi/32, R3, 27*np.pi/32, R3, 17*np.pi/32, R3, 19*np.pi/32, R3, 23*np.pi/32, R3, 21*np.pi/32, R3, 63*np.pi/32, R3, 61*np.pi/32, R3, 57*np.pi/32, R3, 59*np.pi/32, R3, 49*np.pi/32, R3, 51*np.pi/32, R3, 55*np.pi/32, R3, 53*np.pi/32, R3, 33*np.pi/32, R3, 35*np.pi/32, R3, 39*np.pi/32, R3, 37*np.pi/32, R3, 47*np.pi/32, R3, 45*np.pi/32, R3, 41*np.pi/32, R3, 43*np.pi/32, R8, 1*np.pi/32, R8, 3*np.pi/32, R8, 7*np.pi/32, R8, 5*np.pi/32, R8, 15*np.pi/32, R8, 13*np.pi/32, R8, 9*np.pi/32, R8, 11*np.pi/32, R8, 31*np.pi/32, R8, 29*np.pi/32, R8, 25*np.pi/32, R8, 27*np.pi/32, R8, 17*np.pi/32, R8, 19*np.pi/32, R8, 23*np.pi/32, R8, 21*np.pi/32, R8, 63*np.pi/32, R8, 61*np.pi/32, R8, 57*np.pi/32, R8, 59*np.pi/32, R8, 49*np.pi/32, R8, 51*np.pi/32, R8, 55*np.pi/32, R8, 53*np.pi/32, R8, 33*np.pi/32, R8, 35*np.pi/32, R8, 39*np.pi/32, R8, 37*np.pi/32, R8, 47*np.pi/32, R8, 45*np.pi/32, R8, 41*np.pi/32, R8, 43*np.pi/32, R7, 1*np.pi/32, R7, 3*np.pi/32, R7, 7*np.pi/32, R7, 5*np.pi/32, R7, 15*np.pi/32, R7, 13*np.pi/32, R7, 9*np.pi/32, R7, 11*np.pi/32, R7, 31*np.pi/32, R7, 29*np.pi/32, R7, 25*np.pi/32, R7, 27*np.pi/32, R7, 17*np.pi/32, R7, 19*np.pi/32, R7, 23*np.pi/32, R7, 21*np.pi/32, R7, 63*np.pi/32, R7, 61*np.pi/32, R7, 57*np.pi/32, R7, 59*np.pi/32, R7, 49*np.pi/32, R7, 51*np.pi/32, R7, 55*np.pi/32, R7, 53*np.pi/32, R7, 33*np.pi/32, R7, 35*np.pi/32, R7, 39*np.pi/32, R7, 37*np.pi/32, R7, 47*np.pi/32, R7, 45*np.pi/32, R7, 41*np.pi/32, R7, 43*np.pi/32, R5, 1*np.pi/32, R5, 3*np.pi/32, R5, 7*np.pi/32, R5, 5*np.pi/32, R5, 15*np.pi/32, R5, 13*np.pi/32, R5, 9*np.pi/32, R5, 11*np.pi/32, R5, 31*np.pi/32, R5, 29*np.pi/32, R5, 25*np.pi/32, R5, 27*np.pi/32, R5, 17*np.pi/32, R5, 19*np.pi/32, R5, 23*np.pi/32, R5, 21*np.pi/32, R5, 63*np.pi/32, R5, 61*np.pi/32, R5, 57*np.pi/32, R5, 59*np.pi/32, R5, 49*np.pi/32, R5, 51*np.pi/32, R5, 55*np.pi/32, R5, 53*np.pi/32, R5, 33*np.pi/32, R5, 35*np.pi/32, R5, 39*np.pi/32, R5, 37*np.pi/32, R5, 47*np.pi/32, R5, 45*np.pi/32, R5, 41*np.pi/32, R5, 43*np.pi/32, R6, 1*np.pi/32, R6, 3*np.pi/32, R6, 7*np.pi/32, R6, 5*np.pi/32, R6, 15*np.pi/32, R6, 13*np.pi/32, R6, 9*np.pi/32, R6, 11*np.pi/32, R6, 31*np.pi/32, R6, 29*np.pi/32, R6, 25*np.pi/32, R6, 27*np.pi/32, R6, 17*np.pi/32, R6, 19*np.pi/32, R6, 23*np.pi/32, R6, 21*np.pi/32, R6, 63*np.pi/32, R6, 61*np.pi/32, R6, 57*np.pi/32, R6, 59*np.pi/32, R6, 49*np.pi/32, R6, 51*np.pi/32, R6, 55*np.pi/32, R6, 53*np.pi/32, R6, 33*np.pi/32, R6, 35*np.pi/32, R6, 39*np.pi/32, R6, 37*np.pi/32, R6, 47*np.pi/32, R6, 45*np.pi/32, R6, 41*np.pi/32, R6, 43*np.pi/32] # loop through all data for n in range(int(np.ceil(number_of_bits/bits_per_symbol))): # combine three bits and map to a complex symbol symbol_int = 0 for i in range(bits_per_symbol): symbol_int += 2**i * data[bits_per_symbol*n + i] symbol = bit_map[symbol_int][0] * np.exp(1j*bit_map[symbol_int][1]) # break apart the complex symbol to inphase and quadrature arms i_data[n*self.samples_per_symbol] = np.real(symbol) q_data[n*self.samples_per_symbol] = np.imag(symbol) # create the I and Q pulse filters i_filter = fir_filter.fir_filter(self.pulse_coefficients) q_filter = fir_filter.fir_filter(self.pulse_coefficients) # create output waveforms i_waveform = [] q_waveform = [] for n in range(len(i_data)): i_waveform.append( i_filter.update( i_data[n] ) ) q_waveform.append( q_filter.update( q_data[n] ) ) # create the complex signal and frequency offset waveform = [i_waveform[i] + 1j*q_waveform[i] for i in range(len(i_waveform))] waveform = [_*np.exp(-1j*carrier_phase_offset) for _ in waveform] # normalise the waveform waveform_max = max( np.abs(waveform) ) waveform = [_/waveform_max for _ in waveform] return waveform<|fim▁end|>
elif self.config in ["132/180"]: # different mapping for different LDPC codes
<|file_name|>templates.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- #-------------------------------------------------------------------- # Copyright (c) 2014 Eren Inan Canpolat # Author: Eren Inan Canpolat <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #-------------------------------------------------------------------- content_template = """<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> </body> </html>""" toc_ncx = u"""<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd"> <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"> <head> <meta name="dtb:uid" content="{book.uuid}" /> <meta name="dtb:depth" content="{book.toc_root.maxlevel}" /> <meta name="dtb:totalPageCount" content="0" /> <meta name="dtb:maxPageNumber" content="0" /> </head> <docTitle> <text>{book.title}</text> </docTitle> {navmap} </ncx>""" container_xml = """<?xml version="1.0" encoding="UTF-8" standalone="no"?> <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"> <rootfiles><|fim▁hole|></container> """<|fim▁end|>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/> </rootfiles>
<|file_name|>multiple_ranges_test.cc<|end_file_name|><|fim▁begin|>#include "benchmark/benchmark.h" #include <cassert> #include <set> class MultipleRangesFixture : public ::benchmark::Fixture { public: MultipleRangesFixture() : expectedValues({{1, 3, 5}, {1, 3, 8}, {1, 3, 15}, {2, 3, 5}, {2, 3, 8}, {2, 3, 15}, {1, 4, 5}, {1, 4, 8}, {1, 4, 15}, {2, 4, 5}, {2, 4, 8}, {2, 4, 15}, {1, 7, 5}, {1, 7, 8}, {1, 7, 15}, {2, 7, 5}, {2, 7, 8}, {2, 7, 15}, {7, 6, 3}}) {} void SetUp(const ::benchmark::State& state) { std::vector<int> ranges = {state.range(0), state.range(1), state.range(2)}; assert(expectedValues.find(ranges) != expectedValues.end()); actualValues.insert(ranges); } virtual ~MultipleRangesFixture() { assert(actualValues.size() == expectedValues.size()); } std::set<std::vector<int>> expectedValues; std::set<std::vector<int>> actualValues; }; BENCHMARK_DEFINE_F(MultipleRangesFixture, Empty)(benchmark::State& state) { for (auto _ : state) { int product = state.range(0) * state.range(1) * state.range(2); for (int x = 0; x < product; x++) { benchmark::DoNotOptimize(x); } } } BENCHMARK_REGISTER_F(MultipleRangesFixture, Empty) ->RangeMultiplier(2) ->Ranges({{1, 2}, {3, 7}, {5, 15}}) ->Args({7, 6, 3}); void BM_CheckDefaultArgument(benchmark::State& state) { // Test that the 'range()' without an argument is the same as 'range(0)'. assert(state.range() == state.range(0));<|fim▁hole|>BENCHMARK(BM_CheckDefaultArgument)->Ranges({{1, 5}, {6, 10}}); static void BM_MultipleRanges(benchmark::State& st) { for (auto _ : st) { } } BENCHMARK(BM_MultipleRanges)->Ranges({{5, 5}, {6, 6}}); BENCHMARK_MAIN()<|fim▁end|>
assert(state.range() != state.range(1)); for (auto _ : state) { } }
<|file_name|>formulacion_geotextiles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2005-2008 Francisco José Rodríguez Bogado, # # Diego Muñoz Escalante. # # ([email protected], [email protected]) # # # # This file is part of GeotexInn. # # # # GeotexInn is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 2 of the License, or # # (at your option) any later version. # # # # GeotexInn is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with GeotexInn; if not, write to the Free Software # # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # ############################################################################### ################################################################### ## formulacion_geotextiles.py - Formulación HARCODED de geotextiles ################################################################### ## NOTAS: ## Ventana hecha a volapié para crear los descuentos predefinidos. ## No permite definir más material para el descuento automático ni ## cambiar las formulaciones, solo cantidades y productos de compra ## empleados en cada "categoría". ## ---------------------------------------------------------------- ## ################################################################### ## Changelog: ## <|fim▁hole|>from ventana import Ventana from formularios import utils import re import pygtk pygtk.require('2.0') import gtk from framework import pclases from utils import _float as float try: from psycopg import ProgrammingError as psycopg_ProgrammingError except ImportError: from psycopg2 import ProgrammingError as psycopg_ProgrammingError class FormulacionGeotextiles(Ventana): def __init__(self, objeto = None, usuario = None): """ Constructor. objeto puede ser un objeto de pclases con el que comenzar la ventana (en lugar del primero de la tabla, que es el que se muestra por defecto). """ Ventana.__init__(self, 'formulacion_geotextiles.glade', objeto, usuario = usuario) connections = {'b_salir/clicked': self.salir, '_b_guardar/clicked': self.guardar, 'b_ensimaje/clicked': self.buscar_mp, 'b_antiestatico/clicked': self.buscar_mp, 'b_tubos/clicked': self.buscar_mp, 'b_plastico/clicked': self.buscar_mp, 'b_casquillos/clicked': self.buscar_mp, 'b_precinto/clicked': self.buscar_mp, 'b_grapas/clicked': self.buscar_mp, 'b_add_consumo/clicked': self.add_consumo_por_producto, 'b_drop_consumo/clicked': self.drop_consumo_por_producto, 'b_cambiar_producto_compra/clicked': self.cambiar_producto_compra, 'b_add_producto_a_consumo/clicked': self.add_producto_a_consumo } self.add_connections(connections) cols = (("Descripción (opcional)", "gobject.TYPE_STRING", True, True, True, None), ("Material", "gobject.TYPE_STRING", False, True, False, None), ("Cantidad", "gobject.TYPE_STRING", True, True, True, self.cambiar_cantidad), ("Unidad", "gobject.TYPE_STRING", True, True, True, self.cambiar_unidad), ("ID", "gobject.TYPE_STRING", False, False, False, None)) # Unidad: Deberá ser algo así como: # % para porcentaje del peso. # algo/u para descontar m, k o en lo que quiera que se mida el producto de compra por cada unidad fabricada. # algo/kg para descontar m, k o en lo que quiera que se mida el producto de compra por cada kg (m² en rollos) fabricado. # algo/x m para descontar m, k o en lo que quiera que se mida el producto de compra por cada x metros de ancho de cada # rollo fabricado (sólo para geotextiles y geocompuestos) utils.preparar_treeview(self.wids['tv_consumos'], cols, multi = True) # En el treeview cada nodo padre será una materia prima con su descuento y tal. Los nodos hijos contendrán el producto # de venta al que se aplica ese descuento automático. self.wids['tv_consumos'].connect("row-activated", self.abrir_producto) self.comprobar_registro() self.rellenar_widgets() gtk.main() def abrir_producto(self, tv, path, view_column): """ Abre el producto de compra si la línea marcada es de consumo y el de venta si es un "contenido" de consumo. """ model = tv.get_model() ide = model[path][-1] if model[path].parent == None: from formularios import productos_compra consumo = pclases.ConsumoAdicional.get(ide) producto_compra = consumo.productoCompra v = productos_compra.ProductosCompra(producto_compra) # @UnusedVariable else: from formularios import productos_de_venta_rollos v = productos_de_venta_rollos.ProductosDeVentaRollos(pclases.ProductoVenta.get(ide)) # @UnusedVariable def guardar(self, b): """ Guarda los valores para la cantidad en los campos de los registros correspondientes. """ try: self.cas['ensimaje'].cantidad = float(self.wids['e_censimaje'].get_text()) except: utils.dialogo_info(titulo = "ERROR DE FORMATO", texto = "Corrija el formato numérico usado y vuelva a intentarlo.") try: self.cas['antiestatico'].cantidad = float(self.wids['e_cantiestatico'].get_text()) except: utils.dialogo_info(titulo = "ERROR DE FORMATO", texto = "Corrija el formato numérico usado y vuelva a intentarlo.") try: self.cas['tubos'].cantidad = float(self.wids['e_ctubos'].get_text()) except: utils.dialogo_info(titulo = "ERROR DE FORMATO", texto = "Corrija el formato numérico usado y vuelva a intentarlo.") try: self.cas['plastico'].cantidad = float(self.wids['e_cplastico'].get_text()) except: utils.dialogo_info(titulo = "ERROR DE FORMATO", texto = "Corrija el formato numérico usado y vuelva a intentarlo.") try: self.cas['precinto'].cantidad = float(self.wids['e_cprecinto'].get_text()) except: utils.dialogo_info(titulo = "ERROR DE FORMATO", texto = "Corrija el formato numérico usado y vuelva a intentarlo.") try: self.cas['casquillos'].cantidad = float(self.wids['e_ccasquillos'].get_text()) except: utils.dialogo_info(titulo = "ERROR DE FORMATO", texto = "Corrija el formato numérico usado y vuelva a intentarlo.") try: self.cas['grapas'].cantidad = float(self.wids['e_cgrapas'].get_text()) except: utils.dialogo_info(titulo = "ERROR DE FORMATO", texto = "Corrija el formato numérico usado y vuelva a intentarlo.") self.rellenar_widgets() def rellenar_widgets(self): """ Introduce los valores actuales de la formulación. """ #self.wids['e_censimaje'].set_text('%.5f' % self.cas['ensimaje'].cantidad) #self.wids['e_ensimaje'].set_text(self.cas['ensimaje'].productoCompra and self.cas['ensimaje'].productoCompra.descripcion or '') #self.wids['e_cantiestatico'].set_text('%.5f' % self.cas['antiestatico'].cantidad) #self.wids['e_antiestatico'].set_text(self.cas['antiestatico'].productoCompra and self.cas['antiestatico'].productoCompra.descripcion or '') #self.wids['e_ctubos'].set_text('%.5f' % self.cas['tubos'].cantidad) #self.wids['e_tubos'].set_text(self.cas['tubos'].productoCompra and self.cas['tubos'].productoCompra.descripcion or '') #self.wids['e_cplastico'].set_text('%.5f' % self.cas['plastico'].cantidad) #self.wids['e_plastico'].set_text(self.cas['plastico'].productoCompra and self.cas['plastico'].productoCompra.descripcion or '') #self.wids['e_cprecinto'].set_text('%.5f' % self.cas['precinto'].cantidad) #self.wids['e_precinto'].set_text(self.cas['precinto'].productoCompra and self.cas['precinto'].productoCompra.descripcion or '') #self.wids['e_ccasquillos'].set_text('%.5f' % self.cas['casquillos'].cantidad) #self.wids['e_casquillos'].set_text(self.cas['casquillos'].productoCompra and self.cas['casquillos'].productoCompra.descripcion or '') #self.wids['e_cgrapas'].set_text('%.5f' % self.cas['grapas'].cantidad) #self.wids['e_grapas'].set_text(self.cas['grapas'].productoCompra and self.cas['grapas'].productoCompra.descripcion or '') self.rellenar_consumos_adicionales_por_producto() def rellenar_consumos_adicionales_por_producto(self): """ Rellena los consumos adicionales específicos por producto fabricado. """ model = self.wids['tv_consumos'].get_model() model.clear() self.wids['tv_consumos'].freeze_child_notify() self.wids['tv_consumos'].set_model(None) consumos = pclases.ConsumoAdicional.select(""" id IN (SELECT consumo_adicional__producto_venta.consumo_adicional_id FROM consumo_adicional__producto_venta WHERE producto_venta_id IN (SELECT id FROM producto_venta WHERE campos_especificos_rollo_id IS NOT NULL)) """, orderBy = "id") for consumo in consumos: if consumo.productoCompra and consumo.productoCompra.obsoleto: continue padre = model.append(None, (consumo.nombre, consumo.productoCompra and consumo.productoCompra.descripcion or "-", utils.float2str(consumo.cantidad, 5), consumo.unidad, consumo.id)) for producto in consumo.productosVenta: model.append(padre, ("", producto.descripcion, "", "", producto.id)) self.wids['tv_consumos'].set_model(model) self.wids['tv_consumos'].thaw_child_notify() def comprobar_registro(self): """ Comprueba si existe el registro de la formulación de la línea de geotextiles y los registros de descuento automático relacionados. Si no existen, los crea con valores por defecto. (De geocompuestos todavía no se ha dicho nada.) """ try: linea = pclases.LineaDeProduccion.select(pclases.LineaDeProduccion.q.nombre.contains("de geotextiles"))[0] except: utils.dialogo_info(titulo = "ERROR GRAVE", texto = "No se encontró la línea de geotextiles en la BD.\nCierre la ventana y contacte con el administrador de la aplicación.", padre = self.wids['ventana']) return self.objeto = linea.formulacion if self.objeto == None: self.objeto = pclases.Formulacion(nombre = "GEOTEXTILES", observaciones = "Generado automáticamente.") pclases.Auditoria.nuevo(self.objeto, self.usuario, __file__) linea.formulacion = self.objeto nombres_ca_existentes = [ca.nombre for ca in self.objeto.consumosAdicionales] nombres_ca = {'ensimaje': (0.3, ' %'), # 'antiestatico': (0.3, ' %'), 'tubos': (1, ' ud / 5.5 m'), 'plastico': (0.414, ' k / 5.5 m'), 'casquillos': (2, ' ud / ud'), # 'precinto': (10, ' m / ud'), 'grapas': (6, ' ud / ud'), 'agujas': (1, 'ud / 5.5 m'), } self.cas = {} for nombre in nombres_ca: if nombre not in nombres_ca_existentes: ca = pclases.ConsumoAdicional(nombre = nombre, cantidad = nombres_ca[nombre][0], unidad = nombres_ca[nombre][1], formulacionID = self.objeto.id, productoCompraID = None) pclases.Auditoria.nuevo(ca, self.usuario, __file__) for productoVenta in pclases.ProductoVenta.select(pclases.ProductoVenta.q.camposEspecificosRolloID != None): ca.addProductoVenta(productoVenta) self.cas[nombre] = ca else: self.cas[nombre] = [ca for ca in self.objeto.consumosAdicionales if ca.nombre == nombre][0] def refinar_resultados_busqueda(self, resultados): """ Muestra en una ventana de resultados todos los registros de "resultados". Devuelve el id (primera columna de la ventana de resultados) de la fila seleccionada o None si se canceló. """ filas_res = [] for r in resultados: filas_res.append((r.id, r.codigo, r.descripcion)) idproducto = utils.dialogo_resultado(filas_res, titulo = 'Seleccione producto', cabeceras = ('ID Interno', 'Código', 'Descripción')) if idproducto < 0: return None else: return idproducto def buscar_producto(self): """ Muestra una ventana de búsqueda y a continuación los resultados. El objeto seleccionado se devolverá a no ser que se pulse en Cancelar en la ventana de resultados, en cuyo caso se deveulve None. """ a_buscar = utils.dialogo_entrada("Introduzca código o descripción de producto:") if a_buscar != None: try: ida_buscar = int(a_buscar) except ValueError: ida_buscar = -1 criterio = pclases.OR( pclases.ProductoCompra.q.codigo.contains(a_buscar), pclases.ProductoCompra.q.descripcion.contains(a_buscar), pclases.ProductoCompra.q.id == ida_buscar) resultados = pclases.ProductoCompra.select(pclases.AND( criterio, pclases.ProductoCompra.q.obsoleto == False, pclases.ProductoCompra.q.controlExistencias == True)) if resultados.count() > 1: ## Refinar los resultados idproducto = self.refinar_resultados_busqueda(resultados) if idproducto == None: return None resultados = [pclases.ProductoCompra.get(idproducto)] elif resultados.count() < 1: ## Sin resultados de búsqueda utils.dialogo_info('SIN RESULTADOS', 'La búsqueda no produjo resultados.\n' 'Pruebe a cambiar el texto buscado o ' 'déjelo en blanco para ver una lista ' 'completa.\n(Atención: Ver la lista ' 'completa puede resultar lento si el ' 'número de elementos es muy alto)', padre = self.wids['ventana']) return None ## Un único resultado return resultados[0] else: return "CANCELAR" def buscar_mp(self, b): """ Muestra un cuadro de búsqueda de productos de compra. Relaciona el seleccionado con el registro correspondiente en función del botón pulsado. """ producto = self.buscar_producto() if producto == "CANCELAR": return nombreb = b.name.replace('b_', '') trans = {'ensimaje': 'ensimaje', 'antiestatico': 'antiestatico', 'tubos': 'tubos', 'plastico': 'plastico', 'casquillos': 'casquillos', 'precinto': 'precinto', 'grapas': 'grapas'} nombre = trans[nombreb] self.cas[nombre].productoCompra = producto self.rellenar_widgets() def add_consumo_por_producto(self, boton): """ Añade un consumo automático por producto. """ productos = self.pedir_productos_venta() if productos: producto_compra = self.pedir_producto_compra() if (productos != None and len(productos) > 0 and producto_compra != None): nombre = self.pedir_nombre() if nombre == None: return cantidad = self.pedir_cantidad() if cantidad == None: return unidad = self.pedir_unidad(producto_compra) if unidad == None: return nuevo_consumo_adicional = pclases.ConsumoAdicional( formulacionID = self.objeto.id, productoCompraID = producto_compra.id, nombre = nombre, cantidad = cantidad, unidad = unidad) pclases.Auditoria.nuevo(nuevo_consumo_adicional, self.usuario, __file__) for producto in productos: nuevo_consumo_adicional.addProductoVenta(producto) self.rellenar_consumos_adicionales_por_producto() def drop_consumo_por_producto(self, boton): """ Elimina el consumo o consumos seleccionados en el TreeView. """ texto = """ Si ha seleccionado un consumo se eliminará el consumo completo. Si seleccionó uno o varios productos, se eliminarán del consumo al que pertenece, por lo que ya no empleará el material relacionado cuando se fabriquen artículos del mismo. ¿Está seguro de querer continuar? """ model, paths = self.wids['tv_consumos'].get_selection().get_selected_rows() if paths and utils.dialogo(titulo = "¿ELIMINAR?", texto = texto, padre = self.wids['ventana']): for path in paths: if model[path].parent == None: id_consumo = model[path][-1] consumo_adicional_por_producto = pclases.ConsumoAdicional.get(id_consumo) try: for p in consumo_adicional_por_producto.productosVenta: consumo_adicional_por_producto.removeProductoVenta(p) consumo_adicional_por_producto.destroy(ventana = __file__) except psycopg_ProgrammingError, msg: utils.dialogo_info(titulo = "ERROR: INFORME A LOS DESARROLLADORES", texto = "Ocurrió un error al eliminar el consumo.\nDEBUG: Traza de la excepción:\n%s" % (msg), padre = self.wids['ventana']) else: id_consumo = model[path].parent[-1] idproductov = model[path][-1] consumo_adicional_por_producto = pclases.ConsumoAdicional.get(id_consumo) productov = pclases.ProductoVenta.get(idproductov) consumo_adicional_por_producto.removeProductoVenta(productov) self.rellenar_consumos_adicionales_por_producto() def cambiar_cantidad(self, cell, path, texto): """ Cambia la cantidad del descuento adicional por producto. """ try: cantidad = utils._float(texto) except ValueError: utils.dialogo_info(titulo = "FORMATO INCORRECTO", texto = "El texto %s no es válido." % (texto), padre = self.wids['ventana']) return model = self.wids['tv_consumos'].get_model() if model[path].parent == None: idconsumo = model[path][-1] consumo = pclases.ConsumoAdicional.get(idconsumo) consumo.cantidad = cantidad self.rellenar_consumos_adicionales_por_producto() def cambiar_unidad(self, cell, path, texto): """ Cambia la unidad de descuento para el descuento adicional por producto """ model = self.wids['tv_consumos'].get_model() if model[path].parent == None: idconsumo = model[path][-1] consumo = pclases.ConsumoAdicional.get(idconsumo) if comprobar_unidad(texto, consumo.cantidad): consumo.unidad = texto self.rellenar_consumos_adicionales_por_producto() def pedir_producto(self): """ Solicita un código, nombre o descripcicón de producto, muestra una ventana de resultados coincidentes con la búsqueda y devuelve una lista de ids de productos o [] si se cancela o no se encuentra. """ productos = None txt = utils.dialogo_entrada(texto = 'Introduzca código, nombre o descripción del geotextil:', titulo = 'BUSCAR PRODUCTO VENTA', padre = self.wids['ventana']) if txt != None: criterio = pclases.OR(pclases.ProductoVenta.q.codigo.contains(txt), pclases.ProductoVenta.q.nombre.contains(txt), pclases.ProductoVenta.q.descripcion.contains(txt)) criterio = pclases.AND(criterio, pclases.ProductoVenta.q.camposEspecificosRolloID != None) prods = pclases.ProductoVenta.select(criterio) productos = [p for p in prods] return productos def pedir_productos_venta(self): """ Muestra una ventana de búsqueda de un producto y devuelve uno o varios objetos productos dentro de una tupla o None si se cancela. """ productos = self.pedir_producto() if productos == None: return if productos == []: utils.dialogo_info(titulo = "NO ENCONTRADO", texto = "Producto no encontrado", padre = self.wids['ventana']) return filas = [(p.id, p.codigo, p.descripcion) for p in productos] idsproducto = utils.dialogo_resultado(filas, titulo = "SELECCIONE UNO O VARIOS PRODUCTOS", padre = self.wids['ventana'], cabeceras = ("ID", "Código", "Descripción"), multi = True) if idsproducto and idsproducto!= [-1]: return [pclases.ProductoVenta.get(ide) for ide in idsproducto] def pedir_producto_compra(self): """ Devuelve UN producto de compra obtenido a partir de una búsqueda, etc. """ producto = None a_buscar = utils.dialogo_entrada(titulo = "BUSCAR MATERIAL", texto = "Introduzca texto a buscar en productos de compra:", padre = self.wids['ventana']) if a_buscar != None: resultados = utils.buscar_productos_compra(a_buscar) if resultados.count() > 1: ## Refinar los resultados: filas_res = [] for r in resultados: filas_res.append((r.id, r.codigo, r.descripcion)) idproducto = utils.dialogo_resultado(filas_res, titulo = 'Seleccione producto', cabeceras = ('ID Interno', 'Código', 'Descripción'), padre = self.wids['ventana']) if idproducto < 0: return producto = pclases.ProductoCompra.get(idproducto) # id es clave primaria, esta comprensión debería devolver un único producto elif resultados.count() < 1: ## La búsqueda no produjo resultados. utils.dialogo_info('SIN RESULTADOS', 'La búsqueda no produjo ningún resultado.\nIntente una ' 'búsqueda menos restrictiva usando un texto más corto.', padre = self.wids['ventana']) return None else: producto = resultados[0] return producto def pedir_nombre(self): """ Pide un texto y lo devuelve. Sin más. """ return utils.dialogo_entrada(titulo = "NOMBRE CONSUMO", texto = "Introduzca un nombre identificativo si lo desea:", padre = self.wids['ventana']) def pedir_cantidad(self): """ Pide una cantidad que debe ser un número float. """ res = utils.dialogo_entrada(titulo = "CANTIDAD", texto = "Introduzca la cantidad a consumir del producto de compra (sin unidades):", padre = self.wids['ventana']) try: res = utils._float(res) except ValueError: utils.dialogo_info(titulo = "CANTIDAD INCORRECTA", texto = "El texto introducido %s no es correcto." % (res), padre = self.wids['ventana']) res = None return res def pedir_unidad(self, productoCompra): """ Pide la unidad del descuento y comprueba que sea correcta. Recibe el producto de compra para mostrar el valor por defecto. """ txt = """ Introduzca las unidades para el descuento de materiales. Por ejemplo: % (porcentaje en las unidades del material por peso de producto terminado). ud / 5 ud (unidad del material por cada 5 unidades de producto terminado). m / kg (metro de material por kilo de producto). kg / 5.5 m (kg de material por cada 5.5 metros de producto). NOTA: La unidad del materal que se descuenta debe ser la misma que consta en catálogo, pedidos de compra, etc. No use puntos en las unidades de medida. """ defecto = "%s / ud" % (productoCompra.unidad.replace(".", " ")) res = utils.dialogo_entrada(titulo = "INTRODUZCA UNIDAD", texto = txt, padre = self.wids['ventana'], valor_por_defecto = defecto) seguir = True while seguir and not comprobar_unidad(res): seguir = utils.dialogo(titulo = "FORMATO INCORRECTO", texto = "El texto introducido %s no tiene el formato correcto.\n\n\n¿Desea volver a intentarlo?" % (res), padre = self.wids['ventana']) if seguir == False: res = None return res def cambiar_producto_compra(self, boton): """ Cambia por otro el producto que se consume en el registro de consumo adicional seleccionado. """ producto_compra = self.buscar_producto() if producto_compra == "CANCELAR": return sel = self.wids['tv_consumos'].get_selection() model, paths = sel.get_selected_rows() for path in paths: if model[path].parent == None: id_consumo = model[path][-1] else: id_consumo = model[path].parent[-1] consumo_adicional_por_producto = pclases.ConsumoAdicional.get( id_consumo) consumo_adicional_por_producto.productoCompra = producto_compra self.rellenar_consumos_adicionales_por_producto() def add_producto_a_consumo(self, boton): """ Añade un producto de venta a un consumo existente. """ model, paths = self.wids['tv_consumos'].get_selection().get_selected_rows() if paths != []: productos = self.pedir_productos_venta() if productos: for path in paths: if model[path].parent == None: id_consumo = model[path][-1] else: id_consumo = model[path].parent[-1] consumo_adicional_por_producto = pclases.ConsumoAdicional.get(id_consumo) for producto in productos: if producto not in consumo_adicional_por_producto.productosVenta: consumo_adicional_por_producto.addProductoVenta(producto) else: utils.dialogo_info(titulo = "YA EXISTE", texto = "El producto %s ya consume según la fórmula de %s.\n\nPulse «Aceptar» para continuar." % (producto.descripcion, consumo_adicional_por_producto.nombre), padre = self.wids['ventana']) self.rellenar_consumos_adicionales_por_producto() else: utils.dialogo_info(titulo = "SELECCIONE UN CONSUMO", texto = "Debe seleccionar un consumo existente.", padre = self.wids['ventana']) def comprobar_unidad(txt, cantidadpc = 1.0): """ Comprueba si la unidad de descuento "txt" cumple con alguna de las unidades interpretables por el programa. cantidadpc se usa para agregarlo a la parte "unidad" y chequear todo el conjunto en el proceso. """ res = False txt = "%s %s" % (utils.float2str(cantidadpc, 5), txt) txt = txt.strip() # TODO: De momento lo hago así porque no sé de qué modo ni dónde guardarlo: regexp_porcentaje = re.compile("^-?\d+[\.,]?\d*\s*%$") regexp_fraccion = re.compile("-?\d+[\.,]?\d*\s*\w*\s*/\s*-?\d*[\.,]?\d*\s*\w+") if regexp_porcentaje.findall(txt) != []: cantidad = parsear_porcentaje(txt) # @UnusedVariable res = True elif regexp_fraccion.findall(txt) != []: cantidad, unidad, cantidad_pv, unidad_pv = parsear_fraccion(txt) # @UnusedVariable res = True return res def parsear_porcentaje(txt): """ Devuelve la cantidad del porcentaje como fracción de 1. """ regexp_float = re.compile("^-?\d+[\.,]?\d*") num = regexp_float.findall(txt)[0] return utils._float(num) def parsear_fraccion(txt): """ Devuelve la cantidad de producto compra y unidad que hay que descontar por cada cantidad de producto venta y unidad (que también se devuelven). Es necesario que venga la cantidadpc aunque en el registro, en el campo "unidad" no aparece. """ regexp_float = re.compile("-?\d+[\.,]?\d*") regexp_unidad = re.compile("\w+") cantidades = regexp_float.findall(txt) if len(cantidades) == 1: cantidadpc = cantidades[0] cantidadpv = '1' txt = txt.replace(cantidadpc, "") elif len(cantidades) == 2: cantidadpc, cantidadpv = cantidades[0:2] txt = txt.replace(cantidadpc, "") txt = txt.replace(cantidadpv, "") else: cantidadpc = '1' cantidadpv = '1' txt = txt.replace("/", "") unidadpc, unidadpv = regexp_unidad.findall(txt)[0:2] cantidadpc = utils._float(cantidadpc) cantidadpv = utils._float(cantidadpv) return cantidadpc, unidadpc, cantidadpv, unidadpv if __name__ == '__main__': f = FormulacionGeotextiles()<|fim▁end|>
## ################################################################### # ###################################################################
<|file_name|>inotify.rs<|end_file_name|><|fim▁begin|>//! Monitoring API for filesystem events. //! //! Inotify is a Linux-only API to monitor filesystems events. //! //! For more documentation, please read [inotify(7)](https://man7.org/linux/man-pages/man7/inotify.7.html). //! //! # Examples //! //! Monitor all events happening in directory "test": //! ```no_run<|fim▁hole|>//! //! // We add a new watch on directory "test" for all events. //! let wd = instance.add_watch("test", AddWatchFlags::IN_ALL_EVENTS).unwrap(); //! //! loop { //! // We read from our inotify instance for events. //! let events = instance.read_events().unwrap(); //! println!("Events: {:?}", events); //! } //! ``` use libc::{ c_char, c_int, }; use std::ffi::{OsString,OsStr,CStr}; use std::os::unix::ffi::OsStrExt; use std::mem::{MaybeUninit, size_of}; use std::os::unix::io::{RawFd,AsRawFd,FromRawFd}; use std::ptr; use crate::unistd::read; use crate::Result; use crate::NixPath; use crate::errno::Errno; use cfg_if::cfg_if; libc_bitflags! { /// Configuration options for [`inotify_add_watch`](fn.inotify_add_watch.html). pub struct AddWatchFlags: u32 { /// File was accessed. IN_ACCESS; /// File was modified. IN_MODIFY; /// Metadata changed. IN_ATTRIB; /// Writable file was closed. IN_CLOSE_WRITE; /// Nonwritable file was closed. IN_CLOSE_NOWRITE; /// File was opened. IN_OPEN; /// File was moved from X. IN_MOVED_FROM; /// File was moved to Y. IN_MOVED_TO; /// Subfile was created. IN_CREATE; /// Subfile was deleted. IN_DELETE; /// Self was deleted. IN_DELETE_SELF; /// Self was moved. IN_MOVE_SELF; /// Backing filesystem was unmounted. IN_UNMOUNT; /// Event queue overflowed. IN_Q_OVERFLOW; /// File was ignored. IN_IGNORED; /// Combination of `IN_CLOSE_WRITE` and `IN_CLOSE_NOWRITE`. IN_CLOSE; /// Combination of `IN_MOVED_FROM` and `IN_MOVED_TO`. IN_MOVE; /// Only watch the path if it is a directory. IN_ONLYDIR; /// Don't follow symlinks. IN_DONT_FOLLOW; /// Event occurred against directory. IN_ISDIR; /// Only send event once. IN_ONESHOT; /// All of the events. IN_ALL_EVENTS; } } libc_bitflags! { /// Configuration options for [`inotify_init1`](fn.inotify_init1.html). pub struct InitFlags: c_int { /// Set the `FD_CLOEXEC` flag on the file descriptor. IN_CLOEXEC; /// Set the `O_NONBLOCK` flag on the open file description referred to by the new file descriptor. IN_NONBLOCK; } } /// An inotify instance. This is also a file descriptor, you can feed it to /// other interfaces consuming file descriptors, epoll for example. #[derive(Debug, Clone, Copy)] pub struct Inotify { fd: RawFd } /// This object is returned when you create a new watch on an inotify instance. /// It is then returned as part of an event once triggered. It allows you to /// know which watch triggered which event. #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct WatchDescriptor { wd: i32 } /// A single inotify event. /// /// For more documentation see, [inotify(7)](https://man7.org/linux/man-pages/man7/inotify.7.html). #[derive(Debug)] pub struct InotifyEvent { /// Watch descriptor. This field corresponds to the watch descriptor you /// were issued when calling add_watch. It allows you to know which watch /// this event comes from. pub wd: WatchDescriptor, /// Event mask. This field is a bitfield describing the exact event that /// occured. pub mask: AddWatchFlags, /// This cookie is a number that allows you to connect related events. For /// now only IN_MOVED_FROM and IN_MOVED_TO can be connected. pub cookie: u32, /// Filename. This field exists only if the event was triggered for a file /// inside the watched directory. pub name: Option<OsString> } impl Inotify { /// Initialize a new inotify instance. /// /// Returns a Result containing an inotify instance. /// /// For more information see, [inotify_init(2)](https://man7.org/linux/man-pages/man2/inotify_init.2.html). pub fn init(flags: InitFlags) -> Result<Inotify> { let res = Errno::result(unsafe { libc::inotify_init1(flags.bits()) }); res.map(|fd| Inotify { fd }) } /// Adds a new watch on the target file or directory. /// /// Returns a watch descriptor. This is not a File Descriptor! /// /// For more information see, [inotify_add_watch(2)](https://man7.org/linux/man-pages/man2/inotify_add_watch.2.html). pub fn add_watch<P: ?Sized + NixPath>(self, path: &P, mask: AddWatchFlags) -> Result<WatchDescriptor> { let res = path.with_nix_path(|cstr| { unsafe { libc::inotify_add_watch(self.fd, cstr.as_ptr(), mask.bits()) } })?; Errno::result(res).map(|wd| WatchDescriptor { wd }) } /// Removes an existing watch using the watch descriptor returned by /// inotify_add_watch. /// /// Returns an EINVAL error if the watch descriptor is invalid. /// /// For more information see, [inotify_rm_watch(2)](https://man7.org/linux/man-pages/man2/inotify_rm_watch.2.html). pub fn rm_watch(self, wd: WatchDescriptor) -> Result<()> { cfg_if! { if #[cfg(target_os = "linux")] { let arg = wd.wd; } else if #[cfg(target_os = "android")] { let arg = wd.wd as u32; } } let res = unsafe { libc::inotify_rm_watch(self.fd, arg) }; Errno::result(res).map(drop) } /// Reads a collection of events from the inotify file descriptor. This call /// can either be blocking or non blocking depending on whether IN_NONBLOCK /// was set at initialization. /// /// Returns as many events as available. If the call was non blocking and no /// events could be read then the EAGAIN error is returned. pub fn read_events(self) -> Result<Vec<InotifyEvent>> { let header_size = size_of::<libc::inotify_event>(); const BUFSIZ: usize = 4096; let mut buffer = [0u8; BUFSIZ]; let mut events = Vec::new(); let mut offset = 0; let nread = read(self.fd, &mut buffer)?; while (nread - offset) >= header_size { let event = unsafe { let mut event = MaybeUninit::<libc::inotify_event>::uninit(); ptr::copy_nonoverlapping( buffer.as_ptr().add(offset), event.as_mut_ptr() as *mut u8, (BUFSIZ - offset).min(header_size) ); event.assume_init() }; let name = match event.len { 0 => None, _ => { let ptr = unsafe { buffer .as_ptr() .add(offset + header_size) as *const c_char }; let cstr = unsafe { CStr::from_ptr(ptr) }; Some(OsStr::from_bytes(cstr.to_bytes()).to_owned()) } }; events.push(InotifyEvent { wd: WatchDescriptor { wd: event.wd }, mask: AddWatchFlags::from_bits_truncate(event.mask), cookie: event.cookie, name }); offset += header_size + event.len as usize; } Ok(events) } } impl AsRawFd for Inotify { fn as_raw_fd(&self) -> RawFd { self.fd } } impl FromRawFd for Inotify { unsafe fn from_raw_fd(fd: RawFd) -> Self { Inotify { fd } } }<|fim▁end|>
//! # use nix::sys::inotify::{AddWatchFlags,InitFlags,Inotify}; //! # //! // We create a new inotify instance. //! let instance = Inotify::init(InitFlags::empty()).unwrap();
<|file_name|>domomaster_postinst.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 ## @package domomaster # Master daemon for D3 boxes. # # Developed by GreenLeaf. import sys; import os; import random; import string; from hashlib import sha1 from subprocess import * import socket; sys.path.append("/usr/lib/domoleaf"); from DaemonConfigParser import *; MASTER_CONF_FILE_BKP = '/etc/domoleaf/master.conf.save'; MASTER_CONF_FILE_TO = '/etc/domoleaf/master.conf'; SLAVE_CONF_FILE = '/etc/domoleaf/slave.conf'; ## Copies the conf data from a backup file to a new one. def master_conf_copy(): file_from = DaemonConfigParser(MASTER_CONF_FILE_BKP); file_to = DaemonConfigParser(MASTER_CONF_FILE_TO); #listen var = file_from.getValueFromSection('listen', 'port_slave'); file_to.writeValueFromSection('listen', 'port_slave', var); var = file_from.getValueFromSection('listen', 'port_cmd'); file_to.writeValueFromSection('listen', 'port_cmd', var); #connect var = file_from.getValueFromSection('connect', 'port'); file_to.writeValueFromSection('connect', 'port', var); #mysql var = file_from.getValueFromSection('mysql', 'user'); file_to.writeValueFromSection('mysql', 'user', var); var = file_from.getValueFromSection('mysql', 'database_name'); file_to.writeValueFromSection('mysql', 'database_name', var); #greenleaf var = file_from.getValueFromSection('greenleaf', 'commercial'); file_to.writeValueFromSection('greenleaf', 'commercial', var); var = file_from.getValueFromSection('greenleaf', 'admin_addr'); file_to.writeValueFromSection('greenleaf', 'admin_addr', var); ## Initializes the conf in database. def master_conf_initdb(): file = DaemonConfigParser(MASTER_CONF_FILE_TO); #mysql password password = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(128)) password = sha1(password.encode('utf-8')) file.writeValueFromSection('mysql', 'password', password.hexdigest()); os.system('sed -i "s/define(\'DB_PASSWORD\', \'domoleaf\')/define(\'DB_PASSWORD\', \''+password.hexdigest()+'\')/g" /etc/domoleaf/www/config.php') #mysql user query1 = 'DELETE FROM user WHERE User="domoleaf"'; query2 = 'DELETE FROM db WHERE User="domoleaf"';<|fim▁hole|> call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query1]); call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query2]); call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query3]); call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query4]); call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query5]); ## Initializes the conf in file. def master_conf_init(): file = DaemonConfigParser(SLAVE_CONF_FILE); personnal_key = file.getValueFromSection('personnal_key', 'aes'); hostname = socket.gethostname(); #KNX Interface if os.path.exists('/dev/ttyAMA0'): knx = "tpuarts" knx_interface = 'ttyAMA0'; elif os.path.exists('/dev/ttyS0'): knx = "tpuarts" knx_interface = 'ttyS0'; else: knx = "ipt" knx_interface = '127.0.0.1'; domoslave = os.popen("dpkg-query -W -f='${Version}\n' domoslave").read().split('\n')[0]; query1 = "INSERT INTO daemon (name, serial, secretkey, validation, version) VALUES ('"+hostname+"','"+hostname+"','"+personnal_key+"',1,'"+domoslave+"')" query2 = "INSERT INTO daemon_protocol (daemon_id, protocol_id, interface, interface_arg) VALUES (1,1,'"+knx+"','"+knx_interface+"')" call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'domoleaf', '-e', query1]); call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'domoleaf', '-e', query2]); if __name__ == "__main__": #Upgrade if os.path.exists(MASTER_CONF_FILE_BKP): master_conf_copy() os.remove(MASTER_CONF_FILE_BKP); else: master_conf_init() master_conf_initdb()<|fim▁end|>
query3 = 'INSERT INTO user (Host, User, Password) VALUES (\'%\', \'domoleaf\', PASSWORD(\''+password.hexdigest()+'\'));'; query4 = 'INSERT INTO db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Create_tmp_table_priv, Lock_tables_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv) VALUES ("%","domoleaf","domoleaf","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y");'; query5 = 'FLUSH PRIVILEGES';
<|file_name|>test_json.py<|end_file_name|><|fim▁begin|>"""Test Home Assistant json utility functions.""" from json import JSONEncoder import os import sys from tempfile import mkdtemp import unittest from unittest.mock import Mock import pytest from homeassistant.exceptions import HomeAssistantError from homeassistant.util.json import SerializationError, load_json, save_json # Test data that can be saved as JSON TEST_JSON_A = {"a": 1, "B": "two"} TEST_JSON_B = {"a": "one", "B": 2} # Test data that can not be saved as JSON (keys must be strings) TEST_BAD_OBJECT = {("A",): 1} # Test data that can not be loaded as JSON TEST_BAD_SERIALIED = "THIS IS NOT JSON\n" TMP_DIR = None def setup(): """Set up for tests.""" global TMP_DIR TMP_DIR = mkdtemp() def teardown(): """Clean up after tests.""" for fname in os.listdir(TMP_DIR): os.remove(os.path.join(TMP_DIR, fname)) os.rmdir(TMP_DIR) def _path_for(leaf_name): return os.path.join(TMP_DIR, leaf_name + ".json") def test_save_and_load(): """Test saving and loading back.""" fname = _path_for("test1") save_json(fname, TEST_JSON_A) data = load_json(fname) assert data == TEST_JSON_A # Skipped on Windows @unittest.skipIf( sys.platform.startswith("win"), "private permissions not supported on Windows" ) def test_save_and_load_private(): """Test we can load private files and that they are protected.""" fname = _path_for("test2") save_json(fname, TEST_JSON_A, private=True) data = load_json(fname) assert data == TEST_JSON_A stats = os.stat(fname) assert stats.st_mode & 0o77 == 0 def test_overwrite_and_reload(): """Test that we can overwrite an existing file and read back.""" fname = _path_for("test3") save_json(fname, TEST_JSON_A) save_json(fname, TEST_JSON_B) data = load_json(fname) assert data == TEST_JSON_B def test_save_bad_data(): """Test error from trying to save unserialisable data.""" fname = _path_for("test4") with pytest.raises(SerializationError): save_json(fname, TEST_BAD_OBJECT) def test_load_bad_data(): """Test error from trying to load unserialisable data.""" fname = _path_for("test5") with open(fname, "w") as fh: fh.write(TEST_BAD_SERIALIED) with pytest.raises(HomeAssistantError): load_json(fname) def test_custom_encoder(): """Test serializing with a custom encoder."""<|fim▁hole|> def default(self, o): """Mock JSON encode method.""" return "9" fname = _path_for("test6") save_json(fname, Mock(), encoder=MockJSONEncoder) data = load_json(fname) assert data == "9"<|fim▁end|>
class MockJSONEncoder(JSONEncoder): """Mock JSON encoder."""
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from holoviews.element import ( ElementConversion, Points as HvPoints, Polygons as HvPolygons, Path as HvPath ) from .geo import (_Element, Feature, Tiles, is_geographic, # noqa (API import) WMTS, Points, Image, Text, LineContours, RGB, FilledContours, Path, Polygons, Shape, Dataset, Contours, TriMesh, Graph, Nodes, EdgePaths, QuadMesh, VectorField, Labels, HexTiles, Rectangles, Segments) <|fim▁hole|> GeoConversion is a very simple container object which can be given an existing Dataset and provides methods to convert the Dataset into most other Element types. If the requested key dimensions correspond to geographical coordinates the conversion interface will automatically use a geographical Element type while all other plot will use regular HoloViews Elements. """ def __init__(self, cube): self._element = cube def __call__(self, *args, **kwargs): group_type = args[0] if 'crs' not in kwargs and issubclass(group_type, _Element): kwargs['crs'] = self._element.crs is_gpd = self._element.interface.datatype == 'geodataframe' if is_gpd: kdims = args[1] if len(args) > 1 else kwargs.get('kdims', None) if len(args) > 1: args = (Dataset, [])+args[2:] else: args = (Dataset,) kwargs['kdims'] = [] converted = super(GeoConversion, self).__call__(*args, **kwargs) if is_gpd: if kdims is None: kdims = group_type.kdims converted = converted.map(lambda x: x.clone(kdims=kdims, new_type=group_type), Dataset) return converted def linecontours(self, kdims=None, vdims=None, mdims=None, **kwargs): return self(LineContours, kdims, vdims, mdims, **kwargs) def filledcontours(self, kdims=None, vdims=None, mdims=None, **kwargs): return self(FilledContours, kdims, vdims, mdims, **kwargs) def image(self, kdims=None, vdims=None, mdims=None, **kwargs): return self(Image, kdims, vdims, mdims, **kwargs) def points(self, kdims=None, vdims=None, mdims=None, **kwargs): if kdims is None: kdims = self._element.kdims el_type = Points if is_geographic(self._element, kdims) else HvPoints return self(el_type, kdims, vdims, mdims, **kwargs) def polygons(self, kdims=None, vdims=None, mdims=None, **kwargs): if kdims is None: kdims = self._element.kdims el_type = Polygons if is_geographic(self._element, kdims) else HvPolygons return self(el_type, kdims, vdims, mdims, **kwargs) def path(self, kdims=None, vdims=None, mdims=None, **kwargs): if kdims is None: kdims = self._element.kdims el_type = Path if is_geographic(self._element, kdims) else HvPath return self(el_type, kdims, vdims, mdims, **kwargs) Dataset._conversion_interface = GeoConversion<|fim▁end|>
class GeoConversion(ElementConversion): """
<|file_name|>widget.tsx<|end_file_name|><|fim▁begin|>/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Widget rendering. */ import $ from "jquery"; import { Map, Set, List, fromJS } from "immutable"; import { Tabs, Tab } from "../../antd-bootstrap"; import React, { useRef, useState } from "react"; import ReactDOM from "react-dom"; import useIsMountedRef from "@cocalc/frontend/app-framework/is-mounted-hook"; import { usePrevious, useRedux } from "@cocalc/frontend/app-framework"; import { JupyterActions } from "../browser-actions"; import * as pWidget from "@phosphor/widgets"; require("@jupyter-widgets/controls/css/widgets.css"); import { CellOutputMessages } from "./message"; import useNotebookFrameActions from "@cocalc/frontend/frame-editors/jupyter-editor/cell-notebook/hook"; interface WidgetProps { value: Map<string, any>; actions?: JupyterActions; name: string; project_id?: string; directory?: string; trust?: boolean; } export const Widget: React.FC<WidgetProps> = React.memo( (props: WidgetProps) => { const { value, actions, name, project_id, directory, trust } = props; const frameActions = useNotebookFrameActions(); const prev_value = usePrevious(value); const phosphorRef = useRef<HTMLDivElement>(null); const reactBoxRef = useRef<HTMLDivElement>(null); const view = useRef<any>(); const model = useRef<any>(); const init_view_is_running = useRef<boolean>(false); const is_mounted = useIsMountedRef(); const widget_model_ids: Set<string> = useRedux([name, "widget_model_ids"]); // WidgetState: used to store output state, for output widgets, which we render. const [outputs, set_outputs] = useState<Map<string, any> | undefined>(); const [style, set_style] = useState<any>(); const [react_view, set_react_view] = useState< List<string> | string | undefined >(); React.useEffect(() => { if (widget_model_ids?.contains(value.get("model_id"))) { // model known already init_view(value.get("model_id")); } return () => { // always clean up remove_view(); }; }, []); React.useEffect(() => { if (prev_value == null) return; const prev_model_id = prev_value.get("model_id"); const next_model_id = value.get("model_id"); if (prev_model_id != next_model_id) { // the component is being reused for a completely different model, // so get rid of anything currently used. remove_view(); } }, [value]); React.useEffect(() => { if (view.current != null) return; const model_id = value.get("model_id"); // view not yet initialized and model is now known, so initialize it. if (widget_model_ids?.contains(model_id)) { init_view(model_id); } }, [widget_model_ids]); function update_output(): void { if (!is_mounted.current) return; const state: { layout?: { changed: any }; outputs: unknown[] } = model.current.get_state(true); if (state == null || state.outputs == null) { set_outputs(undefined); set_style(undefined); return; } const outputs = {}; for (const i in state.outputs) { outputs[i] = state.outputs[i]; } set_outputs(fromJS(outputs)); if (state?.layout?.changed != null) { // TODO: we only set style once, this first time it is known. // If the layout were to dynamically change, this won't update. set_style(state.layout.changed); } } function update_react_view(): void { if (!is_mounted.current) return; const state = model.current.get_state(true); if (state == null) { set_react_view(undefined); return; } if (state.children == null) { // special case for now when not a container but implemented in react.s set_react_view("unknown"); return; } const react_view: string[] = []; for (const child of state.children) { react_view.push(child.model_id); } set_react_view(fromJS(react_view)); } async function init_view(model_id: string | undefined): Promise<void> { if (init_view_is_running.current) { // it's already running right now. return; } try { init_view_is_running.current = true; if (model_id == null) return; // probably never happens ? if (actions == null) { return; // no way to do anything right now(?) // TODO: maybe can still render widget based on some stored state somewhere? } const widget_manager = actions.widget_manager; if (widget_manager == null) { return; } model.current = await widget_manager.get_model(model_id); if (model.current == null || !is_mounted.current) { // no way to render at present; wait for widget_counter to increase and try again. return; } if (model.current.is_react) { update_react_view(); model.current.on("change", update_react_view); return; } switch (model.current.module) { case "@jupyter-widgets/controls": case "@jupyter-widgets/base": // Right now we use phosphor views for many base and controls. // TODO: we can iteratively rewrite some of these using react // for a more consistent look and feel (with bootstrap). await init_phosphor_view(model_id); break; case "@jupyter-widgets/output": model.current.on("change", update_output); update_output(); break; default: throw Error( `Not implemented widget module ${model.current.module}` ); } } catch (err) { // TODO -- show an error component somehow... console.trace(); console.warn("widget.tsx: init_view -- failed ", err); } finally { init_view_is_running.current = false; } } function remove_view(): void { if (view.current != null) { try { view.current.remove(); // no clue what this does... } catch (err) { // after changing this to an FC, calling remove() causes // 'Widget is not attached.' in phosphorjs. // The only way I found to trigger this is to concurrently work // on the same cell with two tabs. It recovers fine from catching this! console.warn(`widget/remove_view error: ${err}`); } view.current.send = undefined; view.current = undefined; } if (model.current != null) { if (model.current.module == "@jupyter-widgets/output") { model.current.off("change", update_output); } model.current = undefined; } } function handle_phosphor_focus(): void { if (actions == null) return; const elt = ReactDOM.findDOMNode(phosphorRef.current); if (elt == null) return; // See https://stackoverflow.com/questions/7668525/is-there-a-jquery-selector-to-get-all-elements-that-can-get-focus const focuseable = $(elt).find( "a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]" ); if (focuseable.length > 0) { focuseable.on("focus", () => { frameActions.current?.disable_key_handler(); }); focuseable.on("blur", () => { frameActions.current?.enable_key_handler(); }); } } // Configure handler for custom messages, e.g., // {event:"click"} when button is clicked. function handle_phosphor_custom_events(model_id: string): void { if (view.current == null) return; view.current.send = (content) => { if (!is_mounted.current || actions == null) return; const data = { method: "custom", content }; actions.send_comm_message_to_kernel(model_id, data); }; } async function init_phosphor_view(model_id: string): Promise<void> { if (actions == null) return; const widget_manager = actions.widget_manager; if (widget_manager == null) { return; } const view_next = await widget_manager.create_view(model.current); if (!is_mounted.current) return; view.current = view_next as any; const elt = ReactDOM.findDOMNode(phosphorRef.current); if (elt == null) return; pWidget.Widget.attach(view.current.pWidget, elt as any); handle_phosphor_focus(); handle_phosphor_custom_events(model_id); } function renderReactView(): JSX.Element | undefined { if (react_view == null) return; if (typeof react_view == "string") { return ( <div style={{ margin: "5px" }}> <a style={{ color: "white", background: "red", padding: "5px" }} href={"https://github.com/sagemathinc/cocalc/issues/3806"} target={"_blank"} rel={"noopener noreferrer"} > Unsupported Third Party Widget{" "} <code> {model.current.module}.{model.current.name} </code> ... </a> </div> ); } if (model.current == null) return; switch (model.current.name) { case "TabModel": return renderReactTabView(); case "AccordionModel": return renderReactAccordionView(); case "HBoxModel": case "VBoxModel": case "GridBoxView": case "GridBoxModel": case "BoxModel": return renderReactBoxView(); default: // better than nothing. return renderReactBoxView(); } } function renderReactTabView(): JSX.Element | undefined { if (react_view == null) return; if (typeof react_view == "string") return; if (model.current == null) return; const v: JSX.Element[] = []; let i = 0; for (const model_id of react_view.toJS()) { const key = `${i}`; v.push( <Tab eventKey={key} key={key} title={model.current.attributes._titles[i]} > <Widget value={fromJS({ model_id })} actions={actions} name={name} /> </Tab> ); i += 1; } return ( <Tabs activeKey={`${model.current.attributes.selected_index}`} onSelect={(selected_index) => { model.current?.set_state({ selected_index }); }} id={`tabs${model.current.model_id}`} > {v} </Tabs> ); } function renderReactAccordionView(): undefined | JSX.Element { if (react_view == null) return; if (typeof react_view == "string") return; if (model.current == null) return; return ( <div> <div style={{ color: "#888" }}> Accordion not implemented, so falling back to tabs </div> {renderReactTabView()} </div> ); // TODO: we have to upgrade to modern react-bootstrap // (see https://github.com/sagemathinc/cocalc/issues/3782) // or implement this from scratch since our react-bootstrap, // which is doc'd at // https://5c507d49471426000887a6a7--react-bootstrap.netlify.com/components/navs/ // doesn't have Accordion. (There's code // but it isn't documented...). // Actually we are entirely switching away from // bootstrap, so use the accordion here: // https://ant.design/components/collapse/ } function renderReactBoxView(): undefined | JSX.Element { if (react_view == null) return; if (typeof react_view == "string") return; const v: JSX.Element[] = []; let i = 0; for (const model_id of react_view.toJS()) { v.push( <Widget key={i} value={fromJS({ model_id })} actions={actions} name={name} /> ); i += 1; } let cls = "jupyter-widgets widget-container"; switch (model.current.name) { case "BoxModel": cls += " widget-box";<|fim▁hole|> break; case "HBoxModel": cls += " widget-box widget-hbox"; break; case "VBoxModel": cls += " widget-box widget-vbox"; break; case "GridBoxView": case "GridBoxModel": cls += " widget-gridbox"; break; } setTimeout(() => { if (!is_mounted.current) return; // This is a ridiculously horrible hack, but I can // think of no other possible way to do it, and we're // lucky it happens to work (due to internal implementation // details of phosphor). The motivation for this is // that in the function render_phosphor above we // make a react node whose *contents* get managed by // Phosphor for all the interesting widgets such as // text and buttons that are NOT implemented in React. // Unfortunately, all the style and layout of // ipywidgets assumes that this extra level of wrapping // isn't there and is broken by this. So we set things // up like that, then copy the style and class from // the elements that phosphor creates to the wrapper elements // that we create. // See https://github.com/sagemathinc/cocalc/issues/5228 // and https://github.com/sagemathinc/cocalc/pull/5273 const elt = ReactDOM.findDOMNode(reactBoxRef.current); const container = $(elt as any); const children = container.children().children(); for (const child of children) { const a = $(child); const p = a.parent(); p.attr("class", a.attr("class") ?? null); p.attr("style", a.attr("style") ?? null); } }, 1); return ( <div className={cls} style={getLayoutStyle(model.current)} ref={reactBoxRef} > {v} </div> ); } return ( <> {/* This div is managed by phosphor, so don't put any react in it! */} <div key="phosphor" ref={phosphorRef} /> {outputs && ( <div key="output" style={style}> <CellOutputMessages output={outputs} actions={actions} name={name} project_id={project_id} directory={directory} trust={trust} /> </div> )} {renderReactView()} </> ); } ); export function getLayoutStyle(model) { const attributes = model?.attributes?.layout?.attributes; if (attributes == null) return; const style = {}; for (const x in attributes) { if (x.startsWith("_")) continue; const y = attributes[x]; if (y != null) { style[snakeCaseToCamelCase(x)] = y; } } return style; } // Modified version of // https://www.npmjs.com/package/@ivanhanak_com/snake-case-to-camel-case function snakeCaseToCamelCase(string) { let split = string.split("_"); if (split.length) { const firstWord = split.shift(); split = split .map((word) => word.trim()) .filter((word) => word.length > 0) .map((word) => { const firstLetter = word.substring(0, 1).toUpperCase(); const restOfTheWord = word.substring(1).toLowerCase(); return `${firstLetter}${restOfTheWord}`; }); split.unshift(firstWord); return split.join(""); } else { return string; } }<|fim▁end|>
<|file_name|>wrapper.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of holmesalf. # https://github.com/holmes-app/holmes-alf # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT-license # Copyright (c) 2014 Pablo Aguiar [email protected] from holmesalf import BaseAuthNZWrapper from alf.client import Client as AlfSyncClient from tornadoalf.client import Client as AlfAsyncClient class AlfAuthNZWrapper(BaseAuthNZWrapper): """This class gathers authentication and authorization for some of the services used by Holmes""" def __init__(self, config): self.config = config self._sync_client = None self._async_client = None @property def sync_client(self): """Synchronous OAuth 2.0 Bearer client""" if not self._sync_client: self._sync_client = AlfSyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), client_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=self.config.get('OAUTH_CLIENT_SECRET') ) return self._sync_client @property def async_client(self): """Asynchronous OAuth 2.0 Bearer client""" if not self._async_client: self._async_client = AlfAsyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),<|fim▁hole|><|fim▁end|>
client_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=self.config.get('OAUTH_CLIENT_SECRET') ) return self._async_client
<|file_name|>github_test.go<|end_file_name|><|fim▁begin|>package github import ( "bytes" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/openshift/origin/pkg/build/api" "github.com/openshift/origin/pkg/build/webhook" ) type okBuildConfigGetter struct{} func (c *okBuildConfigGetter) Get(namespace, name string) (*api.BuildConfig, error) { return &api.BuildConfig{ Triggers: []api.BuildTriggerPolicy{ { Type: api.GithubWebHookBuildTriggerType, GithubWebHook: &api.WebHookTrigger{ Secret: "secret101", }, }, }, Parameters: api.BuildParameters{ Source: api.BuildSource{ Type: api.BuildSourceGit, Git: &api.GitBuildSource{ URI: "git://github.com/my/repo.git", }, }, Strategy: mockBuildStrategy, }, }, nil } var mockBuildStrategy api.BuildStrategy = api.BuildStrategy{ Type: "STI", STIStrategy: &api.STIBuildStrategy{ From: &kapi.ObjectReference{ Kind: "DockerImage", Name: "repository/image", }, }, } type okBuildConfigInstantiator struct{} func (*okBuildConfigInstantiator) Instantiate(namespace string, requet *api.BuildRequest) (*api.Build, error) { return &api.Build{}, nil } func TestWrongMethod(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() resp, _ := http.Get(server.URL + "/build100/secret101/github") body, _ := ioutil.ReadAll(resp.Body) if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "method") { t.Errorf("Expected BadRequest , got %s: %s!", resp.Status, string(body)) } } func TestWrongContentType(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() client := &http.Client{} req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil) req.Header.Add("Content-Type", "application/text") req.Header.Add("User-Agent", "GitHub-Hookshot/github") req.Header.Add("X-Github-Event", "ping") resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "Content-Type") { t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body)) } } func TestWrongUserAgent(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() client := &http.Client{} req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil) req.Header.Add("Content-Type", "application/json") req.Header.Add("User-Agent", "go-lang") req.Header.Add("X-Github-Event", "ping") resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "User-Agent go-lang") { t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body)) } } func TestMissingGithubEvent(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() client := &http.Client{} req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil) req.Header.Add("Content-Type", "application/json") req.Header.Add("User-Agent", "GitHub-Hookshot/github") resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "X-GitHub-Event") { t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body)) } } func TestWrongGithubEvent(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() client := &http.Client{} req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil) req.Header.Add("Content-Type", "application/json") req.Header.Add("User-Agent", "GitHub-Hookshot/github") req.Header.Add("X-GitHub-Event", "wrong") resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "Unknown") { t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body)) } } func TestJsonPingEvent(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() postFile("ping", "pingevent.json", server.URL+"/build100/secret101/github", http.StatusOK, t) } func TestJsonPushEventError(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() post("push", []byte{}, server.URL+"/build100/secret101/github", http.StatusBadRequest, t) } func TestJsonPushEvent(t *testing.T) { server := httptest.NewServer(webhook.NewController(&okBuildConfigGetter{}, &okBuildConfigInstantiator{}, map[string]webhook.Plugin{"github": New()})) defer server.Close() postFile("push", "pushevent.json", server.URL+"/build100/secret101/github", http.StatusOK, t) } func postFile(event, filename, url string, expStatusCode int, t *testing.T) { data, err := ioutil.ReadFile("fixtures/" + filename) if err != nil { t.Errorf("Failed to open %s: %v", filename, err) } post(event, data, url, expStatusCode, t) } func post(event string, data []byte, url string, expStatusCode int, t *testing.T) { client := &http.Client{} req, err := http.NewRequest("POST", url, bytes.NewReader(data)) if err != nil { t.Errorf("Error creating POST request: %v!", err) } req.Header.Add("Content-Type", "application/json") req.Header.Add("User-Agent", "GitHub-Hookshot/github") req.Header.Add("X-Github-Event", event) resp, err := client.Do(req) if err != nil { t.Errorf("Failed posting webhook to: %s!", url) } body, _ := ioutil.ReadAll(resp.Body) if resp.StatusCode != expStatusCode { t.Errorf("Wrong response code, expecting %d, got %s: %s!", expStatusCode, resp.Status, string(body)) } } type testContext struct { plugin WebHook buildCfg *api.BuildConfig req *http.Request path string } func setup(t *testing.T, filename, eventType string) *testContext { context := testContext{ plugin: WebHook{}, buildCfg: &api.BuildConfig{ Triggers: []api.BuildTriggerPolicy{ { Type: api.GithubWebHookBuildTriggerType, GithubWebHook: &api.WebHookTrigger{ Secret: "secret101", }, }, }, Parameters: api.BuildParameters{ Source: api.BuildSource{ Type: api.BuildSourceGit, Git: &api.GitBuildSource{ URI: "git://github.com/my/repo.git", }, }, Strategy: mockBuildStrategy, }, }, path: "/foobar", } event, err := ioutil.ReadFile("fixtures/" + filename) if err != nil { t.Errorf("Failed to open %s: %v", filename, err) } req, err := http.NewRequest("POST", "http://origin.com", bytes.NewReader(event)) req.Header.Add("Content-Type", "application/json") req.Header.Add("User-Agent", "GitHub-Hookshot/github") req.Header.Add("X-Github-Event", eventType) context.req = req return &context } func TestExtractForAPingEvent(t *testing.T) { //setup context := setup(t, "pingevent.json", "ping") //execute _, proceed, err := context.plugin.Extract(context.buildCfg, "secret101", context.path, context.req) <|fim▁hole|> if err != nil { t.Errorf("Error while extracting build info: %s", err) } if proceed { t.Errorf("The 'proceed' return value should equal 'false' %t", proceed) } } func TestExtractProvidesValidBuildForAPushEvent(t *testing.T) { //setup context := setup(t, "pushevent.json", "push") //execute revision, proceed, err := context.plugin.Extract(context.buildCfg, "secret101", context.path, context.req) //validation if err != nil { t.Errorf("Error while extracting build info: %s", err) } if !proceed { t.Errorf("The 'proceed' return value should equal 'true' %t", proceed) } if revision == nil { t.Error("Expecting the revision to not be nil") } else { if revision.Git.Commit != "9bdc3a26ff933b32f3e558636b58aea86a69f051" { t.Error("Expecting the revision to contain the commit id from the push event") } } } func TestExtractProvidesValidBuildForAPushEventOtherThanMaster(t *testing.T) { //setup context := setup(t, "pushevent-not-master-branch.json", "push") context.buildCfg.Parameters.Source.Git.Ref = "my_other_branch" //execute revision, proceed, err := context.plugin.Extract(context.buildCfg, "secret101", context.path, context.req) //validation if err != nil { t.Errorf("Error while extracting build info: %s", err) } if !proceed { t.Errorf("The 'proceed' return value should equal 'true' %t", proceed) } if revision == nil { t.Error("Expecting the revision to not be nil") } else { if revision.Git.Commit != "9bdc3a26ff933b32f3e558636b58aea86a69f051" { t.Error("Expecting the revision to contain the commit id from the push event") } } } func TestExtractSkipsBuildForUnmatchedBranches(t *testing.T) { //setup context := setup(t, "pushevent.json", "push") context.buildCfg.Parameters.Source.Git.Ref = "adfj32qrafdavckeaewra" //execute _, proceed, _ := context.plugin.Extract(context.buildCfg, "secret101", context.path, context.req) if proceed { t.Errorf("Expecting to not continue from this event because the branch is not for this buildConfig '%s'", context.buildCfg.Parameters.Source.Git.Ref) } }<|fim▁end|>
//validation
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>def get_attributes_display_map(variant, attributes): display = {} for attribute in attributes: value = variant.get_attribute(attribute.pk) if value: choices = {a.pk: a for a in attribute.values.all()} attr = choices.get(value) if attr:<|fim▁hole|> display[attribute.pk] = attr else: display[attribute.pk] = value return display<|fim▁end|>
<|file_name|>TypeA.java<|end_file_name|><|fim▁begin|><|fim▁hole|>public class TypeA extends VisitableType {}<|fim▁end|>
package org.inferred.freevisitor.tests.j8;
<|file_name|>bitcoin_nb.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="nb" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About RipoffCoin</source> <translation>Om RipoffCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;RipoffCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;RipoffCoin&lt;/b&gt; versjon</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Dette er eksperimentell programvare. Distribuert under MIT/X11 programvarelisensen, se medfølgende fil COPYING eller http://www.opensource.org/licenses/mit-license.php. Dette produktet inneholder programvare utviklet av OpenSSL prosjektet for bruk i OpenSSL Toolkit (http://www.openssl.org/) og kryptografisk programvare skrevet av Eric Young ([email protected]) og UPnP programvare skrevet av Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The RipoffCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adressebok</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dobbeltklikk for å redigere adresse eller merkelapp</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Lag en ny adresse</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopier den valgte adressen til systemets utklippstavle</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Ny Adresse</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your RipoffCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Dette er dine RipoffCoin-adresser for mottak av betalinger. Du kan gi forskjellige adresser til alle som skal betale deg for å holde bedre oversikt.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopier Adresse</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Vis &amp;QR Kode</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a RipoffCoin address</source> <translation>Signer en melding for å bevise at du eier en RipoffCoin-adresse</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Signér &amp;Melding</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Slett den valgte adressen fra listen.</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Eksporter data fra nåværende fane til fil</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified RipoffCoin address</source> <translation>Verifiser en melding for å være sikker på at den ble signert av en angitt RipoffCoin-adresse</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiser Melding</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Slett</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your RipoffCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopier &amp;Merkelapp</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Rediger</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Send &amp;Coins</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Eksporter adressebok</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommaseparert fil (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Feil ved eksportering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til filen %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Merkelapp</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ingen merkelapp)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Dialog for Adgangsfrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Angi adgangsfrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Ny adgangsfrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Gjenta ny adgangsfrase</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Skriv inn den nye adgangsfrasen for lommeboken.&lt;br/&gt;Vennligst bruk en adgangsfrase med &lt;b&gt;10 eller flere tilfeldige tegn&lt;/b&gt;, eller &lt;b&gt;åtte eller flere ord&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Krypter lommebok</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Denne operasjonen krever adgangsfrasen til lommeboken for å låse den opp.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Lås opp lommebok</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Denne operasjonen krever adgangsfrasen til lommeboken for å dekryptere den.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dekrypter lommebok</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Endre adgangsfrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Skriv inn gammel og ny adgangsfrase for lommeboken.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bekreft kryptering av lommebok</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR RipoffCoinS&lt;/b&gt;!</source> <translation>Advarsel: Hvis du krypterer lommeboken og mister adgangsfrasen, så vil du &lt;b&gt;MISTE ALLE DINE RipoffCoinS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Er du sikker på at du vil kryptere lommeboken?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>VIKTIG: Tidligere sikkerhetskopier av din lommebok-fil, bør erstattes med den nylig genererte, krypterte filen, da de blir ugyldiggjort av sikkerhetshensyn så snart du begynner å bruke den nye krypterte lommeboken.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Advarsel: Caps Lock er på !</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Lommebok kryptert</translation> </message> <message> <location line="-56"/> <source>RipoffCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your RipoffCoins from being stolen by malware infecting your computer.</source> <translation>RipoffCoin vil nå lukkes for å fullføre krypteringsprosessen. Husk at kryptering av lommeboken ikke fullt ut kan beskytte dine RipoffCoins fra å bli stjålet om skadevare infiserer datamaskinen.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Kryptering av lommebok feilet</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Kryptering av lommebok feilet på grunn av en intern feil. Din lommebok ble ikke kryptert.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>De angitte adgangsfrasene er ulike.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Opplåsing av lommebok feilet</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Adgangsfrasen angitt for dekryptering av lommeboken var feil.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dekryptering av lommebok feilet</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Adgangsfrase for lommebok endret.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Signer &amp;melding...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synkroniserer med nettverk...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Oversikt</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Vis generell oversikt over lommeboken</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transaksjoner</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Vis transaksjonshistorikk</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Rediger listen over adresser og deres merkelapper</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Vis listen over adresser for mottak av betalinger</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Avslutt</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Avslutt applikasjonen</translation> </message> <message> <location line="+4"/> <source>Show information about RipoffCoin</source> <translation>Vis informasjon om RipoffCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Om &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Vis informasjon om Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Innstillinger...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Krypter Lommebok...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Lag &amp;Sikkerhetskopi av Lommebok...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Endre Adgangsfrase...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importere blokker...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indekserer blokker på disk...</translation> </message> <message> <location line="-347"/> <source>Send coins to a RipoffCoin address</source> <translation>Send til en RipoffCoin-adresse</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for RipoffCoin</source> <translation>Endre oppsett for RipoffCoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Sikkerhetskopiér lommebok til annet sted</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Endre adgangsfrasen brukt for kryptering av lommebok</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Feilsøkingsvindu</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Åpne konsoll for feilsøk og diagnostikk</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifiser melding...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>RipoffCoin</source> <translation>RipoffCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Lommebok</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Send</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Motta</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adressebok</translation> </message> <message> <location line="+22"/> <source>&amp;About RipoffCoin</source> <translation>&amp;Om RipoffCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Gjem / vis</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Vis eller skjul hovedvinduet</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Krypter de private nøklene som tilhører lommeboken din</translation> </message> <message> <location line="+7"/> <source>Sign messages with your RipoffCoin addresses to prove you own them</source> <translation>Signér en melding for å bevise at du eier denne adressen</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified RipoffCoin addresses</source> <translation>Bekreft meldinger for å være sikker på at de ble signert av en angitt RipoffCoin-adresse</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Fil</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Innstillinger</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Hjelp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Verktøylinje for faner</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnett]</translation> </message> <message> <location line="+47"/> <source>RipoffCoin client</source> <translation>RipoffCoinklient</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to RipoffCoin network</source> <translation><numerusform>%n aktiv forbindelse til RipoffCoin-nettverket</numerusform><numerusform>%n aktive forbindelser til RipoffCoin-nettverket</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Lastet %1 blokker med transaksjonshistorikk.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transaksjoner etter dette vil ikke være synlige enda.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Denne transaksjonen overstiger størrelsesbegrensningen. Du kan likevel sende den med et gebyr på %1, som går til nodene som prosesserer transaksjonen din og støtter nettverket. Vil du betale gebyret?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ajour</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Kommer ajour...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Bekreft transaksjonsgebyr</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Sendt transaksjon</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Innkommende transaksjon</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dato: %1 Beløp: %2 Type: %3 Adresse: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI håndtering</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid RipoffCoin address or malformed URI parameters.</source> <translation>URI kunne ikke tolkes! Dette kan forårsakes av en ugyldig RipoffCoin-adresse eller feil i URI-parametere.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Lommeboken er &lt;b&gt;kryptert&lt;/b&gt; og for tiden &lt;b&gt;ulåst&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Lommeboken er &lt;b&gt;kryptert&lt;/b&gt; og for tiden &lt;b&gt;låst&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. RipoffCoin can no longer continue safely and will quit.</source> <translation>En fatal feil har inntruffet. Det er ikke trygt å fortsette og RipoffCoin må derfor avslutte.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Nettverksvarsel</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Rediger adresse</translation> </message> <message> <location line="+11"/><|fim▁hole|> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Merkelappen koblet til denne adressen i adresseboken</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresse</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adressen til denne oppføringen i adresseboken. Denne kan kun endres for utsendingsadresser.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Ny mottaksadresse</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Ny utsendingsadresse</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Rediger mottaksadresse</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Rediger utsendingsadresse</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Den oppgitte adressen &quot;%1&quot; er allerede i adresseboken.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid RipoffCoin address.</source> <translation>Den angitte adressed &quot;%1&quot; er ikke en gyldig RipoffCoin-adresse.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kunne ikke låse opp lommeboken.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generering av ny nøkkel feilet.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>RipoffCoin-Qt</source> <translation>RipoffCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versjon</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Bruk:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>kommandolinjevalg</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>valg i brukergrensesnitt</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Sett språk, for eksempel &quot;nb_NO&quot; (standardverdi: fra operativsystem)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Start minimert </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Vis splashskjerm ved oppstart (standardverdi: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Innstillinger</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Hoved</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betal transaksjons&amp;gebyr</translation> </message> <message> <location line="+31"/> <source>Automatically start RipoffCoin after logging in to the system.</source> <translation>Start RipoffCoin automatisk etter innlogging.</translation> </message> <message> <location line="+3"/> <source>&amp;Start RipoffCoin on system login</source> <translation>&amp;Start RipoffCoin ved systeminnlogging</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Nettverk</translation> </message> <message> <location line="+6"/> <source>Automatically open the RipoffCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Åpne automatisk RipoffCoin klientporten på ruteren. Dette virker kun om din ruter støtter UPnP og dette er påslått.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Sett opp port vha. &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the RipoffCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Koble til RipoffCoin-nettverket gjennom en SOCKS proxy (f.eks. ved tilkobling gjennom Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Koble til gjenom SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-adresse for mellomtjener (f.eks. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxyens port (f.eks. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versjon:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Proxyens SOCKS versjon (f.eks. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Vindu</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Vis kun ikon i systemkurv etter minimering av vinduet.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimer til systemkurv istedenfor oppgavelinjen</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimerer vinduet istedenfor å avslutte applikasjonen når vinduet lukkes. Når dette er slått på avsluttes applikasjonen kun ved å velge avslutt i menyen.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimer ved lukking</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Visning</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Språk for brukergrensesnitt</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting RipoffCoin.</source> <translation>Språket for brukergrensesnittet kan settes her. Innstillingen trer i kraft ved omstart av RipoffCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Enhet for visning av beløper:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Velg standard delt enhet for visning i grensesnittet og for sending av RipoffCoins.</translation> </message> <message> <location line="+9"/> <source>Whether to show RipoffCoin addresses in the transaction list or not.</source> <translation>Om RipoffCoin-adresser skal vises i transaksjonslisten eller ikke.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Vis adresser i transaksjonslisten</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Avbryt</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Bruk</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>standardverdi</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Advarsel</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting RipoffCoin.</source> <translation>Denne innstillingen trer i kraft etter omstart av RipoffCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Angitt proxyadresse er ugyldig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Skjema</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the RipoffCoin network after a connection is established, but this process has not completed yet.</source> <translation>Informasjonen som vises kan være foreldet. Din lommebok synkroniseres automatisk med RipoffCoin-nettverket etter at tilkobling er opprettet, men denne prosessen er ikke ferdig enda.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Ubekreftet</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Lommebok</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Umoden:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Minet saldo har ikke modnet enda</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Siste transaksjoner&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Din nåværende saldo</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totalt antall ubekreftede transaksjoner som ikke telles med i saldo enda</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>ute av synk</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start ripoffcoin: click-to-pay handler</source> <translation>Kan ikke starte ripoffcoin: klikk-og-betal håndterer</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Dialog for QR Kode</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Etterspør Betaling</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Beløp:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Merkelapp:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Melding:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Lagre Som...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Feil ved koding av URI i QR kode.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Angitt beløp er ugyldig.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulterende URI for lang, prøv å redusere teksten for merkelapp / melding.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Lagre QR Kode</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG bilder (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Klientnavn</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>-</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Klientversjon</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informasjon</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Bruker OpenSSL versjon</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Oppstartstidspunkt</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Nettverk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Antall tilkoblinger</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>På testnett</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokkjeden</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Nåværende antall blokker</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Estimert totalt antall blokker</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tidspunkt for siste blokk</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Åpne</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Kommandolinjevalg</translation> </message> <message> <location line="+7"/> <source>Show the RipoffCoin-Qt help message to get a list with possible RipoffCoin command-line options.</source> <translation>Vis RipoffCoin-Qt hjelpemelding for å få en liste med mulige kommandolinjevalg.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Vis</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsoll</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Byggedato</translation> </message> <message> <location line="-104"/> <source>RipoffCoin - Debug window</source> <translation>RipoffCoin - vindu for feilsøk</translation> </message> <message> <location line="+25"/> <source>RipoffCoin Core</source> <translation>RipoffCoin Kjerne</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Loggfil for feilsøk</translation> </message> <message> <location line="+7"/> <source>Open the RipoffCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Åpne RipoffCoin loggfil for feilsøk fra datamappen. Dette kan ta noen sekunder for store loggfiler.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Tøm konsoll</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the RipoffCoin RPC console.</source> <translation>Velkommen til RipoffCoin RPC konsoll.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Bruk opp og ned pil for å navigere historikken, og &lt;b&gt;Ctrl-L&lt;/b&gt; for å tømme skjermen.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Skriv &lt;b&gt;help&lt;/b&gt; for en oversikt over kommandoer.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Send RipoffCoins</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Send til flere enn én mottaker</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Legg til Mottaker</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Fjern alle transaksjonsfelter</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Fjern &amp;Alt</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Bekreft sending</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>S&amp;end</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; til %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bekreft sending av RipoffCoins</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Er du sikker på at du vil sende %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> og </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresse for mottaker er ugyldig.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Beløpen som skal betales må være over 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Beløpet overstiger saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totalbeløpet overstiger saldo etter at %1 transaksjonsgebyr er lagt til.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Duplikate adresser funnet. Kan bare sende én gang til hver adresse per operasjon.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Feil: Opprettelse av transaksjon feilet </translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Feil: Transaksjonen ble avvist. Dette kan skje om noe av beløpet allerede var brukt, f.eks. hvis du kopierte wallet.dat og noen RipoffCoins ble brukt i kopien men ikke ble markert som brukt her.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Skjema</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Beløp:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betal &amp;Til:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</source> <translation>Adressen betalingen skal sendes til (f.eks. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Skriv inn en merkelapp for denne adressen for å legge den til i din adressebok</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Merkelapp:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Velg adresse fra adresseboken</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Lim inn adresse fra utklippstavlen</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Fjern denne mottakeren</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a RipoffCoin address (e.g. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</source> <translation>Skriv inn en RipoffCoin adresse (f.eks. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signaturer - Signer / Verifiser en melding</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Signér Melding</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Du kan signere meldinger med dine adresser for å bevise at du eier dem. Ikke signér vage meldinger da phishing-angrep kan prøve å lure deg til å signere din identitet over til andre. Signér kun fullt detaljerte utsagn som du er enig i.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</source> <translation>Adressen for signering av meldingen (f.eks. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Velg en adresse fra adresseboken</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Lim inn adresse fra utklippstavlen</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Skriv inn meldingen du vil signere her</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopier valgt signatur til utklippstavle</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this RipoffCoin address</source> <translation>Signer meldingen for å bevise at du eier denne RipoffCoin-adressen</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Tilbakestill alle felter for meldingssignering</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Fjern &amp;Alt</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiser Melding</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Angi adresse for signering, melding (vær sikker på at du kopierer linjeskift, mellomrom, tab, etc. helt nøyaktig) og signatur under for å verifisere meldingen. Vær forsiktig med at du ikke gir signaturen mer betydning enn det som faktisk står i meldingen, for å unngå å bli lurt av såkalte &quot;man-in-the-middle&quot; angrep.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</source> <translation>Adressen meldingen var signert med (f.eks. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified RipoffCoin address</source> <translation>Verifiser meldingen for å være sikker på at den ble signert av den angitte RipoffCoin-adressen</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Tilbakestill alle felter for meldingsverifikasjon</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a RipoffCoin address (e.g. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</source> <translation>Skriv inn en RipoffCoin adresse (f.eks. RMtv9sBUPxKb2Evcsw8TMaNbAUndmGqaXR)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klikk &quot;Signer Melding&quot; for å generere signatur</translation> </message> <message> <location line="+3"/> <source>Enter RipoffCoin signature</source> <translation>Angi RipoffCoin signatur</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Angitt adresse er ugyldig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Vennligst sjekk adressen og prøv igjen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Angitt adresse refererer ikke til en nøkkel.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Opplåsing av lommebok ble avbrutt.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Privat nøkkel for den angitte adressen er ikke tilgjengelig.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Signering av melding feilet.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Melding signert.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Signaturen kunne ikke dekodes.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Vennligst sjekk signaturen og prøv igjen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Signaturen passer ikke til meldingen.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifikasjon av melding feilet.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Melding verifisert.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The RipoffCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnett]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Åpen til %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/frakoblet</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/ubekreftet</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bekreftelser</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, kringkast gjennom %n node</numerusform><numerusform>, kringkast gjennom %n noder</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Kilde</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generert</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Fra</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Til</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>egen adresse</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>merkelapp</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kredit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>blir moden om %n blokk</numerusform><numerusform>blir moden om %n blokker</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>ikke akseptert</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transaksjonsgebyr</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Nettobeløp</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Melding</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Kommentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaksjons-ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Genererte RipoffCoins må modnes 120 blokker før de kan brukes. Da du genererte denne blokken ble den kringkastet til nettverket for å legges til i blokkjeden. Hvis den ikke kommer inn i kjeden får den tilstanden &quot;ikke akseptert&quot; og vil ikke kunne brukes. Dette skjer noen ganger hvis en annen node genererer en blokk noen sekunder fra din.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informasjon for feilsøk</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transaksjon</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Inndata</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Beløp</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>sann</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>usann</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, har ikke blitt kringkastet uten problemer enda.</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>ukjent</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transaksjonsdetaljer</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Her vises en detaljert beskrivelse av transaksjonen</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Beløp</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Åpen til %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Frakoblet (%1 bekreftelser)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Ubekreftet (%1 av %2 bekreftelser)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Bekreftet (%1 bekreftelser)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokk</numerusform><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokker</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Denne blokken har ikke blitt mottatt av noen andre noder og vil sannsynligvis ikke bli akseptert!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generert men ikke akseptert</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Mottatt med</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Mottatt fra</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betaling til deg selv</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Utvunnet</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>-</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transaksjonsstatus. Hold muspekeren over dette feltet for å se antall bekreftelser.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Dato og tid for da transaksjonen ble mottat.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Type transaksjon.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Mottaksadresse for transaksjonen</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Beløp fjernet eller lagt til saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alle</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>I dag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Denne uken</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Denne måneden</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Forrige måned</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Dette året</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervall...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Mottatt med</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Til deg selv</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Utvunnet</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Andre</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Skriv inn adresse eller merkelapp for søk</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimumsbeløp</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopier adresse</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopier merkelapp</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiér beløp</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopier transaksjons-ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Rediger merkelapp</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Vis transaksjonsdetaljer</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Eksporter transaksjonsdata</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommaseparert fil (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bekreftet</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Merkelapp</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Beløp</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Feil ved eksport</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til filen %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervall:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>til</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Send RipoffCoins</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Eksporter data fra nåværende fane til fil</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Sikkerhetskopier lommebok</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Lommebokdata (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Sikkerhetskopiering feilet</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>En feil oppstod under lagringen av lommeboken til den nye plasseringen.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Sikkerhetskopiering fullført</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Lommebokdata ble lagret til den nye plasseringen. </translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>RipoffCoin version</source> <translation>RipoffCoin versjon</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Bruk:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or RipoffCoind</source> <translation>Send kommando til -server eller RipoffCoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>List opp kommandoer</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Vis hjelpetekst for en kommando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Innstillinger:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: ripoffcoin.conf)</source> <translation>Angi konfigurasjonsfil (standardverdi: ripoffcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: RipoffCoind.pid)</source> <translation>Angi pid-fil (standardverdi: RipoffCoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Angi mappe for datafiler</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Sett størrelse på mellomlager for database i megabytes (standardverdi: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 54001 or testnet: 54002)</source> <translation>Lytt etter tilkoblinger på &lt;port&gt; (standardverdi: 54001 eller testnet: 54002)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Hold maks &lt;n&gt; koblinger åpne til andre noder (standardverdi: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Koble til node for å hente adresser til andre noder, koble så fra igjen</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Angi din egen offentlige adresse</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Grenseverdi for å koble fra noder med dårlig oppførsel (standardverdi: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Antall sekunder noder med dårlig oppførsel hindres fra å koble til på nytt (standardverdi: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>En feil oppstod ved opprettelse av RPC port %u for lytting: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 54010 or testnet: 54011)</source> <translation>Lytt etter JSON-RPC tilkoblinger på &lt;port&gt; (standardverdi: 54010 or testnet: 54011)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Ta imot kommandolinje- og JSON-RPC-kommandoer</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Kjør i bakgrunnen som daemon og ta imot kommandoer</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Bruk testnettverket</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Ta imot tilkoblinger fra utsiden (standardverdi: 1 hvis uten -proxy eller -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=RipoffCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;RipoffCoin Alert&quot; [email protected] </source> <translation>%s, du må angi rpcpassord i konfigurasjonsfilen. %s Det anbefales at du bruker det følgende tilfeldige passordet: rpcbruker=RipoffCoinrpc rpcpassord=%s (du behøver ikke å huske passordet) Brukernavnet og passordet MÅ IKKE være like. Om filen ikke eksisterer, opprett den nå med eier-kun-les filrettigheter. Det er også anbefalt at å sette varselsmelding slik du får melding om problemer. For eksempel: varselmelding=echo %%s | mail -s &quot;RipoffCoin varsel&quot; [email protected]</translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>En feil oppstod under oppsettet av RPC port %u for IPv6, tilbakestilles til IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind til angitt adresse. Bruk [vertsmaskin]:port notasjon for IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. RipoffCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Kjør kommando når relevant varsel blir mottatt (%s i cmd er erstattet med TxID)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Kjør kommando når en lommeboktransaksjon endres (%s i cmd er erstattet med TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Sett maks størrelse for transaksjoner med høy prioritet / lavt gebyr, i bytes (standardverdi: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Advarsel: -paytxfee er satt veldig høyt! Dette er transaksjonsgebyret du betaler når du sender transaksjoner.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Advarsel: Viste transaksjoner kan være feil! Du, eller andre noder, kan trenge en oppgradering.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong RipoffCoin will not work properly.</source> <translation>Advarsel: Vennligst undersøk at din datamaskin har riktig dato og klokkeslett! Hvis klokken er stilt feil vil ikke RipoffCoin fungere riktig.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Valg for opprettelse av blokker:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Koble kun til angitt(e) node(r)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Oppdaget korrupt blokkdatabase</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Oppdag egen IP-adresse (standardverdi: 1 ved lytting og uten -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Ønsker du å gjenopprette blokkdatabasen nå?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Feil under oppstart av lommebokdatabasemiljø %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Feil under åpning av blokkdatabase</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Kunne ikke lytte på noen port. Bruk -listen=0 hvis det er dette du vil.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Finn andre noder gjennom DNS-oppslag (standardverdi: 1 med mindre -connect er oppgit)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Gjenopprett blokkjedeindex fra blk000??.dat filer</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verifiserer blokker...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verifiserer lommebok...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Ugyldig -tor adresse: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maks mottaksbuffer per forbindelse, &lt;n&gt;*1000 bytes (standardverdi: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maks sendebuffer per forbindelse, &lt;n&gt;*1000 bytes (standardverdi: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Koble kun til noder i nettverket &lt;nett&gt; (IPv4, IPv6 eller Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Skriv ekstra informasjon for feilsøk. Medfører at alle -debug* valg tas med</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Skriv ekstra informasjon for feilsøk av nettverk</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Sett tidsstempel på debugmeldinger</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the RipoffCoin Wiki for SSL setup instructions)</source> <translation>SSL valg: (se RipoffCoin Wiki for instruksjoner for oppsett av SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Velg versjon av socks proxy (4-5, standardverdi 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Send spor/debug informasjon til konsollet istedenfor debug.log filen</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Send spor/debug informasjon til debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Sett maks blokkstørrelse i bytes (standardverdi: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Sett minimum blokkstørrelse i bytes (standardverdi: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Krymp debug.log filen når klienten starter (standardverdi: 1 hvis uten -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Angi tidsavbrudd for forbindelse i millisekunder (standardverdi: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Bruk UPnP for lytteport (standardverdi: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Bruk UPnP for lytteport (standardverdi: 1 ved lytting)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Bruk en proxy for å nå skjulte tor tjenester (standardverdi: samme som -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Brukernavn for JSON-RPC forbindelser</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Advarsel: Denne versjonen er foreldet, oppgradering kreves!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Passord for JSON-RPC forbindelser</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Tillat JSON-RPC tilkoblinger fra angitt IP-adresse</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Send kommandoer til node på &lt;ip&gt; (standardverdi: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Eksekvér kommando når beste blokk endrer seg (%s i kommandoen erstattes med blokkens hash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Oppgradér lommebok til nyeste format</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Angi størrelse på nøkkel-lager til &lt;n&gt; (standardverdi: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Se gjennom blokk-kjeden etter manglende lommeboktransaksjoner</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Bruk OpenSSL (https) for JSON-RPC forbindelser</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Servers sertifikat (standardverdi: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Servers private nøkkel (standardverdi: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Akseptable krypteringsmetoder (standardverdi: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Denne hjelpemeldingen</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kan ikke binde til %s på denne datamaskinen (bind returnerte feil %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Koble til gjennom socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Tillat DNS oppslag for -addnode, -seednode og -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Laster adresser...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Feil ved lasting av wallet.dat: Lommeboken er skadet</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of RipoffCoin</source> <translation>Feil ved lasting av wallet.dat: Lommeboken krever en nyere versjon av RipoffCoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart RipoffCoin to complete</source> <translation>Lommeboken måtte skrives om: start RipoffCoin på nytt for å fullføre</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Feil ved lasting av wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ugyldig -proxy adresse: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Ukjent nettverk angitt i -onlynet &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Ukjent -socks proxy versjon angitt: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kunne ikke slå opp -bind adresse: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kunne ikke slå opp -externalip adresse: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ugyldig beløp for -paytxfee=&lt;beløp&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Ugyldig beløp</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Utilstrekkelige midler</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Laster blokkindeks...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Legg til node for tilkobling og hold forbindelsen åpen</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. RipoffCoin is probably already running.</source> <translation>Kan ikke binde til %s på denne datamaskinen. Sannsynligvis kjører RipoffCoin allerede.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Gebyr per KB for transaksjoner du sender</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Laster lommebok...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Kan ikke nedgradere lommebok</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Kan ikke skrive standardadresse</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Leser gjennom...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Ferdig med lasting</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>For å bruke %s opsjonen</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Feil</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Du må sette rpcpassword=&lt;passord&gt; i konfigurasjonsfilen: %s Hvis filen ikke finnes, opprett den med leserettighet kun for eier av filen.</translation> </message> </context> </TS><|fim▁end|>
<source>&amp;Label</source> <translation>&amp;Merkelapp</translation>
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import glob import os.path class Xbraid(MakefilePackage): """XBraid: Parallel time integration with Multigrid""" homepage = "https://computing.llnl.gov/projects/parallel-time-integration-multigrid/software" url = "https://github.com/XBraid/xbraid/archive/v2.2.0.tar.gz" version('2.2.0', sha256='082623b2ddcd2150b3ace65b96c1e00be637876ec6c94dc8fefda88743b35ba3') depends_on('mpi') def build(self, spec, prefix): make('libbraid.a') # XBraid doesn't have a real install target, so it has to be done # manually def install(self, spec, prefix): # Install headers mkdirp(prefix.include) headers = glob.glob('*.h') for f in headers: install(f, join_path(prefix.include, os.path.basename(f))) # Install library mkdirp(prefix.lib) library = 'libbraid.a' install(library, join_path(prefix.lib, library)) # Install other material (e.g., examples, tests, docs) mkdirp(prefix.share)<|fim▁hole|> install_tree('examples', prefix.share.examples) install_tree('drivers', prefix.share.drivers) # TODO: Some of the scripts in 'test' are useful, even for # users; some could be deleted from an installation because # they're not useful to users install_tree('test', prefix.share.test) install_tree('user_utils', prefix.share.user_utils) install_tree('docs', prefix.share.docs) @property def libs(self): return find_libraries('libbraid', root=self.prefix, shared=False, recursive=True)<|fim▁end|>
install('makefile.inc', prefix.share)
<|file_name|>issue-3008-3.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::marker; enum E1 { V1(E2<E1>), } enum E2<T> { V2(E2<E1>, marker::PhantomData<T>), } //~^ ERROR illegal recursive enum type; wrap the inner value in a box to make it representable impl E1 { fn foo(&self) {} } fn main() {<|fim▁hole|><|fim▁end|>
}
<|file_name|>events.js<|end_file_name|><|fim▁begin|>define([ // '../../../../src/utils/event', // '../../../../src/utils/objectCreate' ], function( // Event, // objectCreate ){ var objectCreate = hello.utils.objectCreate; var utils = hello.utils; // // Events // describe('utils / event', function(){ var hello, arbitary_data, event_name; beforeEach(function(){ // Pass an arbitary piece of data around arbitary_data = {boom:true}; event_name = 'custom'; hello = { utils : utils }; utils.Event.call(hello); }); it('should bind events by name and be able to trigger them by name', function(){ // Make request var spy = sinon.spy(function( data, type ){ expect( event_name ).to.be( type ); expect( arbitary_data ).to.be( data ); }); hello.on( event_name, spy ); hello.emit( event_name, arbitary_data ); expect( spy.called ).to.be.ok(); }); it('should listen to any event by using a "*"', function(){ // Make request var spy = sinon.spy(function( data, type ){ expect( event_name ).to.be( type ); expect( arbitary_data ).to.be( data ); }); hello.on( '*', spy ); hello.emit( event_name, arbitary_data ); expect( spy.called ).to.be.ok(); }); it('should unbind an event by name and callback', function(){ // Listeners var spy = sinon.spy(function(){ // should not be called. }); var spy2 = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); hello.on( event_name, spy2 ); // Remove hello.off( event_name, spy ); // Trigger hello.emit( event_name ); // Test spies expect( !spy.called ).to.be.ok(); expect( spy2.called ).to.be.ok(); }); it('should unbind all events by name', function(){ // Listeners var spy = sinon.spy(function(){ // should not be called. }); var spy2 = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); hello.on( event_name, spy2 ); // Remove hello.off( event_name ); // Trigger hello.emit( event_name ); // Test spies expect( !spy.called ).to.be.ok(); expect( !spy2.called ).to.be.ok(); }); it('should trigger events on its proto (predecessor in chain)', function(){ // PROTO // Listeners var spy = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); // PROTO var child = objectCreate(hello);<|fim▁hole|> // should not be called. }); hello.on( event_name, spy2 ); // Trigger hello.emit( event_name ); // Test spies expect( spy.called ).to.be.ok(); expect( spy2.called ).to.be.ok(); }); }); });<|fim▁end|>
var spy2 = sinon.spy(function(){
<|file_name|>list.py<|end_file_name|><|fim▁begin|>from node import Node from fern.ast.tools import simplify, ItemStream from fern.primitives import Undefined class List(Node): def __init__(self): Node.__init__(self) self.children = [] self.value = None def put(self, thingy): if isinstance(thingy, ItemStream): for it in thingy: self.put_item(it) else: self.put_item(thingy) def put_item(self, item): if not item is Undefined: self.reparent(item) self.children.append(item) self.invalidate() def __getitem__(self, index): self.refresh() return self.value[index] def refresh_impl(self): self.value = [] for child in self.children: result = simplify(child) if isinstance(result, ItemStream): for it in result: self.value.append(it)<|fim▁hole|><|fim▁end|>
else: self.value.append(result) def get_children(self): return self.children
<|file_name|>GetCategories.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################### # # GetCategories # Returns the latest category hierarchy for the eBay site. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # 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 temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class GetCategories(Choreography): def __init__(self, temboo_session): """ Create a new instance of the GetCategories Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(GetCategories, self).__init__(temboo_session, '/Library/eBay/Trading/GetCategories') def new_input_set(self): return GetCategoriesInputSet() def _make_result_set(self, result, path): return GetCategoriesResultSet(result, path) def _make_execution(self, session, exec_id, path): return GetCategoriesChoreographyExecution(session, exec_id, path) class GetCategoriesInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the GetCategories Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_CategoryParent(self, value): """ Set the value of the CategoryParent input for this Choreo. ((optional, string) Indicates the ID of the highest-level category to return. Multiple CategoryParent IDs can be specified in a comma-separated list.) """ super(GetCategoriesInputSet, self)._set_input('CategoryParent', value) def set_CategorySiteID(self, value): """ Set the value of the CategorySiteID input for this Choreo. ((optional, string) The ID for the site for which to retrieve the category hierarchy. Use the numeric site code (e.g., 0 for US, 77 for eBay Germany, etc).) """ super(GetCategoriesInputSet, self)._set_input('CategorySiteID', value) def set_DetailLevel(self, value): """ Set the value of the DetailLevel input for this Choreo. ((optional, string) The level of detail to return in the response. Valid values are: ReturnAll.) """ super(GetCategoriesInputSet, self)._set_input('DetailLevel', value) def set_LevelLimit(self, value): """ Set the value of the LevelLimit input for this Choreo. ((optional, string) Indicates the maximum depth of the category hierarchy to retrieve, where the top-level categories (meta-categories) are at level 1. Default is 0.) """ super(GetCategoriesInputSet, self)._set_input('LevelLimit', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) """ super(GetCategoriesInputSet, self)._set_input('ResponseFormat', value) def set_SandboxMode(self, value): """ Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) """<|fim▁hole|> super(GetCategoriesInputSet, self)._set_input('SandboxMode', value) def set_SiteID(self, value): """ Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) """ super(GetCategoriesInputSet, self)._set_input('SiteID', value) def set_UserToken(self, value): """ Set the value of the UserToken input for this Choreo. ((required, string) A valid eBay Auth Token.) """ super(GetCategoriesInputSet, self)._set_input('UserToken', value) def set_ViewAllNodes(self, value): """ Set the value of the ViewAllNodes input for this Choreo. ((optional, boolean) A flag that controls whether all eBay categories are returned, or only leaf categories are returned. To retrieve leaf categories, set this parameter to 'false'.) """ super(GetCategoriesInputSet, self)._set_input('ViewAllNodes', value) class GetCategoriesResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the GetCategories Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) """ return self._output.get('Response', None) class GetCategoriesChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return GetCategoriesResultSet(response, path)<|fim▁end|>
<|file_name|>load_module.cpp<|end_file_name|><|fim▁begin|>#include <pybind11/embed.h> #include <iostream> #include <string> namespace py = pybind11; #include "load_module.h" py::object LoadPyModuleFromFile(const char * file_path) { py::dict locals; locals["path"] = py::cast(file_path); py::eval<py::eval_statements>( // tell eval we're passing multiple statements "import importlib.util\n" "import os\n" "import sys\n" "module_name = os.path.basename(path)[:-3]\n" "try:\n" " new_module = sys.modules[module_name]\n" "except KeyError:\n" " spec = importlib.util.spec_from_file_location(module_name, path)\n" " new_module = importlib.util.module_from_spec(spec)\n" " spec.loader.exec_module(new_module)\n", py::globals(), locals); auto py_module = locals["new_module"]; return py_module; } py::object LoadPyModuleFromString(const char * content, const char * module_name, const char * module_file) { py::dict locals; locals["module_content"] = py::cast(content); locals["module_name"] = py::cast(module_name); locals["module_file"] = py::cast(module_file); py::object result = py::eval<py::eval_statements>( "import importlib.util\n" "import os\n" "import io\n" "import sys\n" "import tempfile\n" "try:\n" " new_module = sys.modules[module_name]\n" "except KeyError:\n" " t_fd, t_path = tempfile.mkstemp(suffix='.py', text=True)\n" " t_f = os.fdopen(t_fd, 'w')\n" " t_f.write(module_content)\n" " t_f.close()\n" " spec = importlib.util.spec_from_file_location(module_name, t_path)\n" " new_module = importlib.util.module_from_spec(spec)\n" " spec.loader.exec_module(new_module)\n" " os.remove(t_path)\n", py::globals(),<|fim▁hole|> locals); return locals["new_module"]; }<|fim▁end|>
<|file_name|>base.py<|end_file_name|><|fim▁begin|># 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<|fim▁hole|> import abc import functools from oslo_utils import excutils import six def rollback_wrapper(original): @functools.wraps(original) def wrap(self): try: return original(self) except Exception as ex: with excutils.save_and_reraise_exception(): self.rollback(ex) return wrap @six.add_metaclass(abc.ABCMeta) class TaskBase(object): def __init__(self, context, instance): self.context = context self.instance = instance @rollback_wrapper def execute(self): """Run task's logic, written in _execute() method """ return self._execute() @abc.abstractmethod def _execute(self): """Descendants should place task's logic here, while resource initialization should be performed over __init__ """ pass def rollback(self, ex): """Rollback failed task Descendants should implement this method to allow task user to rollback status to state before execute method was call """ pass<|fim▁end|>
# License for the specific language governing permissions and limitations # under the License.
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserActivation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('activation_key', models.CharField(max_length=128)), ('key_expires', models.DateTimeField()), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), ]<|fim▁end|>
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-25 18:48 from __future__ import unicode_literals
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![feature(string_split_off)] extern crate ansi_term; #[macro_use] extern crate lazy_static;<|fim▁hole|> pub mod prompt; pub mod command; pub mod functions; pub mod signals; pub mod job_manager;<|fim▁end|>
<|file_name|>test_sensor.py<|end_file_name|><|fim▁begin|>"""Test the Advantage Air Sensor Platform.""" from datetime import timedelta from json import loads from homeassistant.components.advantage_air.const import DOMAIN as ADVANTAGE_AIR_DOMAIN from homeassistant.components.advantage_air.sensor import ( ADVANTAGE_AIR_SERVICE_SET_TIME_TO, ADVANTAGE_AIR_SET_COUNTDOWN_VALUE, ) from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY from homeassistant.const import ATTR_ENTITY_ID from homeassistant.helpers import entity_registry as er from homeassistant.util import dt from tests.common import async_fire_time_changed from tests.components.advantage_air import ( TEST_SET_RESPONSE, TEST_SET_URL, TEST_SYSTEM_DATA, TEST_SYSTEM_URL, add_mock_config, ) async def test_sensor_platform(hass, aioclient_mock): """Test sensor platform.""" aioclient_mock.get( TEST_SYSTEM_URL, text=TEST_SYSTEM_DATA, ) aioclient_mock.get( TEST_SET_URL, text=TEST_SET_RESPONSE, ) await add_mock_config(hass) registry = er.async_get(hass) assert len(aioclient_mock.mock_calls) == 1 # Test First TimeToOn Sensor entity_id = "sensor.ac_one_time_to_on" state = hass.states.get(entity_id) assert state assert int(state.state) == 0 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-timetoOn" value = 20 await hass.services.async_call( ADVANTAGE_AIR_DOMAIN, ADVANTAGE_AIR_SERVICE_SET_TIME_TO, {ATTR_ENTITY_ID: [entity_id], ADVANTAGE_AIR_SET_COUNTDOWN_VALUE: value}, blocking=True, )<|fim▁hole|> assert aioclient_mock.mock_calls[-2][1].path == "/setAircon" data = loads(aioclient_mock.mock_calls[-2][1].query["json"]) assert data["ac1"]["info"]["countDownToOn"] == value assert aioclient_mock.mock_calls[-1][0] == "GET" assert aioclient_mock.mock_calls[-1][1].path == "/getSystemData" # Test First TimeToOff Sensor entity_id = "sensor.ac_one_time_to_off" state = hass.states.get(entity_id) assert state assert int(state.state) == 10 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-timetoOff" value = 0 await hass.services.async_call( ADVANTAGE_AIR_DOMAIN, ADVANTAGE_AIR_SERVICE_SET_TIME_TO, {ATTR_ENTITY_ID: [entity_id], ADVANTAGE_AIR_SET_COUNTDOWN_VALUE: value}, blocking=True, ) assert len(aioclient_mock.mock_calls) == 5 assert aioclient_mock.mock_calls[-2][0] == "GET" assert aioclient_mock.mock_calls[-2][1].path == "/setAircon" data = loads(aioclient_mock.mock_calls[-2][1].query["json"]) assert data["ac1"]["info"]["countDownToOff"] == value assert aioclient_mock.mock_calls[-1][0] == "GET" assert aioclient_mock.mock_calls[-1][1].path == "/getSystemData" # Test First Zone Vent Sensor entity_id = "sensor.zone_open_with_sensor_vent" state = hass.states.get(entity_id) assert state assert int(state.state) == 100 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-z01-vent" # Test Second Zone Vent Sensor entity_id = "sensor.zone_closed_with_sensor_vent" state = hass.states.get(entity_id) assert state assert int(state.state) == 0 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-z02-vent" # Test First Zone Signal Sensor entity_id = "sensor.zone_open_with_sensor_signal" state = hass.states.get(entity_id) assert state assert int(state.state) == 40 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-z01-signal" # Test Second Zone Signal Sensor entity_id = "sensor.zone_closed_with_sensor_signal" state = hass.states.get(entity_id) assert state assert int(state.state) == 10 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-z02-signal" # Test First Zone Temp Sensor (disabled by default) entity_id = "sensor.zone_open_with_sensor_temperature" assert not hass.states.get(entity_id) registry.async_update_entity(entity_id=entity_id, disabled_by=None) await hass.async_block_till_done() async_fire_time_changed( hass, dt.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1), ) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert int(state.state) == 25 entry = registry.async_get(entity_id) assert entry assert entry.unique_id == "uniqueid-ac1-z01-temp"<|fim▁end|>
assert len(aioclient_mock.mock_calls) == 3 assert aioclient_mock.mock_calls[-2][0] == "GET"
<|file_name|>search.component.ts<|end_file_name|><|fim▁begin|>import { Component, EventEmitter, ChangeDetectionStrategy, Output } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Http } from '@angular/http'; import { AlbumService } from '../../services/album/album.service'; import { LoadingService } from '../../services/loading/loading.service'; import { LoadingIndicator } from '../loading/loading.indicator.component'; import { Album } from '../../models'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/debounceTime'; import 'rxjs/add/operator/distinctUntilChanged'; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/merge'; import 'rxjs/add/operator/mapTo'; <|fim▁hole|>@Component({ selector: 'search', templateUrl: 'app/components/search/search.component.html', styleUrls: ['app/components/search/search.component.css'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [AlbumService, LoadingService] }) export class Search { @Output('selected') selected = new EventEmitter(); clear = new EventEmitter(); searchText = new FormControl(); albums: Observable<any>; constructor(http: Http, albumService: AlbumService, loadingService: LoadingService) { this.albums = this.searchText.valueChanges .debounceTime(500) .distinctUntilChanged() .do(() => { console.log("Loading started"); loadingService.toggleLoadingIndicator(true); }) .switchMap((val: string) => albumService.search(val).defaultIfEmpty([])) .do(() => { console.log("Loading finished"); loadingService.toggleLoadingIndicator(false); }) .merge(this.clear.mapTo([])); } onSelect(album) { this.selected.next(album); this.clear.next(''); } }<|fim▁end|>
<|file_name|>step_copy_image.go<|end_file_name|><|fim▁begin|>package uhost import ( "context" "fmt" "github.com/hashicorp/packer/common/retry" "strings" "time" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" "github.com/ucloud/ucloud-sdk-go/ucloud" ) <|fim▁hole|> RegionId string ProjectId string } func (s *stepCopyUCloudImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { if len(s.ImageDestinations) == 0 { return multistep.ActionContinue } client := state.Get("client").(*UCloudClient) conn := client.uhostconn ui := state.Get("ui").(packer.Ui) srcImageId := state.Get("image_id").(string) artifactImages := state.Get("ucloud_images").(*imageInfoSet) expectedImages := newImageInfoSet(nil) ui.Say(fmt.Sprintf("Copying images from %q...", srcImageId)) for _, v := range s.ImageDestinations { if v.ProjectId == s.ProjectId && v.Region == s.RegionId { continue } req := conn.NewCopyCustomImageRequest() req.TargetProjectId = ucloud.String(v.ProjectId) req.TargetRegion = ucloud.String(v.Region) req.SourceImageId = ucloud.String(srcImageId) req.TargetImageName = ucloud.String(v.Name) req.TargetImageDescription = ucloud.String(v.Description) resp, err := conn.CopyCustomImage(req) if err != nil { return halt(state, err, fmt.Sprintf("Error on copying image %q to %s:%s", srcImageId, v.ProjectId, v.Region)) } image := imageInfo{ Region: v.Region, ProjectId: v.ProjectId, ImageId: resp.TargetImageId, } expectedImages.Set(image) artifactImages.Set(image) ui.Message(fmt.Sprintf("Copying image from %s:%s:%s to %s:%s:%s)", s.ProjectId, s.RegionId, srcImageId, v.ProjectId, v.Region, resp.TargetImageId)) } ui.Message("Waiting for the copied images to become available...") err := retry.Config{ Tries: 200, ShouldRetry: func(err error) bool { return isNotCompleteError(err) }, RetryDelay: (&retry.Backoff{InitialBackoff: 2 * time.Second, MaxBackoff: 12 * time.Second, Multiplier: 2}).Linear, }.Run(ctx, func(ctx context.Context) error { for _, v := range expectedImages.GetAll() { imageSet, err := client.describeImageByInfo(v.ProjectId, v.Region, v.ImageId) if err != nil { return fmt.Errorf("reading %s:%s:%s failed, %s", v.ProjectId, v.Region, v.ImageId, err) } if imageSet.State == imageStateAvailable { expectedImages.Remove(v.Id()) continue } } if len(expectedImages.GetAll()) != 0 { return newNotCompleteError("copying image") } return nil }) if err != nil { var s []string for _, v := range expectedImages.GetAll() { s = append(s, fmt.Sprintf("%s:%s:%s", v.ProjectId, v.Region, v.ImageId)) } return halt(state, err, fmt.Sprintf("Error on waiting for copying images %q to become available", strings.Join(s, ","))) } ui.Message(fmt.Sprintf("Copying image complete")) return multistep.ActionContinue } func (s *stepCopyUCloudImage) Cleanup(state multistep.StateBag) { _, cancelled := state.GetOk(multistep.StateCancelled) _, halted := state.GetOk(multistep.StateHalted) if !cancelled && !halted { return } srcImageId := state.Get("image_id").(string) ucloudImages := state.Get("ucloud_images").(*imageInfoSet) imageInfos := ucloudImages.GetAll() if len(imageInfos) == 0 { return } else if len(imageInfos) == 1 && imageInfos[0].ImageId == srcImageId { return } ui := state.Get("ui").(packer.Ui) client := state.Get("client").(*UCloudClient) conn := client.uhostconn ui.Say(fmt.Sprintf("Deleting copied image because of cancellation or error...")) for _, v := range imageInfos { if v.ImageId == srcImageId { continue } req := conn.NewTerminateCustomImageRequest() req.ProjectId = ucloud.String(v.ProjectId) req.Region = ucloud.String(v.Region) req.ImageId = ucloud.String(v.ImageId) _, err := conn.TerminateCustomImage(req) if err != nil { ui.Error(fmt.Sprintf("Error on deleting copied image %q", v.ImageId)) } } ui.Message("Deleting copied image complete") }<|fim▁end|>
type stepCopyUCloudImage struct { ImageDestinations []ImageDestination
<|file_name|>run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """Run pytest with coverage and generate an html report.""" from sys import argv from os import system as run # To run a specific file with debug logging prints: # py -3 -m pytest test_can.py --log-cli-format="%(asctime)s.%(msecs)d %(levelname)s: %(message)s (%(filename)s:%(lineno)d)" --log-cli-level=debug def main(): # noqa run_str = 'python -m coverage run --include={} --omit=./* -m pytest {} {}' <|fim▁hole|> includes = '../*' if len(argv) >= 2: arg = argv[1] if ':' in argv[1]: includes = argv[1].split('::')[0] other_args = ' '.join(argv[2:]) run(run_str.format(includes, arg, other_args)) # Generate the html coverage report and ignore errors run('python -m coverage html -i') if __name__ == '__main__': main()<|fim▁end|>
arg = '' # All source files included in coverage
<|file_name|>image_interpolation_params.py<|end_file_name|><|fim▁begin|># Copyright 2018 The Lucid 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. # ============================================================================== import numpy as np import tensorflow as tf from lucid.optvis.param import lowres_tensor def multi_interpolation_basis(n_objectives=6, n_interp_steps=5, width=128, channels=3): """A paramaterization for interpolating between each pair of N objectives. Sometimes you want to interpolate between optimizing a bunch of objectives, in a paramaterization that encourages images to align. Args: n_objectives: number of objectives you want interpolate between n_interp_steps: number of interpolation steps width: width of intepolated images channel Returns: A [n_objectives, n_objectives, n_interp_steps, width, width, channel]<|fim▁hole|> t[a, i, 0] = t[a, j, 0] for all i, j t[a, a, i] = t[a, a, j] for all i, j t[a, b, i] = t[b, a, -i] for all i """ N, M, W, Ch = n_objectives, n_interp_steps, width, channels const_term = sum([lowres_tensor([W, W, Ch], [W//k, W//k, Ch]) for k in [1, 2, 4, 8]]) const_term = tf.reshape(const_term, [1, 1, 1, W, W, Ch]) example_interps = [ sum([lowres_tensor([M, W, W, Ch], [2, W//k, W//k, Ch]) for k in [1, 2, 4, 8]]) for _ in range(N)] example_basis = [] for n in range(N): col = [] for m in range(N): interp = example_interps[n] + example_interps[m][::-1] col.append(interp) example_basis.append(col) interp_basis = [] for n in range(N): col = [interp_basis[m][N-n][::-1] for m in range(n)] col.append(tf.zeros([M, W, W, 3])) for m in range(n+1, N): interp = sum([lowres_tensor([M, W, W, Ch], [M, W//k, W//k, Ch]) for k in [1, 2]]) col.append(interp) interp_basis.append(col) basis = [] for n in range(N): col_ex = tf.stack(example_basis[n]) col_in = tf.stack(interp_basis[n]) basis.append(col_ex + col_in) basis = tf.stack(basis) return basis + const_term<|fim▁end|>
shaped tensor, t, where the final [width, width, channel] should be seen as images, such that the following properties hold: t[a, b] = t[b, a, ::-1]
<|file_name|>artificial-block.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> fn f() -> isize { { return 3; } } pub fn main() { assert_eq!(f(), 3); }<|fim▁end|>
// run-pass
<|file_name|>linux.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import os from pathlib import Path from scripts.build_env import BuildEnv, Platform from scripts.platform_builder import PlatformBuilder class pugixmlLinuxBuilder(PlatformBuilder): def __init__(self, config_package: dict=None,<|fim▁hole|> def build(self): build_path = '{}/{}/scripts/build'.format( self.env.source_path, self.config['name'] ) # if os.path.exists(self.env.install_lib_path+'/libpugixml.a'): _check = self.env.install_lib_path / self.config.get("checker") if os.path.exists(_check): self.tag_log("Already built.") return self.tag_log("Start building ...") BuildEnv.mkdir_p(build_path) os.chdir(build_path) cmd = '{} cmake -DCMAKE_INSTALL_LIBDIR={} -DCMAKE_INSTALL_INCLUDEDIR={} ..; make -j {}; make install'.format( self.env.BUILD_FLAG, self.env.install_lib_path, self.env.install_include_path, self.env.NJOBS ) self.env.run_command(cmd, module_name=self.config['name'])<|fim▁end|>
config_platform: dict=None): super().__init__(config_package, config_platform)
<|file_name|>utils.go<|end_file_name|><|fim▁begin|><|fim▁hole|> package convert import ( "strings" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" ) // ToCorrectPageSize makes sure page size is in allowed range. func ToCorrectPageSize(size int) int { if size <= 0 { size = setting.API.DefaultPagingNum } else if size > setting.API.MaxResponseItems { size = setting.API.MaxResponseItems } return size } // ToGitServiceType return GitServiceType based on string func ToGitServiceType(value string) structs.GitServiceType { switch strings.ToLower(value) { case "github": return structs.GithubService case "gitea": return structs.GiteaService case "gitlab": return structs.GitlabService case "gogs": return structs.GogsService default: return structs.PlainGitService } }<|fim▁end|>
// Copyright 2020 The Gitea Authors. All rights reserved. // Copyright 2016 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file.
<|file_name|>stmt_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2016 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. """Tests for StatementVisitor.""" from __future__ import unicode_literals import re import subprocess import textwrap import unittest from grumpy_tools.compiler import block from grumpy_tools.compiler import imputil from grumpy_tools.compiler import shard_test from grumpy_tools.compiler import stmt from grumpy_tools.compiler import util from grumpy_tools.vendor import pythonparser from grumpy_tools.vendor.pythonparser import ast class StatementVisitorTest(unittest.TestCase): def testAssertNoMsg(self): self.assertEqual((0, 'AssertionError()\n'), _GrumpRun(textwrap.dedent("""\ try: assert False except AssertionError as e: print repr(e)"""))) def testAssertMsg(self): want = (0, "AssertionError('foo',)\n") self.assertEqual(want, _GrumpRun(textwrap.dedent("""\ try: assert False, 'foo' except AssertionError as e: print repr(e)"""))) def testBareAssert(self): # Assertion errors at the top level of a block should raise: # https://github.com/google/grumpy/issues/18 want = (0, 'ok\n') self.assertEqual(want, _GrumpRun(textwrap.dedent("""\ def foo(): assert False try: foo() except AssertionError: print 'ok' else: print 'bad'"""))) def testAssignAttribute(self): self.assertEqual((0, '123\n'), _GrumpRun(textwrap.dedent("""\ e = Exception() e.foo = 123 print e.foo"""))) def testAssignName(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ foo = 'bar' print foo"""))) def testAssignMultiple(self): self.assertEqual((0, 'baz baz\n'), _GrumpRun(textwrap.dedent("""\ foo = bar = 'baz' print foo, bar"""))) def testAssignSubscript(self): self.assertEqual((0, "{'bar': None}\n"), _GrumpRun(textwrap.dedent("""\ foo = {} foo['bar'] = None print foo"""))) def testAssignTuple(self): self.assertEqual((0, 'a b\n'), _GrumpRun(textwrap.dedent("""\ baz = ('a', 'b') foo, bar = baz print foo, bar"""))) def testAugAssign(self): self.assertEqual((0, '42\n'), _GrumpRun(textwrap.dedent("""\ foo = 41 foo += 1 print foo"""))) def testAugAssignBitAnd(self): self.assertEqual((0, '3\n'), _GrumpRun(textwrap.dedent("""\ foo = 7 foo &= 3 print foo"""))) def testAugAssignPow(self): self.assertEqual((0, '64\n'), _GrumpRun(textwrap.dedent("""\ foo = 8 foo **= 2 print foo"""))) def testClassDef(self): self.assertEqual((0, "<type 'type'>\n"), _GrumpRun(textwrap.dedent("""\ class Foo(object): pass print type(Foo)"""))) def testClassDefWithVar(self): self.assertEqual((0, 'abc\n'), _GrumpRun(textwrap.dedent("""\ class Foo(object): bar = 'abc' print Foo.bar"""))) def testDeleteAttribute(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\ class Foo(object): bar = 42 del Foo.bar print hasattr(Foo, 'bar')"""))) def testDeleteClassLocal(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\ class Foo(object): bar = 'baz' del bar print hasattr(Foo, 'bar')"""))) def testDeleteGlobal(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\ foo = 42 del foo print 'foo' in globals()"""))) def testDeleteLocal(self): self.assertEqual((0, 'ok\n'), _GrumpRun(textwrap.dedent("""\ def foo(): bar = 123 del bar try: print bar raise AssertionError except UnboundLocalError: print 'ok' foo()"""))) def testDeleteNonexistentLocal(self): self.assertRaisesRegexp( util.ParseError, 'cannot delete nonexistent local', _ParseAndVisit, 'def foo():\n del bar') def testDeleteSubscript(self): self.assertEqual((0, '{}\n'), _GrumpRun(textwrap.dedent("""\ foo = {'bar': 'baz'} del foo['bar'] print foo"""))) def testExprCall(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ def foo(): print 'bar' foo()"""))) def testExprNameGlobal(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ foo = 42 foo"""))) def testExprNameLocal(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ foo = 42 def bar(): foo bar()"""))) def testFor(self): self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent("""\ for i in (1, 2, 3): print i"""))) def testForBreak(self): self.assertEqual((0, '1\n'), _GrumpRun(textwrap.dedent("""\ for i in (1, 2, 3): print i break"""))) def testForContinue(self): self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent("""\ for i in (1, 2, 3): print i continue raise AssertionError"""))) def testForElse(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\ for i in (1,): print 'foo' else: print 'bar'"""))) def testForElseBreakNotNested(self): self.assertRaisesRegexp( util.ParseError, "'continue' not in loop", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') def testForElseContinueNotNested(self): self.assertRaisesRegexp( util.ParseError, "'continue' not in loop", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') def testFunctionDecorator(self): self.assertEqual((0, '<b>foo</b>\n'), _GrumpRun(textwrap.dedent("""\ def bold(fn): return lambda: '<b>' + fn() + '</b>' @bold def foo(): return 'foo' print foo()"""))) def testFunctionDecoratorWithArg(self): self.assertEqual((0, '<b id=red>foo</b>\n'), _GrumpRun(textwrap.dedent("""\ def tag(name): def bold(fn): return lambda: '<b id=' + name + '>' + fn() + '</b>' return bold @tag('red') def foo(): return 'foo' print foo()"""))) def testFunctionDef(self): self.assertEqual((0, 'bar baz\n'), _GrumpRun(textwrap.dedent("""\ def foo(a, b): print a, b foo('bar', 'baz')"""))) def testFunctionDefGenerator(self): self.assertEqual((0, "['foo', 'bar']\n"), _GrumpRun(textwrap.dedent("""\ def gen(): yield 'foo' yield 'bar' print list(gen())"""))) def testFunctionDefGeneratorReturnValue(self): self.assertRaisesRegexp( util.ParseError, 'returning a value in a generator function', _ParseAndVisit, 'def foo():\n yield 1\n return 2') def testFunctionDefLocal(self): self.assertEqual((0, 'baz\n'), _GrumpRun(textwrap.dedent("""\ def foo(): def bar(): print 'baz' bar() foo()"""))) def testIf(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ if 123: print 'foo' if '': print 'bar'"""))) def testIfElif(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\ if True: print 'foo' elif False: print 'bar' if False: print 'foo' elif True: print 'bar'"""))) def testIfElse(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\ if True: print 'foo' else: print 'bar' if False: print 'foo' else: print 'bar'"""))) def testImport(self): self.assertEqual((0, "<type 'dict'>\n"), _GrumpRun(textwrap.dedent("""\ import sys print type(sys.modules)"""))) def testImportFutureLateRaises(self): regexp = 'from __future__ imports must occur at the beginning of the file' self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'foo = bar\nfrom __future__ import print_function') <|fim▁hole|> from __future__ import unicode_literals print repr('foo')"""))) def testImportMember(self): self.assertEqual((0, "<type 'dict'>\n"), _GrumpRun(textwrap.dedent("""\ from sys import modules print type(modules)"""))) def testImportConflictingPackage(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ import time from "__go__/time" import Now"""))) def testImportNative(self): self.assertEqual((0, '1 1000000000\n'), _GrumpRun(textwrap.dedent("""\ from "__go__/time" import Nanosecond, Second print Nanosecond, Second"""))) def testImportGrumpy(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ from "__go__/grumpy" import Assert Assert(__frame__(), True, 'bad')"""))) def testImportNativeType(self): self.assertEqual((0, "<type 'Duration'>\n"), _GrumpRun(textwrap.dedent("""\ from "__go__/time" import Duration print Duration"""))) def testImportWildcardMemberRaises(self): regexp = 'wildcard member import is not implemented' self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'from foo import *') self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'from "__go__/foo" import *') def testPrintStatement(self): self.assertEqual((0, 'abc 123\nfoo bar\n'), _GrumpRun(textwrap.dedent("""\ print 'abc', print '123' print 'foo', 'bar'"""))) def testPrintFunction(self): want = "abc\n123\nabc 123\nabcx123\nabc 123 " self.assertEqual((0, want), _GrumpRun(textwrap.dedent("""\ "module docstring is ok to proceed __future__" from __future__ import print_function print('abc') print(123) print('abc', 123) print('abc', 123, sep='x') print('abc', 123, end=' ')"""))) def testRaiseExitStatus(self): self.assertEqual(1, _GrumpRun('raise Exception')[0]) def testRaiseInstance(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ try: raise RuntimeError('foo') print 'bad' except RuntimeError as e: print e"""))) def testRaiseTypeAndArg(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ try: raise KeyError('foo') print 'bad' except KeyError as e: print e"""))) def testRaiseAgain(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ try: try: raise AssertionError('foo') except AssertionError: raise except Exception as e: print e"""))) def testRaiseTraceback(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ import sys try: try: raise Exception except: e, _, tb = sys.exc_info() raise e, None, tb except: e2, _, tb2 = sys.exc_info() assert e is e2 assert tb is tb2"""))) def testReturn(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ def foo(): return 'bar' print foo()"""))) def testTryBareExcept(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ try: raise AssertionError except: pass"""))) def testTryElse(self): self.assertEqual((0, 'foo baz\n'), _GrumpRun(textwrap.dedent("""\ try: print 'foo', except: print 'bar' else: print 'baz'"""))) def testTryMultipleExcept(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ try: raise AssertionError except RuntimeError: print 'foo' except AssertionError: print 'bar' except: print 'baz'"""))) def testTryFinally(self): result = _GrumpRun(textwrap.dedent("""\ try: print 'foo', finally: print 'bar' try: print 'foo', raise Exception finally: print 'bar'""")) self.assertEqual(1, result[0]) self.assertIn('foo bar\nfoo bar\n', result[1]) self.assertIn('Exception\n', result[1]) def testWhile(self): self.assertEqual((0, '2\n1\n'), _GrumpRun(textwrap.dedent("""\ i = 2 while i: print i i -= 1"""))) def testWhileElse(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ while False: print 'foo' else: print 'bar'"""))) def testWith(self): self.assertEqual((0, 'enter\n1\nexit\nenter\n2\nexit\n3\n'), _GrumpRun(textwrap.dedent("""\ class ContextManager(object): def __enter__(self): print "enter" def __exit__(self, exc_type, value, traceback): print "exit" a = ContextManager() with a: print 1 try: with a: print 2 raise RuntimeError except RuntimeError: print 3 """))) def testWithAs(self): self.assertEqual((0, '1 2 3\n'), _GrumpRun(textwrap.dedent("""\ class ContextManager(object): def __enter__(self): return (1, (2, 3)) def __exit__(self, *args): pass with ContextManager() as [x, (y, z)]: print x, y, z """))) def testWriteExceptDispatcherBareExcept(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=ast.Name(id='foo')), ast.ExceptHandler(type=None)] self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access 'exc', 'tb', handlers), [1, 2]) expected = re.compile(r'ResolveGlobal\(.*foo.*\bIsInstance\(.*' r'goto Label1.*goto Label2', re.DOTALL) self.assertRegexpMatches(visitor.writer.getvalue(), expected) def testWriteExceptDispatcherBareExceptionNotLast(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=None), ast.ExceptHandler(type=ast.Name(id='foo'))] self.assertRaisesRegexp(util.ParseError, r"default 'except:' must be last", visitor._write_except_dispatcher, # pylint: disable=protected-access 'exc', 'tb', handlers) def testWriteExceptDispatcherMultipleExcept(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=ast.Name(id='foo')), ast.ExceptHandler(type=ast.Name(id='bar'))] self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access 'exc', 'tb', handlers), [1, 2]) expected = re.compile( r'ResolveGlobal\(.*foo.*\bif .*\bIsInstance\(.*\{.*goto Label1.*' r'ResolveGlobal\(.*bar.*\bif .*\bIsInstance\(.*\{.*goto Label2.*' r'\bRaise\(exc\.ToObject\(\), nil, tb\.ToObject\(\)\)', re.DOTALL) self.assertRegexpMatches(visitor.writer.getvalue(), expected) def _MakeModuleBlock(): return block.ModuleBlock(None, '__main__', '<test>', '', imputil.FutureFeatures()) def _ParseAndVisit(source): mod = pythonparser.parse(source) _, future_features = imputil.parse_future_features(mod) importer = imputil.Importer(None, 'foo', 'foo.py', False) b = block.ModuleBlock(importer, '__main__', '<test>', source, future_features) visitor = stmt.StatementVisitor(b) visitor.visit(mod) return visitor def _GrumpRun(cmd): p = subprocess.Popen(['grumpy', 'run'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = p.communicate(cmd) return p.returncode, out if __name__ == '__main__': shard_test.main()<|fim▁end|>
def testFutureUnicodeLiterals(self): want = "u'foo'\n" self.assertEqual((0, want), _GrumpRun(textwrap.dedent("""\
<|file_name|>CallableAndFutureTest.java<|end_file_name|><|fim▁begin|>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test.thread; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Administrator */ public class CallableAndFutureTest { private final ExecutorService executor = Executors.newFixedThreadPool(2); void start() throws Exception { final Callable<List<Integer>> task = new Callable<List<Integer>>() { public List<Integer> call() throws Exception { // get obj final List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { Thread.sleep(50); list.add(i); } return list; } }; final Future<List<Integer>> future = executor.submit(task); //do sthing others.. //example: due to show some data.. try { final List<Integer> list = future.get(); //这个函数还可以接受超时检测http://www.javaeye.com/topic/671314 System.out.println(list); } catch (final InterruptedException ex) { Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex); future.cancel(true); } catch (final ExecutionException ex) { Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex); throw new ExecutionException(ex); } finally { executor.shutdown(); } } public static void main(final String args[]) { try { new CallableAndFutureTest().start(); } catch (final Exception ex) { Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex); }<|fim▁hole|>}<|fim▁end|>
}
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>############################################################################ # This file is part of LImA, a Library for Image Acquisition # # Copyright (C) : 2009-2011 # European Synchrotron Radiation Facility # BP 220, Grenoble 38043 # FRANCE # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. ############################################################################ import os root_name = __path__[0] csadmin_dirs = ['/csadmin/local', '/csadmin/common'] script_get_os = 'scripts/get_compat_os.share' get_os = None for d in csadmin_dirs: aux_get_os = os.path.join(d, script_get_os)<|fim▁hole|>if get_os is not None: compat_plat = os.popen(get_os).readline().strip() plat = None compat_plat_list = compat_plat.split() for aux_plat in compat_plat_list: if aux_plat.strip() in os.listdir(root_name): plat = aux_plat break if plat is None: raise ImportError, ('Could not find Lima directory for %s ' '(nor compat. %s) platform(s) at %s' % (compat_plat_list[0], compat_plat_list[1:], root_name)) lima_plat = os.path.join(root_name, plat) __path__.insert(0, lima_plat) # This mandatory variable is systematically overwritten by 'make install' os.environ['LIMA_LINK_STRICT_VERSION'] = 'MINOR' if get_os is not None: all_dirs = os.listdir(lima_plat) all_dirs.remove('lib') __all__ = all_dirs del plat, compat_plat, aux_plat, lima_plat, all_dirs del root_name, csadmin_dirs, get_os, script_get_os, d, aux_get_os del os<|fim▁end|>
if os.path.exists(aux_get_os): get_os = aux_get_os break
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
from .tornadoconnection import TornadoLDAPConnection
<|file_name|>application.ts<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 * as _ from 'lodash'; export class ApplicationType { public name: string; public id: string; public description: string; public icon: string; public oauth?: any; public configuration: any; public default_grant_types: Array<any>; public requires_redirect_uris: boolean; public allowed_grant_types: Array<any>; public mandatory_grant_types: Array<any>; constructor({ name, id, description, requires_redirect_uris, allowed_grant_types, default_grant_types, mandatory_grant_types }) { this.id = id; this.name = name; this.description = description; this.requires_redirect_uris = requires_redirect_uris; this.allowed_grant_types = allowed_grant_types; this.default_grant_types = default_grant_types; this.mandatory_grant_types = mandatory_grant_types; this.icon = this.getIcon(); } public isOauth() { return this.id.toLowerCase() !== 'simple'; } public isGrantTypeMandatory(grantType: { type }): boolean { return this.mandatory_grant_types && _.indexOf(this.mandatory_grant_types, grantType.type) !== -1; } private getIcon() { switch (this.id.toUpperCase()) { case 'BROWSER': return 'computer'; case 'WEB': return 'language'; case 'NATIVE': return 'phone_android'; case 'BACKEND_TO_BACKEND': return 'share'; default: return 'pan_tool'; }<|fim▁hole|><|fim▁end|>
} }
<|file_name|>java.ts<|end_file_name|><|fim▁begin|>class System { static out = { println(obj?:any) { console.log(obj); }, print(obj:any) { console.log(obj); } }; static err = { println(obj?:any) { console.log(obj); }, print(obj:any) { console.log(obj); } }; static arraycopy(src:Number[], srcPos:number, dest:Number[], destPos:number, numElements:number):void { for (var i = 0; i < numElements; i++) { dest[destPos + i] = src[srcPos + i]; } } } var TSMap = Map; var TSSet = Set; interface Number { equals : (other:Number) => boolean; longValue() : number; floatValue() : number; intValue() : number; shortValue() : number; } Number.prototype.equals = function (other) { return this == other; }; interface String { equals : (other:String) => boolean; startsWith : (other:String) => boolean; endsWith : (other:String) => boolean; matches : (regEx:String) => boolean; //getBytes : () => number[]; isEmpty : () => boolean; } class StringUtils { static copyValueOf (data:string[], offset:number, count:number) : string { var result : string = ""; for(var i = offset; i < offset+count;i++) { result += data[i]; } return result; } } String.prototype.matches = function (regEx) { return this.match(regEx).length > 0; }; String.prototype.isEmpty = function () { return this.length == 0; }; String.prototype.equals = function (other) { return this == other; }; String.prototype.startsWith = function (other) { for (var i = 0; i < other.length; i++) { if (other.charAt(i) != this.charAt(i)) { return false; } } return true; }; String.prototype.endsWith = function (other) { for (var i = other.length - 1; i >= 0; i--) { if (other.charAt(i) != this.charAt(i)) { return false; } } return true; }; module java { export module lang { export class Double { public static parseDouble(val:string):number { return +val; } } export class Float { public static parseFloat(val:string):number { return +val; } } export class Integer { public static parseInt(val:string):number { return +val; } } export class Long { public static parseLong(val:string):number { return +val; } } export class Short { public static MIN_VALUE = -0x8000; public static MAX_VALUE = 0x7FFF; public static parseShort(val:string):number { return +val; } } export class Throwable { private message:string; private error:Error; constructor(message:string) { this.message = message; this.error = new Error(message); } printStackTrace() { console.error(this.error['stack']); } } export class Exception extends Throwable {} export class RuntimeException extends Exception {} export class IndexOutOfBoundsException extends Exception {} export class StringBuilder { buffer = ""; public length = 0; append(val:any):StringBuilder { this.buffer = this.buffer + val; length = this.buffer.length; return this; } toString():string { return this.buffer; } } } export module util { export class Random { public nextInt(max:number):number { return Math.random() * max; } } export class Arrays { static fill(data:Number[], begin:number, nbElem:number, param:number):void { var max = begin + nbElem; for (var i = begin; i < max; i++) { data[i] = param; } } } export class Collections { public static reverse<A>(p:List<A>):void { var temp = new List<A>(); for (var i = 0; i < p.size(); i++) { temp.add(p.get(i)); } p.clear(); for (var i = temp.size() - 1; i >= 0; i--) { p.add(temp.get(i)); } } public static sort<A>(p:List<A>):void { p.sort(); } } export class Collection<T> { add(val:T):void { throw new java.lang.Exception("Abstract implementation"); } addAll(vals:Collection<T>):void { throw new java.lang.Exception("Abstract implementation"); } remove(val:T):void { throw new java.lang.Exception("Abstract implementation"); } clear():void { throw new java.lang.Exception("Abstract implementation"); } isEmpty():boolean { throw new java.lang.Exception("Abstract implementation"); } size():number { throw new java.lang.Exception("Abstract implementation"); } contains(val:T):boolean { throw new java.lang.Exception("Abstract implementation"); } toArray(a:Array<T>):T[] { throw new java.lang.Exception("Abstract implementation"); } } export class List<T> extends Collection<T> { sort() { this.internalArray = this.internalArray.sort((a, b)=> { if (a == b) { return 0; } else { if (a < b) { return -1; } else { return 1; } } }); } private internalArray:Array<T> = []; addAll(vals:Collection<T>) { var tempArray = vals.toArray(null); for (var i = 0; i < tempArray.length; i++) { this.internalArray.push(tempArray[i]); } } clear() { this.internalArray = []; } public poll():T { return this.internalArray.shift(); } remove(val:T) { //TODO with filter } toArray(a:Array<T>):T[] { //TODO var result = new Array<T>(this.internalArray.length); this.internalArray.forEach((value:T, index:number, p1:T[])=> { result[index] = value; }); return result; } size():number { return this.internalArray.length; } add(val:T):void { this.internalArray.push(val); } get(index:number):T { return this.internalArray[index]; } contains(val:T):boolean { for (var i = 0; i < this.internalArray.length; i++) { if (this.internalArray[i] == val) { return true; } } return false; } isEmpty():boolean { return this.internalArray.length == 0; } } export class ArrayList<T> extends List<T> { } export class LinkedList<T> extends List<T> { } export class Map<K, V> { get(key:K):V { return this.internalMap.get(key); } put(key:K, value:V):void { this.internalMap.set(key, value); } containsKey(key:K):boolean { return this.internalMap.has(key); } remove(key:K):V { var tmp = this.internalMap.get(key); this.internalMap.delete(key); return tmp; } keySet():Set<K> { var result = new HashSet<K>(); this.internalMap.forEach((value:V, index:K, p1)=> { result.add(index); }); return result; } isEmpty():boolean { return this.internalMap.size == 0; } values():Set<V> { var result = new HashSet<V>(); this.internalMap.forEach((value:V, index:K, p1)=> { result.add(value); }); return result; } private internalMap = new TSMap<K,V>(); clear():void { this.internalMap = new TSMap<K,V>(); } } export class HashMap<K, V> extends Map<K,V> { } export class Set<T> extends Collection<T> { private internalSet = new TSSet<T>(); add(val:T) { this.internalSet.add(val); } clear() { this.internalSet = new TSSet<T>(); } contains(val:T):boolean { return this.internalSet.has(val); } addAll(vals:Collection<T>) { var tempArray = vals.toArray(null); for (var i = 0; i < tempArray.length; i++) { this.internalSet.add(tempArray[i]); } } remove(val:T) { this.internalSet.delete(val); } size():number { return this.internalSet.size; } isEmpty():boolean { return this.internalSet.size == 0; } toArray(other:Array<T>):T[] { var result = new Array<T>(this.internalSet.size); var i = 0; this.internalSet.forEach((value:T, index:T, origin)=> { result[i] = value; i++; }); return result; } } export class HashSet<T> extends Set<T> { } } } module org { export module junit { export class Assert { public static assertNotNull(p:any):void { if (p == null) { throw "Assert Error " + p + " must not be null"; } } public static assertNull(p:any):void { if (p != null) { throw "Assert Error " + p + " must be null"; } } public static assertEquals(p:any, p2:any):void { if(p.equals !== undefined) { if(!p.equals(p2)) { throw "Assert Error \n" + p + "\n must be equal to \n" + p2 + "\n"; } } else { if (p != p2) { throw "Assert Error \n" + p + "\n must be equal to \n" + p2 + "\n"; } } } public static assertNotEquals(p:any, p2:any):void { if(p.equals !== undefined) {<|fim▁hole|> throw "Assert Error \n" + p + "\n must not be equal to \n" + p2 + "\n"; } } else { if (p == p2) { throw "Assert Error \n" + p + "\n must not be equal to \n" + p2 + "\n"; } } } public static assertTrue(b:boolean):void { if (!b) { throw "Assert Error " + b + " must be true"; } } } } }<|fim▁end|>
if(p.equals(p2)) {
<|file_name|>Asteroid.java<|end_file_name|><|fim▁begin|>package septemberpack.september; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import java.util.Random; /** * Created by Vlady on 22.10.2015. */ /** * Данный класс реализует отрисовку астероидов */ public class Asteroid { Bitmap bitmap; /** * Координаты первого астероида */ private int line1x; private int line1y; /** * Координаты второго астероида */ private int line2x; private int line2y; /** * Координаты третьего астероида */ private int line3x; private int line3y; private Random random; /** * Конструктор получающий объект картинки будущего астероида и * задающий астероидам рандомные координаты * @param bmp - объект картинки астероида */ public Asteroid(Bitmap bmp){ this.bitmap = bmp; random = new Random(); line1x = random.nextInt(880); line2x = random.nextInt(880); line3x = random.nextInt(880); line1y = -random.nextInt(300); line2y = -random.nextInt(300) - 400; // За пределом экрана минус 400 line3y = -random.nextInt(300) - 800; // За пределом экрана минус 800 } /** * Метод отрисовки астероидов * @param canvas - прямоугольная область экрана для рисования */ public void draw(Canvas canvas){ canvas.drawBitmap(bitmap, line1x, line1y, null); // Первая линия canvas.drawBitmap(bitmap, line2x, line2y, null); // Вторая линия canvas.drawBitmap(bitmap, line3x, line3y, null); // Третья линия } /**<|fim▁hole|> line1y = -80; line1x = random.nextInt(880); } else if(line2y > 1400) { line2y = -80; line2x = random.nextInt(880); } else if(line3y > 1400) { line3y = -80; line3x = random.nextInt(880); } line1y += GamePanel.speed; line2y += GamePanel.speed; line3y += GamePanel.speed; } /* * Методы возвращают прямоугольную область астероида по его координатам, для проверки столкновения с кораблем * Реализацию можно было уместить в один метод с четырьмя параметрами, но его вызов был бы нечитаемым * Поскольку присутствуют всего три астероида, мы имеем возможность сделать для каждого свой метод */ public Rect getAsteroid1(){ return new Rect(line1x, line1y, line1x + 100, line1y + 120); } public Rect getAsteroid2(){ return new Rect(line2x, line2y, line2x + 100, line2y + 120); } public Rect getAsteroid3(){ return new Rect(line3x, line3y, line3x + 100, line3y + 120); } }<|fim▁end|>
* Метод обновляющий координаты астероидов и задающий новые координаты при уплытии за границы фона */ public void update(){ if(line1y > 1400) {
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC. from __future__ import print_function import os import sys import yaml weechat_is_fake = False try: import weechat except:<|fim▁hole|> def command(self, cmd): print(cmd) weechat = FakeWeechat() weechat_is_fake = True class IgnoreRule: """An ignore rule. This provides instrumentation for converting ignore rules into weechat filters. It handles both types of ignore-together ignore rules. """ def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]): self.ignorelist = ignorelist self.rulename = rulename.replace(' ', '_') self.rationale = rationale self.typename = typename self.hostmasks = hostmasks self.accountnames = accountnames self.patterns = patterns def install(self): "Install an ignore rule." subrule_ctr = 0 if self.typename == 'ignore': for pattern in self.hostmasks: weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern)) subrule_ctr += 1 # XXX - accountnames elif self.typename == 'message': for pattern in self.patterns: weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern)) subrule_ctr += 1 def uninstall(self): "Uninstall an ignore rule." subrule_ctr = 0 if self.typename == 'ignore': for pattern in self.hostmasks: weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr)) subrule_ctr += 1 elif self.typename == 'message': for pattern in self.patterns: weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr)) subrule_ctr += 1 class IgnoreRuleSet: """A downloaded collection of rules. Handles merging updates vs current state, and so on.""" def __init__(self, name, uri): self.name = name self.uri = uri self.rules = [] def load(self): def build_rules(s): for k, v in s.items(): self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', []))) def test_load_cb(payload): build_rules(yaml.load(payload)) if weechat_is_fake: d = open(self.uri, 'r') return test_load_cb(d.read()) def install(self): [r.install() for r in self.rules] def uninstall(self): [r.uninstall() for r in self.rules] rules = {}<|fim▁end|>
class FakeWeechat:
<|file_name|>use-uninit-match.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn foo<T>(o: myoption<T>) -> int { let mut x: int = 5; match o { none::<T> => { } some::<T>(_t) => { x += 1; }<|fim▁hole|> enum myoption<T> { none, some(T), } pub fn main() { info!("{}", 5); }<|fim▁end|>
} return x; }
<|file_name|>cordova-config.spec.js<|end_file_name|><|fim▁begin|>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cordovaConfig = require("./cordova-config"); describe('parseConfig function', function () { it('should return {} when the config does not contain a widget', function () { var result = cordovaConfig.parseConfig({}); expect(result).toEqual({}); }); it('should return a CordovaProject without id or version if config.$ does not exist', function () { var result = cordovaConfig.parseConfig({ widget: { name: ['thename'], } }); expect(result).toEqual({ name: 'thename', }); }); it('should return a CordovaProject on success', function () { var result = cordovaConfig.parseConfig({ widget: { name: ['thename'], $: {<|fim▁hole|> version: 'theversion' } } }); expect(result).toEqual({ name: 'thename', id: 'theid', version: 'theversion' }); }); }); /* describe('buildCordovaConfig', () => { it('should read the config.xml file', (done) => { let fs: any = jest.genMockFromModule('fs'); fs.readFile = jest.fn().mockReturnValue('blah'); jest.mock('xml2js', function() { return { Parser: function() { return { parseString: function (data, cb) { cb(null, 'parseConfigData'); } }; } }; }); function daCallback() { expect(fs.readfile).toHaveBeenCalledWith('config.xml'); done(); } cordovaConfig.buildCordovaConfig(daCallback, daCallback); }); }); */<|fim▁end|>
id: 'theid',
<|file_name|>models.ts<|end_file_name|><|fim▁begin|>namespace DashCI.Resources.Github { export interface IRepository extends ng.resource.IResource<IRepository> { id: number; name: string; full_name: string; } export interface IIssue extends ng.resource.IResource<IIssue> { } export interface ICount extends ng.resource.IResource<ICount> {<|fim▁hole|><|fim▁end|>
count: number; } }
<|file_name|>query.js<|end_file_name|><|fim▁begin|>var dns = require('native-dns'), util = require('util'); var question = dns.Question({ name: 'www.google.com', type: 'A', // could also be the numerical representation }); var start = new Date().getTime(); var req = dns.Request({ question: question, server: '8.8.8.8', /* // Optionally you can define an object with these properties, // only address is required server: { address: '8.8.8.8', port: 53, type: 'udp' }, */ timeout: 1000, /* Optional -- default 4000 (4 seconds) */ }); req.on('timeout', function () { console.log('Timeout in making request');<|fim▁hole|> else console.log(res); /* answer, authority, additional are all arrays with ResourceRecords */ res.answer.forEach(function (a) { /* promote goes from a generic ResourceRecord to A, AAAA, CNAME etc */ console.log(a.address); }); }); req.on('end', function () { /* Always fired at the end */ var delta = (new Date().getTime()) - start; console.log('Finished processing request: ' + delta.toString() + 'ms'); }); req.send();<|fim▁end|>
}); req.on('message', function (err, res) { if(err) console.error(err, res);
<|file_name|>data.go<|end_file_name|><|fim▁begin|>package prune import ( "fmt" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/cache" kapi "k8s.io/kubernetes/pkg/apis/core" appsapi "github.com/openshift/origin/pkg/apps/apis/apps" appsutil "github.com/openshift/origin/pkg/apps/util" ) // DeploymentByDeploymentConfigIndexFunc indexes Deployment items by their associated DeploymentConfig, if none, index with key "orphan" func DeploymentByDeploymentConfigIndexFunc(obj interface{}) ([]string, error) { controller, ok := obj.(*kapi.ReplicationController) if !ok { return nil, fmt.Errorf("not a replication controller: %v", obj) } name := appsutil.DeploymentConfigNameFor(controller) if len(name) == 0 { return []string{"orphan"}, nil } return []string{controller.Namespace + "/" + name}, nil } // Filter filters the set of objects type Filter interface { Filter(items []*kapi.ReplicationController) []*kapi.ReplicationController } // andFilter ands a set of predicate functions to know if it should be included in the return set type andFilter struct { filterPredicates []FilterPredicate } // Filter ands the set of predicates evaluated against each item to make a filtered set func (a *andFilter) Filter(items []*kapi.ReplicationController) []*kapi.ReplicationController { results := []*kapi.ReplicationController{} for _, item := range items { include := true for _, filterPredicate := range a.filterPredicates { include = include && filterPredicate(item) } if include { results = append(results, item) } } return results } // FilterPredicate is a function that returns true if the object should be included in the filtered set type FilterPredicate func(item *kapi.ReplicationController) bool // NewFilterBeforePredicate is a function that returns true if the build was created before the current time minus specified duration func NewFilterBeforePredicate(d time.Duration) FilterPredicate { now := metav1.Now() before := metav1.NewTime(now.Time.Add(-1 * d)) return func(item *kapi.ReplicationController) bool { return item.CreationTimestamp.Before(&before) } } // FilterDeploymentsPredicate is a function that returns true if the replication controller is associated with a DeploymentConfig func FilterDeploymentsPredicate(item *kapi.ReplicationController) bool { return len(appsutil.DeploymentConfigNameFor(item)) > 0 } // FilterZeroReplicaSize is a function that returns true if the replication controller size is 0 func FilterZeroReplicaSize(item *kapi.ReplicationController) bool { return item.Spec.Replicas == 0 && item.Status.Replicas == 0 } // DataSet provides functions for working with deployment data type DataSet interface { GetDeploymentConfig(deployment *kapi.ReplicationController) (*appsapi.DeploymentConfig, bool, error) ListDeploymentConfigs() ([]*appsapi.DeploymentConfig, error) ListDeployments() ([]*kapi.ReplicationController, error) ListDeploymentsByDeploymentConfig(config *appsapi.DeploymentConfig) ([]*kapi.ReplicationController, error) } type dataSet struct { deploymentConfigStore cache.Store deploymentIndexer cache.Indexer } // NewDataSet returns a DataSet over the specified items func NewDataSet(deploymentConfigs []*appsapi.DeploymentConfig, deployments []*kapi.ReplicationController) DataSet { deploymentConfigStore := cache.NewStore(cache.MetaNamespaceKeyFunc) for _, deploymentConfig := range deploymentConfigs { deploymentConfigStore.Add(deploymentConfig) } deploymentIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{ "deploymentConfig": DeploymentByDeploymentConfigIndexFunc, }) for _, deployment := range deployments { deploymentIndexer.Add(deployment) } return &dataSet{ deploymentConfigStore: deploymentConfigStore, deploymentIndexer: deploymentIndexer, } } // GetDeploymentConfig gets the configuration for the given deployment func (d *dataSet) GetDeploymentConfig(controller *kapi.ReplicationController) (*appsapi.DeploymentConfig, bool, error) { name := appsutil.DeploymentConfigNameFor(controller) if len(name) == 0 { return nil, false, nil } var deploymentConfig *appsapi.DeploymentConfig key := &appsapi.DeploymentConfig{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: controller.Namespace}} item, exists, err := d.deploymentConfigStore.Get(key) if exists { deploymentConfig = item.(*appsapi.DeploymentConfig) } return deploymentConfig, exists, err } // ListDeploymentConfigs returns a list of DeploymentConfigs func (d *dataSet) ListDeploymentConfigs() ([]*appsapi.DeploymentConfig, error) { results := []*appsapi.DeploymentConfig{} for _, item := range d.deploymentConfigStore.List() {<|fim▁hole|> // ListDeployments returns a list of deployments func (d *dataSet) ListDeployments() ([]*kapi.ReplicationController, error) { results := []*kapi.ReplicationController{} for _, item := range d.deploymentIndexer.List() { results = append(results, item.(*kapi.ReplicationController)) } return results, nil } // ListDeploymentsByDeploymentConfig returns a list of deployments for the provided configuration func (d *dataSet) ListDeploymentsByDeploymentConfig(deploymentConfig *appsapi.DeploymentConfig) ([]*kapi.ReplicationController, error) { results := []*kapi.ReplicationController{} key := &kapi.ReplicationController{ ObjectMeta: metav1.ObjectMeta{ Namespace: deploymentConfig.Namespace, Annotations: map[string]string{appsapi.DeploymentConfigAnnotation: deploymentConfig.Name}, }, } items, err := d.deploymentIndexer.Index("deploymentConfig", key) if err != nil { return nil, err } for _, item := range items { results = append(results, item.(*kapi.ReplicationController)) } return results, nil }<|fim▁end|>
results = append(results, item.(*appsapi.DeploymentConfig)) } return results, nil }
<|file_name|>script-explicit.rs<|end_file_name|><|fim▁begin|>extern crate boolinator; use boolinator::Boolinator; fn main() {<|fim▁hole|> println!("--output--"); println!("{:?}", true.as_some(1)); }<|fim▁end|>
<|file_name|>pages.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon<|fim▁hole|># weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. from decimal import Decimal from weboob.deprecated.browser import Page from weboob.capabilities import NotAvailable from weboob.capabilities.pricecomparison import Product, Shop, Price class IndexPage(Page): def get_token(self): input = self.parser.select(self.document.getroot(), 'div#localisation input#recherche_recherchertype__token', 1) return input.attrib['value'] def iter_products(self): for li in self.parser.select(self.document.getroot(), 'div#choix_carbu ul li'): input = li.find('input') label = li.find('label') product = Product(input.attrib['value']) product.name = unicode(label.text.strip()) if '&' in product.name: # "E10 & SP95" produces a non-supported table. continue yield product class ComparisonResultsPage(Page): def get_product_name(self): th = self.document.getroot().cssselect('table#tab_resultat tr th') if th and len(th) == 9: return u'%s' % th[5].find('a').text def iter_results(self, product=None): price = None product.name = self.get_product_name() for tr in self.document.getroot().cssselect('table#tab_resultat tr'): tds = self.parser.select(tr, 'td') if tds and len(tds) == 9 and product is not None: price = Price('%s.%s' % (product.id, tr.attrib['id'])) price.product = product price.cost = Decimal(tds[5].text.replace(',', '.')) price.currency = u'€' shop = Shop(price.id) shop.name = unicode(tds[3].text.strip()) shop.location = unicode(tds[2].text.strip()) price.shop = shop price.set_empty_fields(NotAvailable) yield price class ShopInfoPage(Page): def get_info(self): return self.parser.tostring(self.parser.select(self.document.getroot(), 'div.infos', 1))<|fim▁end|>
# # This file is part of weboob. #
<|file_name|>bitcoin_bs.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="bs" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About SpamSlayer</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;SpamSlayer&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The SpamSlayer developers</source><|fim▁hole|> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your SpamSlayer addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a SpamSlayer address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified SpamSlayer address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>SpamSlayer will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show information about SpamSlayer</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a SpamSlayer address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for SpamSlayer</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-202"/> <source>SpamSlayer</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+180"/> <source>&amp;About SpamSlayer</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+60"/> <source>SpamSlayer client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to SpamSlayer network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About SpamSlayer card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about SpamSlayer card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid SpamSlayer address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. SpamSlayer can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid SpamSlayer address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>SpamSlayer-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start SpamSlayer after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start SpamSlayer on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the SpamSlayer client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the SpamSlayer network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting SpamSlayer.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show SpamSlayer addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting SpamSlayer.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the SpamSlayer network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the SpamSlayer-Qt help message to get a list with possible SpamSlayer command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>SpamSlayer - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>SpamSlayer Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the SpamSlayer debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the SpamSlayer RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 hack</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>123.456 hack</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a SpamSlayer address (e.g. SpamSlayerfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid SpamSlayer address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. SpamSlayerfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a SpamSlayer address (e.g. SpamSlayerfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. SpamSlayerfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this SpamSlayer address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. SpamSlayerfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified SpamSlayer address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a SpamSlayer address (e.g. SpamSlayerfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter SpamSlayer signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovaj mjesec</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošli mjesec</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>SpamSlayer version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to -server or SpamSlayerd</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: SpamSlayer.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: SpamSlayerd.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong SpamSlayer will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=SpamSlayerrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;SpamSlayer Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. SpamSlayer is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>SpamSlayer</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of SpamSlayer</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart SpamSlayer to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. SpamSlayer is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<translation type="unfinished"/> </message>
<|file_name|>OptionsRestRequest.java<|end_file_name|><|fim▁begin|>/** * Copyright (C) 2013 * by 52 North Initiative for Geospatial Open Source Software GmbH * * Contact: Andreas Wytzisk * 52 North Initiative for Geospatial Open Source Software GmbH * Martin-Luther-King-Weg 24 * 48155 Muenster, Germany * [email protected] * * This program is free software; you can redistribute and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * * This program is distributed WITHOUT ANY WARRANTY; even without the implied * WARRANTY OF MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program (see gnu-gpl v2.txt). If not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or * visit the Free Software Foundation web page, http://www.fsf.org. */ package org.n52.sos.binding.rest.resources; import org.n52.sos.binding.rest.requests.RestRequest; /** * @author <a href="mailto:[email protected]">Eike Hinderk J&uuml;rrens</a> * */ public class OptionsRestRequest implements RestRequest { <|fim▁hole|> private boolean isGlobalResource; private boolean isResourceCollection; public OptionsRestRequest(String resourceType, boolean isGlobalResource, boolean isResourceCollection) { this.resourceType = resourceType; this.isGlobalResource = isGlobalResource; this.isResourceCollection = isResourceCollection; } public String getResourceType() { return resourceType; } public boolean isGlobalResource() { return isGlobalResource; } public boolean isResourceCollection() { return isResourceCollection; } }<|fim▁end|>
private String resourceType;
<|file_name|>ImageServerUtils.java<|end_file_name|><|fim▁begin|>// ********************************************************************** // // <copyright> // // BBN Technologies // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> // ********************************************************************** // // $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServerUtils.java,v $ // $RCSfile: ImageServerUtils.java,v $ // $Revision: 1.10 $ // $Date: 2006/02/16 16:22:49 $ // $Author: dietrick $ // // ********************************************************************** package com.bbn.openmap.image; import java.awt.Color; import java.awt.Paint; import java.awt.geom.Point2D; import java.util.Properties; import com.bbn.openmap.omGraphics.OMColor; import com.bbn.openmap.proj.Proj; import com.bbn.openmap.proj.Projection; import com.bbn.openmap.proj.ProjectionFactory; import com.bbn.openmap.util.Debug; import com.bbn.openmap.util.PropUtils; /** * A class to contain convenience functions for parsing web image requests. */ public class ImageServerUtils implements ImageServerConstants { /** * Create an OpenMap projection from the values stored in a Properties * object. The properties inside should be parsed out from a map request, * with the keywords being those defined in the ImageServerConstants * interface. Assumes that the shared instance of the ProjectionFactory has * been initialized with the expected Projections. */ public static Proj createOMProjection(Properties props, Projection defaultProj) { float scale = PropUtils.floatFromProperties(props, SCALE, defaultProj.getScale()); int height = PropUtils.intFromProperties(props, HEIGHT, defaultProj.getHeight()); int width = PropUtils.intFromProperties(props, WIDTH, defaultProj.getWidth()); Point2D llp = defaultProj.getCenter(); float longitude = PropUtils.floatFromProperties(props, LON, (float) llp.getX()); float latitude = PropUtils.floatFromProperties(props, LAT, (float) llp.getY()); Class<? extends Projection> projClass = null; String projType = props.getProperty(PROJTYPE); ProjectionFactory projFactory = ProjectionFactory.loadDefaultProjections(); if (projType != null) { projClass = projFactory.getProjClassForName(projType); } if (projClass == null) { projClass = defaultProj.getClass();<|fim▁hole|> + projClass.getName() + ", with HEIGHT = " + height + ", WIDTH = " + width + ", lat = " + latitude + ", lon = " + longitude + ", scale = " + scale); } Proj proj = (Proj) projFactory.makeProjection(projClass, new Point2D.Float(longitude, latitude), scale, width, height); return (Proj) proj; } /** * Create a Color object from the properties TRANSPARENT and BGCOLOR * properties. Default color returned is white. * * @param props the Properties containing background color information. * @return Color object for background. */ public static Color getBackground(Properties props) { return (Color) getBackground(props, Color.white); } /** * Create a Color object from the properties TRANSPARENT and BGCOLOR * properties. Default color returned is white. * * @param props the Properties containing background color information. * @param defPaint the default Paint to use in case the color isn't defined * in the properties. * @return Color object for background. */ public static Paint getBackground(Properties props, Paint defPaint) { boolean transparent = PropUtils.booleanFromProperties(props, TRANSPARENT, false); Paint backgroundColor = PropUtils.parseColorFromProperties(props, BGCOLOR, defPaint); if (backgroundColor == null) { backgroundColor = Color.white; } if (transparent) { if (backgroundColor instanceof Color) { Color bgc = (Color) backgroundColor; backgroundColor = new Color(bgc.getRed(), bgc.getGreen(), bgc.getBlue(), 0x00); } else { backgroundColor = OMColor.clear; } } if (Debug.debugging("imageserver")) { Debug.output("ImageServerUtils.createOMProjection: projection color: " + (backgroundColor instanceof Color ? Integer.toHexString(((Color) backgroundColor).getRGB()) : backgroundColor.toString()) + ", transparent(" + transparent + ")"); } return backgroundColor; } }<|fim▁end|>
} if (Debug.debugging("imageserver")) { Debug.output("ImageServerUtils.createOMProjection: projection "
<|file_name|>apitest.py<|end_file_name|><|fim▁begin|>from leapp.topics import Topic <|fim▁hole|><|fim▁end|>
class ApiTestTopic(Topic): name = 'api_test'
<|file_name|>moment_curve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """<|fim▁hole|> """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return<|fim▁end|>
Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995).
<|file_name|>middleware.py<|end_file_name|><|fim▁begin|># coding=utf-8 from django.utils.functional import SimpleLazyObject from mongo_auth import get_user as mongo_auth_get_user def get_user(request): if not hasattr(request, '_cached_user'): request._cached_user = mongo_auth_get_user(request) return request._cached_user class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request)) class SessionAuthenticationMiddleware(object): """ Formerly, a middleware for invalidating a user's sessions that don't correspond to the user's current session authentication hash. However, it caused the "Vary: Cookie" header on all responses. Now a backwards compatibility shim that enables session verification in auth.get_user() if this middleware is in MIDDLEWARE_CLASSES. """ def process_request(self, request):<|fim▁hole|><|fim▁end|>
pass
<|file_name|>eventlist.component.ts<|end_file_name|><|fim▁begin|>import {Component, EventEmitter, OnInit, TemplateRef, ViewEncapsulation} from '@angular/core'; import {routerTransition} from '../../router.animations'; import { CalendarService } from '../calendar.service'; import { Eventdate, Windy } from '../eventdate'; import 'rxjs/Rx'; import {environment} from "../../../environments/environment"; import { Http, Response } from '@angular/http'; @Component({ selector: 'app-eventlist', templateUrl: './eventlist.component.html', styleUrls: ['./eventlist.component.scss'], animations: [routerTransition()], host: {'[@routerTransition]': ''} }) export class EventlistComponent implements OnInit { viewDate: Date = new Date(); days : Array<Eventdate>; image; <|fim▁hole|> constructor(private http: Http, public calser: CalendarService) { } ngOnInit() { let year = '' + this.viewDate.getFullYear(); let month = '' + (this.viewDate.getMonth() + 1); this.calser.getMonthData(year, month).then((json: Array<Eventdate>) =>{ this.days = json; }); this.http.get(environment.API_ENDPOINT+'pageimage') .map((res: Response) => res.json()).subscribe((json: Object) =>{ this.image = json[0]['main_image']['image']; }); } reload(){ let year = '' + this.viewDate.getFullYear(); let month = '' + (this.viewDate.getMonth() + 1); this.calser.getMonthData(year, month).then((json: Array<Eventdate>) =>{ this.days = json; }); } previous() { this.viewDate.setMonth(this.viewDate.getMonth() - 1); this.reload(); } next() { this.viewDate.setMonth(this.viewDate.getMonth() + 1); this.reload(); } }<|fim▁end|>
<|file_name|>spec.js<|end_file_name|><|fim▁begin|>isClear = true; function context(description, spec) { describe(description, spec); }; function build() { $('body').append('<div id="element"></div>'); }; function buildDivTarget() { $('body').append('<div id="hint"></div>'); }; function buildComboboxTarget() { $('body').append( '<select id="hint">' + '<option value="Cancel this rating!">cancel hint default</option>' + '<option value="cancel-hint-custom">cancel hint custom</option>' + '<option value="">cancel number default</option>' + '<option value="0">cancel number custom</option>' + '<option value="bad">bad hint imutable</option>' + '<option value="1">bad number imutable</option>' + '<option value="targetText">targetText is setted without targetKeep</option>' + '<option value="score: bad">targetFormat</option>' + '</select>' ); }; function buildTextareaTarget() { $('body').append('<textarea id="hint"></textarea>'); }; function buildTextTarget() { $('body').append('<input id="hint" type="text" />'); }; function clear() { if (isClear) { $('#element').remove(); $('#hint').remove(); } }; describe('Raty', function() { beforeEach(function() { build(); }); afterEach(function() { clear(); }); it ('has the right values', function() { // given var raty = $.fn.raty // when var opt = raty.defaults // then expect(opt.cancel).toBeFalsy(); expect(opt.cancelHint).toEqual('Cancel this rating!'); expect(opt.cancelOff).toEqual('cancel-off.png'); expect(opt.cancelOn).toEqual('cancel-on.png'); expect(opt.cancelPlace).toEqual('left'); expect(opt.click).toBeUndefined(); expect(opt.half).toBeFalsy(); expect(opt.halfShow).toBeTruthy(); expect(opt.hints).toContain('bad', 'poor', 'regular', 'good', 'gorgeous'); expect(opt.iconRange).toBeUndefined(); expect(opt.mouseover).toBeUndefined(); expect(opt.noRatedMsg).toEqual('Not rated yet!'); expect(opt.number).toBe(5); expect(opt.path).toEqual(''); expect(opt.precision).toBeFalsy(); expect(opt.readOnly).toBeFalsy(); expect(opt.round.down).toEqual(.25); expect(opt.round.full).toEqual(.6); expect(opt.round.up).toEqual(.76); expect(opt.score).toBeUndefined(); expect(opt.scoreName).toEqual('score'); expect(opt.single).toBeFalsy(); expect(opt.size).toBe(16); expect(opt.space).toBeTruthy(); expect(opt.starHalf).toEqual('star-half.png'); expect(opt.starOff).toEqual('star-off.png'); expect(opt.starOn).toEqual('star-on.png'); expect(opt.target).toBeUndefined(); expect(opt.targetFormat).toEqual('{score}'); expect(opt.targetKeep).toBeFalsy(); expect(opt.targetText).toEqual(''); expect(opt.targetType).toEqual('hint'); expect(opt.width).toBeUndefined(); }); describe('common features', function() { it ('is chainable', function() { // given var self = $('#element'); // when var ref = self.raty(); // then expect(ref).toBe(self); }); it ('creates the default markup', function() { // given var self = $('#element'); // when self.raty(); // then var imgs = self.children('img'), score = self.children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); }); }); describe('#star', function() { it ('starts all off', function() { // given var self = $('#element'); // when self.raty(); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); context('on :mouseover', function() { it ('turns on the stars', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); }); context('and :mouseout', function() { it ('clears all stars', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); context('on rating', function() { it ('changes the score', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(1).mouseover().click(); // then expect(self.children('input')).toHaveValue(2); }); context('on :mouseout', function() { it ('keeps the stars on', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover().click().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); }); }); }); }); describe('options', function() { describe('#numberMax', function() { it ('limits to 20 stars', function() { // given var self = $('#element').raty({ number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(self.children('img').length).toEqual(20); expect(self.children('input')).toHaveValue(20); }); context('with custom numberMax', function() { it ('chages the limit', function() { // given var self = $('#element').raty({ numberMax: 10, number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(self.children('img').length).toEqual(10); expect(self.children('input')).toHaveValue(10); }); }); }); describe('#starOff', function() { it ('changes the icons', function() { // given var self = $('#element'); // when self.raty({ starOff: 'icon.png' }); // then expect(self.children('img')).toHaveAttr('src', 'icon.png'); }); }); describe('#starOn', function() { it ('changes the icons', function() { // given var self = $('#element').raty({ starOn: 'icon.png' }), imgs = self.children('img'); // when imgs.eq(3).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(1)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(2)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(3)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); }); describe('#iconRange', function() { it ('uses icon intervals', function() { // given var self = $('#element'); // when self.raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); context('when off icon is not especified', function() { it ('uses the :starOff icon', function() { // given var self = $('#element'); // when self.raty({ iconRange: [ { range: 2, on: 'on.png', off: 'off.png' }, { range: 3, on: 'on.png', off: 'off.png' }, { range: 4, on: 'on.png', off: 'off.png' }, { range: 5, on: 'on.png' } ] }); // then expect(self.children('img').eq(4)).toHaveAttr('src', 'star-off.png'); }); }); context('on mouseover', function() { it ('uses the on icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd.png'); }); context('when on icon is not especified', function() { it ('uses the :starOn icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, off: 'off.png', on: 'on.png' }, { range: 3, off: 'off.png', on: 'on.png' }, { range: 4, off: 'off.png', on: 'on.png' }, { range: 5, off: 'off.png' } ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'on.png'); expect(imgs.eq(2)).toHaveAttr('src', 'on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'on.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-on.png'); }); }); }); context('on mouseout', function() { it ('changes to off icons', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' }, ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); self.mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); it ('keeps the score value', function() { // given var self = $('#element').raty({ iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ], score : 1 }); // when self.children('img').eq(4).mouseover(); self.mouseleave(); // then expect(self.children('input')).toHaveValue(1); }); context('when off icon is not especified', function() { it ('uses the :starOff icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'on.png', off: 'off.png' }, { range: 3, on: 'on.png', off: 'off.png' }, { range: 4, on: 'on.png', off: 'off.png' }, { range: 5, on: 'on.png' } ] }), img = self.children('img').eq(4); // when img.mouseover(); self.mouseleave(); // then expect(img).toHaveAttr('src', 'star-off.png'); }); }); }); }); describe('#click', function() { it ('has `this` as the self element', function() { // given var self = $('#element').raty({ click: function() { $(this).data('self', this); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('self')).toBe(self); }); it ('is called on star click', function() { // given var self = $('#element').raty({ click: function() { $(this).data('clicked', true); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('clicked')).toBeTruthy(); }); it ('receives the score', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('score')).toEqual(1); }); context('with :cancel', function() { it ('executes cancel click callback', function() { // given var self = $('#element').raty({ cancel: true, click : function(score) { $(this).data('score', null); } }); // when self.children('.raty-cancel').mouseover().click().mouseleave(); // then expect(self.data('score')).toBeNull(); }); }); }); describe('#score', function() { it ('starts with value', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then expect(self.children('input')).toHaveValue(1); }); it ('turns on 1 stars', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ score: function() { return 1; } }); // then expect(self.raty('score')).toEqual(1); }); context('with negative number', function() { it ('gets none score', function() { // given var self = $('#element'); // when self.raty({ score: -1 }); // then expect(self.children('input').val()).toEqual(''); }); }); context('with :readOnly', function() { it ('becomes readOnly too', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self.children('input')).toHaveAttr('readonly', 'readonly'); }); }); }); describe('#scoreName', function() { it ('changes the score field name', function() { // given var self = $('#element'); // when self.raty({ scoreName: 'entity.score' }); // then expect(self.children('input')).toHaveAttr('name', 'entity.score'); }); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ scoreName: function() { return 'custom'; } }); // then expect(self.data('settings').scoreName).toEqual('custom'); }); describe('#readOnly', function() { it ('Applies "Not rated yet!" on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self.children('img')).toHaveAttr('title', 'Not rated yet!'); }); it ('removes the pointer cursor', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self).not.toHaveCss({ cursor: 'pointer' }); expect(self).not.toHaveCss({ cursor: 'default' }); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ readOnly: function() { return true; } }); // then expect(self.data('settings').readOnly).toEqual(true); }); it ('avoids trigger mouseover', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when imgs.eq(1).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('avoids trigger click', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when imgs.eq(1).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); it ('avoids trigger mouseleave', function() { // given var self = $('#element').raty({ readOnly: true, mouseout: function() { $(this).data('mouseleave', true); } }), imgs = self.children('img'); imgs.eq(1).mouseover(); // when self.mouseleave(); // then expect(self.data('mouseleave')).toBeFalsy(); }); context('with :score', function() { context('as integer', function() { it ('applies the score title on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, score: 3 }); // then expect(self.children('img')).toHaveAttr('title', 'regular'); }); }); context('as float', function() { it ('applies the integer score title on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, score: 3.1 }); // then expect(self.children('img')).toHaveAttr('title', 'regular'); }); }); }); context('with :cancel', function() { it ('hides the button', function() { // given var self = $('#element'); // when self.raty({ cancel: true, readOnly: true, path: '../lib/img' }); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); }); describe('#hints', function() { it ('changes the hints', function() { // given var self = $('#element'); // when self.raty({ hints: ['1', '/', 'c', '-', '#'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', '/'); expect(imgs.eq(2)).toHaveAttr('title', 'c'); expect(imgs.eq(3)).toHaveAttr('title', '-'); expect(imgs.eq(4)).toHaveAttr('title', '#'); }); it ('receives the number of the star when is undefined', function() { // given var self = $('#element'); // when self.raty({ hints: [undefined, 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); it ('receives empty when is empty string', function() { // given var self = $('#element'); // when self.raty({ hints: ['', 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', ''); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); it ('receives the number of the star when is null', function() { // given var self = $('#element'); // when self.raty({ hints: [null, 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); context('whe has less hint than stars', function() { it ('receives the default hint index', function() { // given var self = $('#element'); // when self.raty({ hints: ['1', '2', '3', '4'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', 2); expect(imgs.eq(2)).toHaveAttr('title', 3); expect(imgs.eq(3)).toHaveAttr('title', 4); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); }); context('whe has more stars than hints', function() { it ('sets star number', function() { // given var self = $('#element'); // when self.raty({ number: 6, hints: ['a', 'b', 'c', 'd', 'e'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 'a'); expect(imgs.eq(1)).toHaveAttr('title', 'b'); expect(imgs.eq(2)).toHaveAttr('title', 'c'); expect(imgs.eq(3)).toHaveAttr('title', 'd'); expect(imgs.eq(4)).toHaveAttr('title', 'e'); expect(imgs.eq(5)).toHaveAttr('title', 6); }); }); }); describe('#mouseover', function() { it ('receives the score as int', function() { // given var self = $('#element').raty({ mouseover: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover(); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ mouseover: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('img:first').mouseover(); // then expect(self.data('evt').type).toEqual('mouseover'); }); context('with :cancel', function() { it ('receives null as score', function() { // given var self = $('#element').raty({ cancel : true, mouseover : function(score) { self.data('null', score); } }); // when self.children('.raty-cancel').mouseover(); // then expect(self.data('null')).toBeNull(); }); }); }); describe('#mouseout', function() { it ('receives the score as int', function() { // given var self = $('#element').raty({ mouseout: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover().click().mouseout(); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ mouseout: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('img:first').mouseover().click().mouseout(); // then expect(self.data('evt').type).toEqual('mouseout'); }); context('without score setted', function() { it ('pass undefined on callback', function() { // given var self = $('#element').raty({ cancel : true, mouseout: function(score) { self.data('undefined', score === undefined); } }); // when self.children('img:first').mouseenter().mouseleave(); // then expect(self.data('undefined')).toBeTruthy(); }); }); context('with :score rated', function() { it ('pass the score on callback', function() { // given var self = $('#element').raty({ score : 1, mouseout: function(score) { self.data('score', score); } }); // when self.children('img:first').mouseenter().mouseleave(); // then expect(self.data('score')).toEqual(1); }); }); context('with :cancel', function() { it ('receives the event', function() { // given var self = $('#element').raty({ cancel : true, mouseout: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('.raty-cancel').mouseover().click().mouseout(); // then expect(self.data('evt').type).toEqual('mouseout'); }); context('without score setted', function() { it ('pass undefined on callback', function() { // given var self = $('#element').raty({ mouseout: function(score) { self.data('undefined', score === undefined); }, cancel : true }); // when self.children('.raty-cancel').mouseenter().mouseleave(); // then expect(self.data('undefined')).toBeTruthy(); }); }); context('with :score rated', function() { it ('pass the score on callback', function() { // given var self = $('#element').raty({ mouseout: function(score) { self.data('score', score); }, cancel : true, score : 1 }); // when self.children('.raty-cancel').mouseenter().mouseleave(); // then expect(self.data('score')).toEqual(1); }); }); }); }); describe('#number', function() { it ('changes the number of stars', function() { // given var self = $('#element'); // when self.raty({ number: 1 }); // then expect(self.children('img').length).toEqual(1); }); it ('accepts number as string', function() { // given var self = $('#element'); // when self.raty({ number: '10' }); // then expect(self.children('img').length).toEqual(10); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ number: function() { return 1; } }); // then expect(self.children('img').length).toEqual(1); }); }); describe('#path', function() { context('without last slash', function() { it ('receives the slash', function() { // given var self = $('#element'); // when self.raty({ path: 'path' }); // then expect(self[0].opt.path).toEqual('path/'); }); }); context('with last slash', function() { it ('keeps it', function() { // given var self = $('#element'); // when self.raty({ path: 'path/' }); // then expect(self[0].opt.path).toEqual('path/'); }); }); it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ path: 'path' }); // then expect(self.children('img')).toHaveAttr('src', 'path/star-off.png'); }); context('without path', function() { it ('sets receives empty', function() { // given var self = $('#element'); // when self.raty({ path: null }); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); context('with :cancel', function() { it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ cancel: true, path: 'path' }) // then expect(self.children('.raty-cancel')).toHaveAttr('src', 'path/cancel-off.png'); }); }); context('with :iconRange', function() { it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ path : 'path', iconRange: [{ range: 5 }] }); // then expect(self.children('img')).toHaveAttr('src', 'path/star-off.png'); }); }); }); describe('#cancelOff', function() { it ('changes the icon', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelOff: 'off.png' }); // then expect(self.children('.raty-cancel')).toHaveAttr('src', 'off.png'); }); }); describe('#cancelOn', function() { it ('changes the icon', function() { // given var self = $('#element').raty({ cancel: true, cancelOn: 'icon.png' }); // when var cancel = self.children('.raty-cancel').mouseover(); // then expect(cancel).toHaveAttr('src', 'icon.png'); }); }); describe('#cancelHint', function() { it ('changes the cancel hint', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelHint: 'hint' }); // then expect(self.children('.raty-cancel')).toHaveAttr('title', 'hint'); }); }); describe('#cancelPlace', function() { it ('changes the place off cancel button', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelPlace: 'right' }); // then var cancel = self.children('img:last'); expect(cancel).toHaveClass('raty-cancel'); expect(cancel).toHaveAttr('title', 'Cancel this rating!'); expect(cancel).toHaveAttr('alt', 'x'); expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); }); describe('#cancel', function() { it ('creates the element', function() { // given var self = $('#element'); // when self.raty({ cancel: true }); // then var cancel = self.children('.raty-cancel'); expect(cancel).toHaveClass('raty-cancel'); expect(cancel).toHaveAttr('title', 'Cancel this rating!'); expect(cancel).toHaveAttr('alt', 'x'); expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); context('on mouseover', function() { it ('turns on', function() { // given var self = $('#element').raty({ cancel: true }); // when var cancel = self.children('.raty-cancel').mouseover(); // then expect(cancel).toHaveAttr('src', 'cancel-on.png'); }); context('with :score', function() { it ('turns off the stars', function() { // given var self = $('#element').raty({ score: 3, cancel: true }), imgs = self.children('img:not(.raty-cancel)'); // when self.children('.raty-cancel').mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); context('when :mouseout', function() { it ('turns on', function() { // given var self = $('#element').raty({ cancel: true }); // when var cancel = self.children('.raty-cancel').mouseover().mouseout(); // then expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); context('with :score', function() { it ('turns the star on again', function() { // given var self = $('#element').raty({ score: 4, cancel: true }), imgs = self.children('img:not(.raty-cancel)'); // when self.children('.raty-cancel').mouseover().mouseout(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); }); }); context('on click', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ cancel: true, score: 1 }); // when self.children('.raty-cancel').click().mouseout(); // then var stars = self.children('img:not(.raty-cancel)'); expect(stars).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); }); context('when starts :readOnly', function() { it ('starts hidden', function() { // given var self = $('#element').raty({ cancel: true, readOnly: true, path: '../img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); context('on click', function() { it ('does not cancel the rating', function() { // given var self = $('#element').raty({ cancel: true, readOnly: true, score: 5 }); // when self.children('.raty-cancel').click().mouseout(); // then var stars = self.children('img:not(.raty-cancel)'); expect(stars).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('5'); }); }); }); context('when become :readOnly', function() { it ('becomes hidden', function() { // given var self = $('#element').raty({ cancel: true, path: '../img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); }); describe('#targetType', function() { beforeEach(function() { buildDivTarget(); }); context('with missing target', function() { it ('throws error', function() { // given var self = $('#element'); // when var lambda = function() { self.raty({ target: 'missing' }); }; // then expect(lambda).toThrow(new Error('Target selector invalid or missing!')); }); }); context('as hint', function() { it ('receives the hint', function() { // given var self = $('#element').raty({ target: '#hint', targetType: 'hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('bad'); }); context('with :cancel', function() { it ('receives the :cancelHint', function() { // given var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'hint' }); // when self.children('.raty-cancel').mouseover(); // then expect($('#hint')).toHaveHtml('Cancel this rating!'); }); }); }); context('as score', function() { it ('receives the score', function() { // given var self = $('#element').raty({ target: '#hint', targetType: 'score' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml(1); }); context('with :cancel', function() { it ('receives the :cancelHint', function() { // given var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'score' }); // when self.children('.raty-cancel').mouseover(); // then expect($('#hint')).toHaveHtml('Cancel this rating!'); }); }); }); }); describe('#targetText', function() { beforeEach(function() { buildDivTarget(); }); it ('set target with none value', function() { // given var self = $('#element'); // when self.raty({ target: '#hint', targetText: 'none' }); // then expect($('#hint')).toHaveHtml('none'); }); }); describe('#targetFormat', function() { context('with :target', function() { beforeEach(function() { buildDivTarget(); }); it ('stars empty', function() { // given var self = $('#element'); // when self.raty({ target: '#hint', targetFormat: 'score: {score}' }); // then expect($('#hint')).toBeEmpty(); }); context('with missing score key', function() { it ('throws error', function() { // given var self = $('#element'); // when var lambda = function() { self.raty({ target: '#hint', targetFormat: '' }); }; // then expect(lambda).toThrow(new Error('Template "{score}" missing!')); }); }); context('on mouseover', function() { it ('set target with format on mouseover', function() { // given var self = $('#element').raty({ target: '#hint', targetFormat: 'score: {score}' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('score: bad'); }); }); context('on mouseout', function() { it ('clears the target', function() { // given var self = $('#element').raty({ target : '#hint', targetFormat: 'score: {score}' }); // when self.children('img:first').mouseover().mouseout(); // then expect($('#hint')).toBeEmpty(); }); context('with :targetKeep', function() { context('without score', function() { it ('clears the target', function() { // given var self = $('#element').raty({ target : '#hint', targetFormat: 'score: {score}', targetKeep : true }); // when self.children('img:first').mouseover().mouseleave(); // then expect($('#hint')).toBeEmpty(); }); }); context('with score', function() { it ('keeps the template', function() { // given var self = $('#element').raty({ score : 1, target : '#hint', targetFormat: 'score: {score}', targetKeep : true }); // when self.children('img:first').mouseover().mouseleave(); // then expect($('#hint')).toHaveHtml('score: bad'); }); }); }); }); }); }); describe('#precision', function() { beforeEach(function() { buildDivTarget(); }); it ('enables the :half options', function() { // given var self = $('#element'); // when self.raty({ precision: true }); // then expect(self.data('settings').half).toBeTruthy(); }); it ('changes the :targetType to score', function() { // given var self = $('#element'); // when self.raty({ precision: true }); // then expect(self.data('settings').targetType).toEqual('score'); }); context('with :target', function() { context('with :targetKeep', function() { context('with :score', function() { it ('sets the float with one fractional number', function() { // given var self = $('#element'); // when self.raty({ precision : true, score : 1.23, target : '#hint', targetKeep: true, targetType: 'score' }); // then expect($('#hint')).toHaveHtml('1.2'); }); }); }); }); }); describe('#target', function() { context('on mouseover', function() { context('as div', function() { beforeEach(function() { buildDivTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('bad'); }); }); context('as text field', function() { beforeEach(function() { buildTextTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); context('as textarea', function() { beforeEach(function() { buildTextareaTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); context('as combobox', function() { beforeEach(function() { buildComboboxTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); }); context('on mouseout', function() { context('as div', function() { beforeEach(function() { buildDivTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover().click().mouseleave(); // then expect($('#hint')).toBeEmpty(); }); }); context('as textarea', function() { beforeEach(function() { buildTextareaTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); context('as text field', function() { beforeEach(function() { buildTextTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); context('as combobox', function() { beforeEach(function() { buildComboboxTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); }); }); describe('#size', function() { it ('calculate the right icon size', function() { // given var self = $('#element'), size = 24, stars = 5, space = 4; // when self.raty({ size: size }); // then expect(self.width()).toEqual((stars * size) + (stars * space)); }); context('with :cancel', function() { it ('addes the cancel and space witdh', function() { // given var self = $('#element'), size = 24, stars = 5, cancel = size, space = 4; // when self.raty({ cancel: true, size: size }); // then expect(self.width()).toEqual(cancel + space + (stars * size) + (stars * space)); }); }); }); describe('#space', function() { context('when off', function() { it ('takes off the space', function() { // given var self = $('#element'); size = 16, stars = 5; // when self.raty({ space: false }); // then expect(self.width()).toEqual(size * stars); }); context('with :cancel', function() { it ('takes off the space', function() { // given var self = $('#element'); size = 16, stars = 5, cancel = size; // when self.raty({ cancel: true, space: false }); // then expect(self.width()).toEqual(cancel + (size * stars)); }); }); }); }); describe('#single', function() { context('on mouseover', function() { it ('turns on just one icon', function() { // given var self = $('#element').raty({ single: true }), imgs = self.children('img'); // when imgs.eq(2).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); context('with :iconRange', function() { it ('shows just on icon', function() { // given var self = $('#element').raty({ single : true, iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(3).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); }); }); context('on click', function() { context('on mouseout', function() { it ('keeps the score', function() { // given var self = $('#element').raty({ single: true }) imgs = self.children('img'); // when imgs.eq(2).mouseover().click().mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); context('and :iconRange', function() { it ('keeps the score', function() { // given var self = $('#element').raty({ single : true, iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(3).mouseover().click().mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); }); }); }); }); describe('#width', function() { it ('set custom width', function() { // given var self = $('#element'); // when self.raty({ width: 200 }); // then expect(self.width()).toEqual(200); }); describe('when it is false', function() { it ('does not apply the style', function() { // given var self = $('#element'); // when self.raty({ width: false }); // then expect(self).not.toHaveCss({ width: '100px' }); }); }); describe('when :readOnly', function() { it ('set custom width when readOnly', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, width: 200 }); // then expect(self.width()).toEqual(200); }); }); }); describe('#half', function() { context('as false', function() { context('#halfShow', function() { context('as false', function() { it ('rounds down while less the full limit', function() { // given var self = $('#element'); // when self.raty({ half : false, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .5 // score.5 < full.6 === 0 }); var imgs = self.children('img'); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); }); it ('rounds full when equal the full limit', function() { // given var self = $('#element'); // when self.raty({ half : false, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .6 // score.6 == full.6 === 1 }); var imgs = self.children('img'); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); }); }); context('as true', function() { context('#halfShow', function() { context('as false', function() { it ('ignores round down while less down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .24 // score.24 < down.25 === 0 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual('0.24'); }); it ('ignores half while greater then down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .26 // score.26 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual('0.26'); }); it ('ignores half while equal full limit, ignoring it', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .6 // score.6 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('0.6'); }); it ('ignores half while greater than down limit and less than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .75 // score.75 > down.25 and score.75 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('0.75'); }); it ('ignores full while equal or greater than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .76 // score.76 == up.76 === 1 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); context('as true', function() { it ('rounds down while less down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .24 // score.24 < down.25 === 0 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); }); it ('receives half while greater then down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .26 // score.26 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives half while equal full limit, ignoring it', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .6 // score.6 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives half while greater than down limit and less than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .75 // score.75 > down.25 and score.75 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives full while equal or greater than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .76 // score.76 == up.76 === 1 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :precision', function() { context('and :targetType as score', function() { context('and :targetKeep', function() { context('and :targetType as score', function() { it ('set .5 increment value target with half option and no precision', function() { // given var self = $('#element'); // when self.raty({ half : true, precision : false, score : 1.5, target : '#hint', targetKeep: true, targetType: 'score' }); // then expect($('#hint')).toHaveHtml('1.5'); }); }); }); }); }); }); }); }); }); describe('class bind', function() { beforeEach(function() { $('body').append('<div class="element"></div><div class="element"></div>'); }); afterEach(function() { $('.element').remove(); }); it ('is chainable', function() { // given var self = $('.element'); // when var refs = self.raty(); // then expect(refs.eq(0)).toBe(self.eq(0)); expect(refs.eq(1)).toBe(self.eq(1)); }); it ('creates the default markup', function() { // given var self = $('.element'); // when self.raty(); // then var imgs = self.eq(0).children('img'), score = self.eq(0).children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); imgs = self.eq(1).children('img'); score = self.eq(0).children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); }); }); describe('functions', function() { describe('GET #score', function() { it ('accepts number as string', function() { // given var self = $('#element'); // when self.raty({ score: '1' }); // then expect(self.children('input')).toHaveValue(1); }); it ('accepts float string', function() { // given var self = $('#element'); // when self.raty({ score: '1.5' }); // then expect(self.children('input')).toHaveValue(1.5); }); context('with integer score', function() { it ('gets as int', function() { // given var self = $('#element').raty({ score: 1 }); // when var score = self.raty('score'); // then expect(score).toEqual(1); }); }); context('with float score', function() { it ('gets as float', function() { // given var self = $('#element').raty({ score: 1.5 }); // when var score = self.raty('score'); // then expect(score).toEqual(1.5); }); }); context('with score zero', function() { it ('gets null to emulate cancel', function() { // given var self = $('#element').raty({ score: 0 }); // when var score = self.raty('score'); // then expect(score).toEqual(null); }); }); context('with score greater than :numberMax', function() { it ('gets the max', function() { // given var self = $('#element').raty({ number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(score).toEqual(self.data('settings').numberMax); }); }); }); describe('SET #score', function() { it ('sets the score', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then expect(self.raty('score')).toEqual(1); }); describe('with :click', function() { it ('calls the click callback', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.raty('score', 5); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); }); }); describe('without :click', function() { it ('does not throw exception', function() { // given var self = $('#element').raty(); // when var lambda = function() { self.raty('score', 1); }; // then expect(lambda).not.toThrow(new Error('You must add the "click: function(score, evt) { }" callback.')); }); }); describe('with :readOnly', function() { it ('does not set the score', function() { // given var self = $('#element').raty({ readOnly: true }); // when self.raty('score', 5); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); }); describe('#set', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('set', { number: 1 }); // then expect(ref).toBe(self); }); it ('changes the declared options', function() { // given var self = $('#element').raty(); // when var ref = self.raty('set', { scoreName: 'change-just-it' }); // then expect(ref.children('input')).toHaveAttr('name', 'change-just-it'); }); it ('does not change other none declared options', function() { // given var self = $('#element').raty({ number: 6 }); // when var ref = self.raty('set', { scoreName: 'change-just-it' }); // then expect(ref.children('img').length).toEqual(6); }); context('with external bind on wrapper', function() { it ('keeps it', function() { // given var self = $('#element').on('click', function() { $(this).data('externalClick', true); }).raty(); // when self.raty('set', {}).click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); context('when :readOnly by function', function() { it ('is removes the readonly data info', function() { // given var self = $('#element').raty().raty('readOnly', true); // when var ref = self.raty('set', { readOnly: false }); // then expect(self).not.toHaveData('readonly'); }); }); }); describe('#readOnly', function() { context('changes to true', function() { it ('sets score as readonly', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self.children('input')).toHaveAttr('readonly', 'readonly'); }); it ('removes the pointer cursor', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self).not.toHaveCss({ cursor: 'pointer' }); expect(self).not.toHaveCss({ cursor: 'default' }); }); it ('Applies "Not rated yet!" on stars', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self.children('img')).toHaveAttr('title', 'Not rated yet!'); }); it ('avoids trigger mouseover', function() { // given var self = $('#element').raty(), imgs = self.children('img'); self.raty('readOnly', true); // when imgs.eq(0).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('avoids trigger click', function() { // given var self = $('#element').raty(), imgs = self.children('img'); self.raty('readOnly', true); // when imgs.eq(0).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); context('with :score', function() { it ('applies the score title on stars', function() { // given var self = $('#element').raty({ score: 1 }); // when self.raty('readOnly', true); // then expect(self.children('img')).toHaveAttr('title', 'bad'); }); }); context('with :cancel', function() { it ('hides the button', function() { // given var self = $('#element').raty({ cancel: true, path: '../lib/img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); context('with external bind on wrapper', function() { it ('keeps it', function() { // given var self = $('#element').on('click', function() { $(this).data('externalClick', true); }).raty(); // when self.raty('readOnly', true).click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); context('with external bind on stars', function() { it ('keeps it', function() { // given var self = $('#element').raty(), star = self.children('img').first(); star.on('click', function() { self.data('externalClick', true); }); // when self.raty('readOnly', true); star.click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); }); context('changes to false', function() { it ('removes the :readOnly of the score', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', false); // then expect(self.children('input')).not.toHaveAttr('readonly', 'readonly'); }); it ('applies the pointer cursor on wrapper', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', false); // then expect(self).toHaveCss({ cursor: 'pointer' }); }); it ('Removes the "Not rated yet!" off the stars', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when self.raty('readOnly', false); // then expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); it ('triggers mouseover', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); self.raty('readOnly', false); // when imgs.eq(0).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); it ('triggers click', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); self.raty('readOnly', false); // when imgs.eq(0).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); expect(self.children('input')).toHaveValue('1'); }); context('with :score', function() { it ('removes the score title off the stars', function() { // given var self = $('#element').raty({ readOnly: true, score: 3 }); // when self.raty('readOnly', false); // then var imgs = self.children('img') expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); }); context('with :cancel', function() { it ('shows the button', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true, path: '../lib/img' }); // when self.raty('readOnly', false); // then expect(self.children('.raty-cancel')).toBeVisible(); expect(self.children('.raty-cancel')).not.toHaveCss({ display: 'block' }); }); it ('rebinds the mouseover', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true }), cancel = self.children('.raty-cancel'), imgs = self.children('img:not(.raty-cancel)'); // when self.raty('readOnly', false); cancel.mouseover(); // then expect(cancel).toHaveAttr('src', 'cancel-on.png'); expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('rebinds the click', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true, score: 5 }), imgs = self.children('img:not(.raty-cancel)'); // when self.raty('readOnly', false); self.children('.raty-cancel').click().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); }); describe('#cancel', function() { describe('with :readOnly', function() { it ('does not cancel', function() { // given var self = $('#element').raty({ readOnly: true, score: 5 }); // when self.raty('cancel'); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); }); }); context('without click trigger', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ score: 1, click: function() { $(this).data('clicked', true); } }); // when self.raty('cancel'); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); expect(self.data('clicked')).toBeFalsy(); });<|fim▁hole|> context('with click trigger', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ score: 1, click: function() { $(this).data('clicked', true); } }); // when self.raty('cancel', true); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); expect(self.data('clicked')).toBeTruthy(); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :targetKeep', function() { it ('sets the :targetText on target', function() { // given var hint = $('#hint').html('dirty'), self = $('#element').raty({ cancel : true, target : '#hint', targetKeep: true, targetText: 'targetText' }); // when self.raty('cancel'); // then expect(hint).toHaveHtml('targetText'); }); }); }); }); describe('#click', function() { it ('clicks on star', function() { // given var self = $('#element').raty({ click: function() { $(this).data('clicked', true); } }); // when self.raty('click', 1); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); expect(self.data('clicked')).toBeTruthy(); }); it ('receives the score', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.raty('click', 1); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ click: function(score, evt) { $(this).data('evt', evt); } }); // when self.raty('click', 1); // then expect(self.data('evt').type).toEqual('click'); }); describe('with :readOnly', function() { it ('does not set the score', function() { // given var self = $('#element').raty({ readOnly: true }); // when self.raty('click', 1); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); context('without :click', function() { it ('throws error', function() { // given var self = $('#element').raty(); // when var lambda = function() { self.raty('click', 1); }; // then expect(lambda).toThrow(new Error('You must add the "click: function(score, evt) { }" callback.')); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :targetKeep', function() { it ('sets the score on target', function() { // given var self = $('#element').raty({ target : '#hint', targetKeep: true, click : function() { } }); // when self.raty('click', 1); // then expect($('#hint')).toHaveHtml('bad'); }); }); }); }); describe('#reload', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('reload'); // then expect(ref).toBe(self); }); it ('reloads with the same configuration', function() { // given var self = $('#element').raty({ number: 6 }); // when var ref = self.raty('reload'); // then expect(ref.children('img').length).toEqual(6); }); context('when :readOnly by function', function() { it ('is removes the readonly data info', function() { // given var self = $('#element').raty().raty('readOnly', true); // when var ref = self.raty('reload'); // then expect(self).not.toHaveData('readonly'); }); }); }); describe('#destroy', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('destroy'); // then expect(ref).toBe(self); }); it ('clear the content', function() { // given var self = $('#element').raty(); // when self.raty('destroy'); // then expect(self).toBeEmpty(); }); it ('removes the trigger mouseleave', function() { // given var self = $('#element').raty({ mouseout: function() { console.log(this); $(this).data('mouseleave', true); } }); self.raty('destroy'); // when self.mouseleave(); // then expect(self.data('mouseleave')).toBeFalsy(); }); it ('resets the style attributes', function() { // given var self = $('#element').css({ cursor: 'help', width: 10 }).raty(); // when self.raty('destroy'); // then expect(self[0].style.cursor).toEqual('help'); expect(self[0].style.width).toEqual('10px'); }); }); }); });<|fim▁end|>
});
<|file_name|>KidneyServerSolver.java<|end_file_name|><|fim▁begin|>package web; import graphUtil.CycleChainDecomposition; import graphUtil.EdgeChain; import ilog.concert.IloException; import java.util.HashMap; import java.util.List; import java.util.Map; import kepLib.KepInstance; import kepLib.KepProblemData; import kepModeler.ChainsForcedRemainOpenOptions; import kepModeler.KepModeler; import kepModeler.ModelerInputs; import kepModeler.ObjectiveMode; import replicator.DonorEdge; import threading.FixedThreadPool; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import data.Donor; import data.ExchangeUnit; import database.KidneyDataBase; import exchangeGraph.CycleChainPackingSubtourElimination; import exchangeGraph.SolverOption; public class KidneyServerSolver { private KidneyDataBase database; private Map<String, ModelerInputs<ExchangeUnit, DonorEdge>> dataCache = new HashMap<String, ModelerInputs<ExchangeUnit, DonorEdge>>(); private Optional<FixedThreadPool> threadPool; Optional<Double> maxSolveTimeMs = Optional.of(100.0); public KidneyServerSolver(KidneyDataBase database, Optional<FixedThreadPool> threadPool) { this.database = database; this.threadPool = threadPool; } public ImmutableList<String> availableDatasets() { return database.availableDatasets(); } public Map<Object, Object> getInputs(String databaseName) { return flattenModelerInputs(getModelerInputs(databaseName)); } public Map<Object, Object> getSolution(String databaseName) throws IloException { ModelerInputs<ExchangeUnit, DonorEdge> inputs = getModelerInputs(databaseName); KepModeler modeler = new KepModeler(3, Integer.MAX_VALUE, ChainsForcedRemainOpenOptions.none, new ObjectiveMode.MaximumCardinalityMode()); KepInstance<ExchangeUnit, DonorEdge> instance = modeler.makeKepInstance( inputs, null); CycleChainPackingSubtourElimination<ExchangeUnit, DonorEdge> solver = new CycleChainPackingSubtourElimination<ExchangeUnit, DonorEdge>( instance, true, maxSolveTimeMs, threadPool, SolverOption.makeCheckedOptions(SolverOption.cutsetMode, SolverOption.lazyConstraintCallback, SolverOption.userCutCallback)); solver.solve(); CycleChainDecomposition<ExchangeUnit, DonorEdge> solution = solver .getSolution(); solver.cleanUp(); return flattenSolution(inputs.getKepProblemData(), solution); } private ModelerInputs<ExchangeUnit, DonorEdge> getModelerInputs( String databaseName) { if (this.dataCache.containsKey(databaseName)) { return this.dataCache.get(databaseName); } else { ModelerInputs<ExchangeUnit, DonorEdge> inputs = database .loadInputs(databaseName); this.dataCache.put(databaseName, inputs); return inputs; } } public static Map<Object, Object> flattenModelerInputs( ModelerInputs<ExchangeUnit, DonorEdge> inputs) { Map<Object, Object> ans = new HashMap<Object, Object>(); List<Map<Object, Object>> flatUnits = Lists.newArrayList(); List<Map<Object, Object>> flatEdges = Lists.newArrayList(); for (ExchangeUnit unit : inputs.getKepProblemData().getGraph() .getVertices()) { flatUnits.add(flattenExchangeUnit(inputs, unit)); } for (DonorEdge edge : inputs.getKepProblemData().getGraph().getEdges()) { flatEdges.add(flattenDonorEdge(inputs.getKepProblemData(), edge)); } ans.put("nodes", flatUnits); ans.put("links", flatEdges); return ans; } public static Map<Object, Object> flattenSolution( KepProblemData<ExchangeUnit, DonorEdge> problemData, CycleChainDecomposition<ExchangeUnit, DonorEdge> solution) { Map<Object, Object> ans = new HashMap<Object, Object>(); List<Map<Object, Object>> flatEdges = Lists.newArrayList(); for (EdgeChain<DonorEdge> edgeChain : solution.getEdgeChains()) { for (DonorEdge edge : edgeChain) { flatEdges.add(flattenDonorEdge(problemData, edge)); } } ans.put("links", flatEdges); return ans; } private static Map<Object, Object> flattenDonorEdge( KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, DonorEdge edge) { Map<Object, Object> ans = new HashMap<Object, Object>(); ExchangeUnit source = kepProblemData.getGraph().getSource(edge); ExchangeUnit dest = kepProblemData.getGraph().getDest(edge); String sourceId = makeNodeId(kepProblemData, source); String destId = makeNodeId(kepProblemData, dest); ans.put("sourceId", sourceId); ans.put("targetId", destId); ans.put("id", sourceId + destId); return ans; } private static Map<Object, Object> flattenExchangeUnit( ModelerInputs<ExchangeUnit, DonorEdge> inputs, ExchangeUnit unit) { Map<Object, Object> ans = new HashMap<Object, Object>(); ans.put("id", makeNodeId(inputs.getKepProblemData(), unit)); ans.put("type", makeType(inputs.getKepProblemData(), unit)); ans.put("reachable", true); ans.put("sensitized", computeSensitization(inputs, unit)); return ans; } private static String makeNodeId( KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, ExchangeUnit unit) { if (kepProblemData.getRootNodes().contains(unit)) { return unit.getDonor().get(0).getId(); } else { return unit.getReceiver().getId(); } } private static String makeType( KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, ExchangeUnit unit) { if (kepProblemData.getRootNodes().contains(unit)) { return "root"; } else if (kepProblemData.getPairedNodes().contains(unit)) { return "paired"; } else if (kepProblemData.getTerminalNodes().contains(unit)) { return "terminal"; } else { throw new RuntimeException(); } } private static int computeSensitization( ModelerInputs<ExchangeUnit, DonorEdge> inputs, ExchangeUnit unit) { Map<ExchangeUnit, Double> donorPower = inputs.getAuxiliaryInputStatistics() .getDonorPowerPostPreference(); Map<ExchangeUnit, Double> receiverPower = inputs .getAuxiliaryInputStatistics().getReceiverPowerPostPreference(); // System.out.println(donorPower); // System.out.println(receiverPower); if (inputs.getKepProblemData().getRootNodes().contains(unit)) { if (donorPower.containsKey(unit.getDonor().get(0))) { return singlePersonSensitization(donorPower.get(unit.getDonor().get(0))); } else { // System.err.println("missing donor power data for: " + unit); return 0; } } else if (inputs.getKepProblemData().getPairedNodes().contains(unit)) { double unitDonorPower = 0; for (Donor donor : unit.getDonor()) { if (donorPower.containsKey(donor)) { unitDonorPower += donorPower.get(donor); } else { // System.err.println("missing donor power data for: " + unit); return 0; } } if (receiverPower.containsKey(unit.getReceiver())) { return twoPersonSensitization(unitDonorPower, receiverPower.get(unit.getReceiver())); } else { // System.err.println("missing receiver power for: " + unit); return 0; } } else if (inputs.getKepProblemData().getTerminalNodes().contains(unit)) { if (receiverPower.containsKey(unit.getReceiver())) { return singlePersonSensitization(receiverPower.get(unit.getReceiver())); } else { // System.err.println("missing receiver power for: " + unit); return 0; } } else { throw new RuntimeException(); } } private static int singlePersonSensitization(double matchPower) { if (matchPower < .01) { return 3; } else if (matchPower < .08) { return 2; } else if (matchPower < .2) { return 1; } else { return 0; } } private static int twoPersonSensitization(double donorMatchPower, double receiverMatchPower) { double pmp = 10000 * donorMatchPower * receiverMatchPower; if (pmp < .1) { return 4; } else if (pmp < 5) { return 3;<|fim▁hole|> } else if (pmp < 60) { return 1; } else { return 0; } } }<|fim▁end|>
} else if (pmp < 20) { return 2;
<|file_name|>Euler12.java<|end_file_name|><|fim▁begin|>package com.martijndashorst.euler; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; /** * The sequence of triangle numbers is generated by adding the natural numbers. * So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first * ten terms would be: * * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... * * Let us list the factors of the first seven triangle numbers: * * <pre> 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10<|fim▁hole|> 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 * </pre> * * We can see that 28 is the first triangle number to have over five divisors. * * What is the value of the first triangle number to have over five hundred * divisors? */ public class Euler12 { @Test public void example() { assertThat(firstTriangleNumberWithOverNDivisors(5), is(28L)); } @Test public void solution() { assertThat(firstTriangleNumberWithOverNDivisors(500), is(76_576_500L)); } private long firstTriangleNumberWithOverNDivisors(int n) { int divisors = 0; int counter = 1; long triangle = 0; do { triangle = (counter * (counter + 1)) / 2; divisors = numberOfDivisors(triangle); counter++; } while (divisors < n); return triangle; } @Test public void nrOfDivisors1() { assertThat(numberOfDivisors(1), is(1)); assertThat(numberOfDivisors(2), is(2)); assertThat(numberOfDivisors(3), is(2)); assertThat(numberOfDivisors(4), is(3)); assertThat(numberOfDivisors(10), is(4)); assertThat(numberOfDivisors(28), is(6)); } private int numberOfDivisors(long n) { if (n == 1) return 1; if (n <= 3) return 2; long nr = (long) Math.sqrt(n); int nrOfDivisors = 2; for (int i = 2; i <= nr; i++) { if (n % i == 0) { nrOfDivisors += i == nr ? 1 : 2; } } return nrOfDivisors; } }<|fim▁end|>
<|file_name|>_abcoll.py<|end_file_name|><|fim▁begin|># Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) for collections, according to PEP 3119. DON'T USE THIS MODULE DIRECTLY! The classes here should be imported via collections; they are defined here only to alleviate certain bootstrapping issues. Unit tests are in test_collections. """ from abc import ABCMeta, abstractmethod import sys __all__ = ["Hashable", "Iterable", "Iterator", "Sized", "Container", "Callable", "Set", "MutableSet", "Mapping", "MutableMapping", "MappingView", "KeysView", "ItemsView", "ValuesView", "Sequence", "MutableSequence", ] ### ONE-TRICK PONIES ### class Hashable: __metaclass__ = ABCMeta @abstractmethod def __hash__(self): return 0 @classmethod def __subclasshook__(cls, C): if cls is Hashable: for B in C.__mro__: if "__hash__" in B.__dict__: if B.__dict__["__hash__"]: return True break return NotImplemented class Iterable: __metaclass__ = ABCMeta @abstractmethod def __iter__(self): while False: yield None @classmethod def __subclasshook__(cls, C): if cls is Iterable: if any("__iter__" in B.__dict__ for B in C.__mro__): return True return NotImplemented Iterable.register(str) class Iterator(Iterable): @abstractmethod def __next__(self): raise StopIteration def __iter__(self): return self @classmethod def __subclasshook__(cls, C): if cls is Iterator: if any("next" in B.__dict__ for B in C.__mro__): return True return NotImplemented class Sized: __metaclass__ = ABCMeta @abstractmethod def __len__(self): return 0 @classmethod def __subclasshook__(cls, C): if cls is Sized: if any("__len__" in B.__dict__ for B in C.__mro__): return True return NotImplemented class Container: __metaclass__ = ABCMeta @abstractmethod def __contains__(self, x): return False @classmethod def __subclasshook__(cls, C): if cls is Container: if any("__contains__" in B.__dict__ for B in C.__mro__): return True return NotImplemented class Callable: __metaclass__ = ABCMeta @abstractmethod def __call__(self, *args, **kwds): return False @classmethod def __subclasshook__(cls, C): if cls is Callable: if any("__call__" in B.__dict__ for B in C.__mro__): return True return NotImplemented ### SETS ### class Set(Sized, Iterable, Container): """A set is a finite, iterable container. This class provides concrete generic implementations of all methods except for __contains__, __iter__ and __len__. To override the comparisons (presumably for speed, as the semantics are fixed), all you have to do is redefine __le__ and then the other operations will automatically follow suit. """ def __le__(self, other): if not isinstance(other, Set): return NotImplemented if len(self) > len(other): return False for elem in self: if elem not in other: return False return True def __lt__(self, other): if not isinstance(other, Set): return NotImplemented return len(self) < len(other) and self.__le__(other) def __gt__(self, other): if not isinstance(other, Set): return NotImplemented return other < self def __ge__(self, other): if not isinstance(other, Set): return NotImplemented return other <= self def __eq__(self, other): if not isinstance(other, Set): return NotImplemented return len(self) == len(other) and self.__le__(other) def __ne__(self, other): return not (self == other) @classmethod def _from_iterable(cls, it): '''Construct an instance of the class from any iterable input. Must override this method if the class constructor signature does not accept an iterable for an input. ''' return cls(it) def __and__(self, other): if not isinstance(other, Iterable): return NotImplemented return self._from_iterable(value for value in other if value in self) def isdisjoint(self, other): for value in other: if value in self: return False return True def __or__(self, other): if not isinstance(other, Iterable): return NotImplemented chain = (e for s in (self, other) for e in s) return self._from_iterable(chain) def __sub__(self, other): if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = self._from_iterable(other) return self._from_iterable(value for value in self if value not in other) def __xor__(self, other): if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = self._from_iterable(other) return (self - other) | (other - self) # Sets are not hashable by default, but subclasses can change this __hash__ = None def _hash(self): """Compute the hash value of a set. Note that we don't define __hash__: not all sets are hashable. But if you define a hashable set type, its __hash__ should call this function. This must be compatible __eq__. All sets ought to compare equal if they contain the same elements, regardless of how they are implemented, and regardless of the order of the elements; so there's not much freedom for __eq__ or __hash__. We match the algorithm used by the built-in frozenset type. """ MAX = sys.maxint MASK = 2 * MAX + 1 n = len(self) h = 1927868237 * (n + 1) h &= MASK for x in self: hx = hash(x) h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167 h &= MASK h = h * 69069 + 907133923 h &= MASK if h > MAX: h -= MASK + 1 if h == -1: h = 590923713 return h Set.register(frozenset) class MutableSet(Set): @abstractmethod def add(self, value): """Return True if it was added, False if already there.""" raise NotImplementedError @abstractmethod<|fim▁hole|> """Return True if it was deleted, False if not there.""" raise NotImplementedError def remove(self, value): """Remove an element. If not a member, raise a KeyError.""" if value not in self: raise KeyError(value) self.discard(value) def pop(self): """Return the popped value. Raise KeyError if empty.""" it = iter(self) try: value = it.__next__() except StopIteration: raise KeyError self.discard(value) return value def clear(self): """This is slow (creates N new iterators!) but effective.""" try: while True: self.pop() except KeyError: pass def __ior__(self, it): for value in it: self.add(value) return self def __iand__(self, c): for value in self: if value not in c: self.discard(value) return self def __ixor__(self, it): if not isinstance(it, Set): it = self._from_iterable(it) for value in it: if value in self: self.discard(value) else: self.add(value) return self def __isub__(self, it): for value in it: self.discard(value) return self MutableSet.register(set) ### MAPPINGS ### class Mapping(Sized, Iterable, Container): @abstractmethod def __getitem__(self, key): raise KeyError def get(self, key, default=None): try: return self[key] except KeyError: return default def __contains__(self, key): try: self[key] except KeyError: return False else: return True def iterkeys(self): return iter(self) def itervalues(self): for key in self: yield self[key] def iteritems(self): for key in self: yield (key, self[key]) def keys(self): return list(self) def items(self): return [(key, self[key]) for key in self] def values(self): return [self[key] for key in self] # Mappings are not hashable by default, but subclasses can change this __hash__ = None def __eq__(self, other): return isinstance(other, Mapping) and \ dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) class MappingView(Sized): def __init__(self, mapping): self._mapping = mapping def __len__(self): return len(self._mapping) class KeysView(MappingView, Set): def __contains__(self, key): return key in self._mapping def __iter__(self): for key in self._mapping: yield key class ItemsView(MappingView, Set): def __contains__(self, item): key, value = item try: v = self._mapping[key] except KeyError: return False else: return v == value def __iter__(self): for key in self._mapping: yield (key, self._mapping[key]) class ValuesView(MappingView): def __contains__(self, value): for key in self._mapping: if value == self._mapping[key]: return True return False def __iter__(self): for key in self._mapping: yield self._mapping[key] class MutableMapping(Mapping): @abstractmethod def __setitem__(self, key, value): raise KeyError @abstractmethod def __delitem__(self, key): raise KeyError __marker = object() def pop(self, key, default=__marker): try: value = self[key] except KeyError: if default is self.__marker: raise return default else: del self[key] return value def popitem(self): try: key = next(iter(self)) except StopIteration: raise KeyError value = self[key] del self[key] return key, value def clear(self): try: while True: self.popitem() except KeyError: pass def update(self, other=(), **kwds): if isinstance(other, Mapping): for key in other: self[key] = other[key] elif hasattr(other, "keys"): for key in other.keys(): self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwds.items(): self[key] = value def setdefault(self, key, default=None): try: return self[key] except KeyError: self[key] = default return default MutableMapping.register(dict) ### SEQUENCES ### class Sequence(Sized, Iterable, Container): """All the operations on a read-only sequence. Concrete subclasses must override __new__ or __init__, __getitem__, and __len__. """ @abstractmethod def __getitem__(self, index): raise IndexError def __iter__(self): i = 0 try: while True: v = self[i] yield v i += 1 except IndexError: return def __contains__(self, value): for v in self: if v == value: return True return False def __reversed__(self): for i in reversed(range(len(self))): yield self[i] def index(self, value): for i, v in enumerate(self): if v == value: return i raise ValueError def count(self, value): return sum(1 for v in self if v == value) Sequence.register(tuple) Sequence.register(basestring) Sequence.register(buffer) class MutableSequence(Sequence): @abstractmethod def __setitem__(self, index, value): raise IndexError @abstractmethod def __delitem__(self, index): raise IndexError @abstractmethod def insert(self, index, value): raise IndexError def append(self, value): self.insert(len(self), value) def reverse(self): n = len(self) for i in range(n//2): self[i], self[n-i-1] = self[n-i-1], self[i] def extend(self, values): for v in values: self.append(v) def pop(self, index=-1): v = self[index] del self[index] return v def remove(self, value): del self[self.index(value)] def __iadd__(self, values): self.extend(values) MutableSequence.register(list)<|fim▁end|>
def discard(self, value):
<|file_name|>test.js<|end_file_name|><|fim▁begin|>var testLogin = function(){ var username = document.getElementById("username").value; var password = document.getElementById("password").value; alert("username="+username+" , password="+password); } window.onload = function (){ <|fim▁hole|><|fim▁end|>
}
<|file_name|>rpc-client.ts<|end_file_name|><|fim▁begin|>"use strict" import net = require("net") import rpc = require("./rpc") export class RpcClient { connect(port:Number = 63342) { var socket = net.connect({port: port}, function () { console.log('Connected to IJ RPC server localhost:' + port) }); var jsonRpc = new rpc.JsonRpc(new SocketTransport(socket)) var decoder:MessageDecoder = new MessageDecoder(jsonRpc.messageReceived) socket.on('data', decoder.messageReceived) } } const enum State {LENGTH, CONTENT} class SocketTransport implements rpc.Transport { private headerBuffer = new Buffer(4) constructor(private socket:net.Socket) { } send(id:number, domain:string, command:string, params:any[] = null):void { var encodedParams = JSON.stringify(params) var header = (id == -1 ? '' : (id + ', ')) + '"' + domain + '", "' + command + '"'; this.headerBuffer.writeUInt32BE(Buffer.byteLength(encodedParams) + header.length, 0) this.socket.write(this.headerBuffer) this.socket.write(encodedParams, 'utf-8') } sendResult(id:number, result:any):void { this.sendResultOrError(id, result, false) } sendError(id:number, error:any):void { this.sendResultOrError(id, error, true) } private sendResultOrError(id:number, result:any, isError:boolean):void { var encodedResult = JSON.stringify(result) var header = id + ', "' + (isError ? 'e': 'r') + '"'; this.headerBuffer.writeUInt32BE(Buffer.byteLength(encodedResult) + header.length, 0) this.socket.write(this.headerBuffer) this.socket.write(encodedResult, 'utf-8') } } class MessageDecoder { private state:State = State.LENGTH private contentLength:number = 0 private buffers:Array<Buffer> = [] private totalBufferLength:number = 0 private offset:number = 0 constructor(private messageProcessor:(message:any)=>void) { } private byteConsumed(count:number) { this.offset += count this.totalBufferLength -= count } messageReceived(buffer:Buffer) { this.totalBufferLength += buffer.length while (true) { //noinspection FallThroughInSwitchStatementJS switch (this.state) { case State.LENGTH: { if (this.totalBufferLength < 4) { this.buffers.push(buffer) return } var totalBuffer:Buffer if (this.buffers.length === 0) { totalBuffer = buffer } else { this.buffers.push(buffer) totalBuffer = Buffer.concat(this.buffers, this.totalBufferLength) this.buffers.length = 0 } this.state = State.CONTENT this.contentLength = totalBuffer.readUInt32BE(this.offset) this.byteConsumed(4) buffer = totalBuffer } case State.CONTENT: { if (this.totalBufferLength < this.contentLength) { this.buffers.push(buffer) return } var totalBuffer:Buffer if (this.buffers.length === 0) { totalBuffer = buffer } else { this.buffers.push(buffer) totalBuffer = Buffer.concat(this.buffers, this.totalBufferLength) this.buffers.length = 0 } var message = JSON.parse(totalBuffer.toString('utf8', this.offset, this.contentLength)); this.state = State.LENGTH<|fim▁hole|> this.messageProcessor(message) } } } } }<|fim▁end|>
this.byteConsumed(this.contentLength) this.contentLength = 0 buffer = totalBuffer
<|file_name|>allocate.rs<|end_file_name|><|fim▁begin|>// Our use cases use super::expander; pub fn allocate_expander(par_eax: i32, par_edx: i32) -> expander::SoundExpander { let mut sound_expander = expander::SoundExpander::new(); let mut par_eax = par_eax; let mut par_edx = par_edx; sound_expander.wave_format_ex.format_tag = expander::WAVE_FORMAT_PCM as u16; sound_expander.wave_format_ex.channels = 1; if 8 & par_edx != 0 { sound_expander.wave_format_ex.bits_per_sample = 16; } else { sound_expander.wave_format_ex.bits_per_sample = 8; } sound_expander.wave_format_ex.samples_per_second = 22050; // MixRate sound_expander.wave_format_ex.block_align = (sound_expander.wave_format_ex.channels * sound_expander.wave_format_ex.bits_per_sample) >> 3; sound_expander.wave_format_ex.cb_size = 0; sound_expander.wave_format_ex.average_bytes_per_second = ((sound_expander.wave_format_ex.samples_per_second as u16) * (sound_expander.wave_format_ex.block_align as u16)) as i32; par_edx = par_edx | 2; sound_expander.flags1 = par_edx; sound_expander.flags2 = par_eax; sound_expander.some_var_6680E8 = 0x10000; // SomeConst6680E8 sound_expander.some_var_6680EC = 0x10; // SomeConst6680EC sound_expander.read_limit = 0x10000 & 0x10; sound_expander.memb_64 = 0; sound_expander.memb_24 = 0; sound_expander.memb_40 = 0; sound_expander.memb_28 = 0x14; sound_expander.flags0 = 0x10000; <|fim▁hole|> sound_expander.flags0 = sound_expander.flags0 | 0x80; } else if 4 & par_edx != 0 { sound_expander.flags0 = sound_expander.flags0 | 0x40; } else if 0x40 & par_edx != 0 { sound_expander.flags0 = sound_expander.flags0 | 0x20; } if 0x10 & par_eax != 0 { sound_expander.flags1 = sound_expander.flags1 | 0x20; sound_expander.loop_point = -1; } else { sound_expander.loop_point = 0; } sound_expander.memb_58 = -1; sound_expander.memb_5C = 1; sound_expander.memb_4C = 0x7FFF; sound_expander.memb_54 = 0; sound_expander.previous = Box::new(expander::SoundExpander::new()); sound_expander.next = Box::new(expander::SoundExpander::new()); sound_expander } pub fn allocate_sound(par_ecx: i32, par_ebx: i32) -> expander::SoundExpander { let mut edx = 0x0A; let mut eax = 0; match par_ebx { 0x0D => eax = 1, 0x0E => eax = 2, _ => eax = 0, } match par_ecx { 0x0F => eax = eax | 4, _ => edx = edx | 0x20, } allocate_expander(eax, edx) }<|fim▁end|>
if 2 & par_edx != 0 {
<|file_name|>son_emu_simple_switch_13.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Nippon Telegraph and Telephone Corporation. # # 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 ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_3 from ryu.lib.packet import packet from ryu.lib.packet import ethernet from ryu.lib.packet import ether_types from ryu.topology.event import EventSwitchEnter, EventSwitchReconnected class SimpleSwitch13(app_manager.RyuApp): OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION] def __init__(self, *args, **kwargs): super(SimpleSwitch13, self).__init__(*args, **kwargs) self.mac_to_port = {} @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER) def switch_features_handler(self, ev): datapath = ev.msg.datapath ofproto = datapath.ofproto parser = datapath.ofproto_parser # install table-miss flow entry # # We specify NO BUFFER to max_len of the output action due to # OVS bug. At this moment, if we specify a lesser number, e.g., # 128, OVS will send Packet-In with invalid buffer_id and # truncated packet data. In that case, we cannot output packets # correctly. The bug has been fixed in OVS v2.1.0. match = parser.OFPMatch() # actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, # ofproto.OFPCML_NO_BUFFER)] actions = [parser.OFPActionOutput(ofproto.OFPCML_NO_BUFFER)] self.add_flow(datapath, 0, match, actions) def add_flow(self, datapath, priority, match, actions, buffer_id=None, table_id=0): ofproto = datapath.ofproto parser = datapath.ofproto_parser inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)] if buffer_id: mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id, priority=priority, match=match, instructions=inst, table_id=table_id) else: mod = parser.OFPFlowMod(datapath=datapath, priority=priority, match=match, instructions=inst, table_id=table_id) datapath.send_msg(mod) # new switch detected @set_ev_cls([EventSwitchEnter, EventSwitchReconnected]) def _ev_switch_enter_handler(self, ev): datapath = ev.switch.dp self.logger.info('registered OF switch id: %s' % datapath.id) ofproto = datapath.ofproto self.logger.info('OF version: {0}'.format(ofproto)) # send NORMAL action for all undefined flows ofp_parser = datapath.ofproto_parser actions = [ofp_parser.OFPActionOutput(ofproto_v1_3.OFPP_NORMAL)] self.add_flow(datapath, 0, None, actions, table_id=0) @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER) def _packet_in_handler(self, ev): # If you hit this you might want to increase # the "miss_send_length" of your switch if ev.msg.msg_len < ev.msg.total_len: self.logger.debug("packet truncated: only %s of %s bytes", ev.msg.msg_len, ev.msg.total_len) msg = ev.msg datapath = msg.datapath ofproto = datapath.ofproto parser = datapath.ofproto_parser in_port = msg.match['in_port'] pkt = packet.Packet(msg.data) eth = pkt.get_protocols(ethernet.ethernet)[0] if eth.ethertype == ether_types.ETH_TYPE_LLDP: # ignore lldp packet return dst = eth.dst src = eth.src dpid = datapath.id self.mac_to_port.setdefault(dpid, {}) self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port) # learn a mac address to avoid FLOOD next time. self.mac_to_port[dpid][src] = in_port<|fim▁hole|> out_port = self.mac_to_port[dpid][dst] else: out_port = ofproto.OFPP_FLOOD actions = [parser.OFPActionOutput(out_port)] # install a flow to avoid packet_in next time if out_port != ofproto.OFPP_FLOOD: match = parser.OFPMatch(in_port=in_port, eth_dst=dst) # verify if we have a valid buffer_id, if yes avoid to send both # flow_mod & packet_out if msg.buffer_id != ofproto.OFP_NO_BUFFER: self.add_flow(datapath, 1, match, actions, msg.buffer_id) return else: self.add_flow(datapath, 1, match, actions) data = None if msg.buffer_id == ofproto.OFP_NO_BUFFER: data = msg.data out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port, actions=actions, data=data) datapath.send_msg(out)<|fim▁end|>
if dst in self.mac_to_port[dpid]:
<|file_name|>test_Factor.py<|end_file_name|><|fim▁begin|>import unittest import warnings from collections import OrderedDict import numpy as np import numpy.testing as np_test from pgmpy.extern.six.moves import range from pgmpy.factors.discrete import DiscreteFactor from pgmpy.factors.discrete import JointProbabilityDistribution as JPD from pgmpy.factors import factor_divide from pgmpy.factors import factor_product from pgmpy.factors.discrete.CPD import TabularCPD from pgmpy.independencies import Independencies from pgmpy.models import BayesianModel from pgmpy.models import MarkovModel class TestFactorInit(unittest.TestCase): def test_class_init(self): phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 2, 2], np.ones(8)) self.assertEqual(phi.variables, ['x1', 'x2', 'x3']) np_test.assert_array_equal(phi.cardinality, np.array([2, 2, 2])) np_test.assert_array_equal(phi.values, np.ones(8).reshape(2, 2, 2)) def test_class_init1(self): phi = DiscreteFactor([1, 2, 3], [2, 3, 2], np.arange(12)) self.assertEqual(phi.variables, [1, 2, 3]) np_test.assert_array_equal(phi.cardinality, np.array([2, 3, 2])) np_test.assert_array_equal(phi.values, np.arange(12).reshape(2, 3, 2)) def test_class_init_sizeerror(self): self.assertRaises(ValueError, DiscreteFactor, ['x1', 'x2', 'x3'], [2, 2, 2], np.ones(9)) def test_class_init_typeerror(self): self.assertRaises(TypeError, DiscreteFactor, 'x1', [3], [1, 2, 3]) self.assertRaises(ValueError, DiscreteFactor, ['x1', 'x1', 'x3'], [2, 3, 2], range(12)) def test_init_size_var_card_not_equal(self): self.assertRaises(ValueError, DiscreteFactor, ['x1', 'x2'], [2], np.ones(2)) class TestFactorMethods(unittest.TestCase): def setUp(self): self.phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 2, 2], np.random.uniform(5, 10, size=8)) self.phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12)) self.phi2 = DiscreteFactor([('x1', 0), ('x2', 0), ('x3', 0)], [2, 3, 2], range(12)) # This larger factor (phi3) caused a bug in reduce card3 = [3, 3, 3, 2, 2, 2, 2, 2, 2] self.phi3 = DiscreteFactor(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], card3, np.arange(np.prod(card3), dtype=np.float)) self.tup1 = ('x1', 'x2') self.tup2 = ('x2', 'x3') self.tup3 = ('x3', (1, 'x4')) self.phi4 = DiscreteFactor([self.tup1, self.tup2, self.tup3], [2, 3, 4], np.random.uniform(3, 10, size=24)) self.phi5 = DiscreteFactor([self.tup1, self.tup2, self.tup3], [2, 3, 4], range(24)) self.card6 = [4, 2, 1, 3, 5, 6] self.phi6 = DiscreteFactor([self.tup1, self.tup2, self.tup3, self.tup1 + self.tup2, self.tup2 + self.tup3, self.tup3 + self.tup1], self.card6, np.arange(np.prod(self.card6), dtype=np.float)) self.var1 = 'x1' self.var2 = ('x2', 1) self.var3 = frozenset(['x1', 'x2']) self.phi7 = DiscreteFactor([self.var1, self.var2], [3, 2], [3, 2, 4, 5, 9, 8]) self.phi8 = DiscreteFactor([self.var2, self.var3], [2, 2], [2, 1, 5, 6]) self.phi9 = DiscreteFactor([self.var1, self.var3], [3, 2], [3, 2, 4, 5, 9, 8]) self.phi10 = DiscreteFactor([self.var3], [2], [3, 6]) def test_scope(self): self.assertListEqual(self.phi.scope(), ['x1', 'x2', 'x3']) self.assertListEqual(self.phi1.scope(), ['x1', 'x2', 'x3']) self.assertListEqual(self.phi4.scope(), [self.tup1, self.tup2, self.tup3]) def test_assignment(self): self.assertListEqual(self.phi.assignment([0]), [[('x1', 0), ('x2', 0), ('x3', 0)]]) self.assertListEqual(self.phi.assignment([4, 5, 6]), [[('x1', 1), ('x2', 0), ('x3', 0)], [('x1', 1), ('x2', 0), ('x3', 1)], [('x1', 1), ('x2', 1), ('x3', 0)]]) self.assertListEqual(self.phi1.assignment(np.array([4, 5, 6])), [[('x1', 0), ('x2', 2), ('x3', 0)], [('x1', 0), ('x2', 2), ('x3', 1)], [('x1', 1), ('x2', 0), ('x3', 0)]]) self.assertListEqual(self.phi4.assignment(np.array([11, 12, 23])), [[(self.tup1, 0), (self.tup2, 2), (self.tup3, 3)], [(self.tup1, 1), (self.tup2, 0), (self.tup3, 0)], [(self.tup1, 1), (self.tup2, 2), (self.tup3, 3)]]) def test_assignment_indexerror(self): self.assertRaises(IndexError, self.phi.assignment, [10]) self.assertRaises(IndexError, self.phi.assignment, [1, 3, 10, 5]) self.assertRaises(IndexError, self.phi.assignment, np.array([1, 3, 10, 5])) self.assertRaises(IndexError, self.phi4.assignment, [2, 24]) self.assertRaises(IndexError, self.phi4.assignment, np.array([24, 2, 4, 30])) def test_get_cardinality(self): self.assertEqual(self.phi.get_cardinality(['x1']), {'x1': 2}) self.assertEqual(self.phi.get_cardinality(['x2']), {'x2': 2}) self.assertEqual(self.phi.get_cardinality(['x3']), {'x3': 2}) self.assertEqual(self.phi.get_cardinality(['x1', 'x2']), {'x1': 2, 'x2': 2}) self.assertEqual(self.phi.get_cardinality(['x1', 'x3']), {'x1': 2, 'x3': 2}) self.assertEqual(self.phi.get_cardinality(['x1', 'x2', 'x3']), {'x1': 2, 'x2': 2, 'x3': 2}) self.assertEqual(self.phi4.get_cardinality([self.tup1, self.tup3]), {self.tup1: 2, self.tup3: 4}) def test_get_cardinality_scopeerror(self): self.assertRaises(ValueError, self.phi.get_cardinality, ['x4']) self.assertRaises(ValueError, self.phi4.get_cardinality, [('x1', 'x4')]) self.assertRaises(ValueError, self.phi4.get_cardinality, [('x3', (2, 'x4'))]) def test_get_cardinality_typeerror(self): self.assertRaises(TypeError, self.phi.get_cardinality, 'x1') def test_marginalize(self): self.phi1.marginalize(['x1']) np_test.assert_array_equal(self.phi1.values, np.array([[6, 8], [10, 12], [14, 16]])) self.phi1.marginalize(['x2']) np_test.assert_array_equal(self.phi1.values, np.array([30, 36])) self.phi1.marginalize(['x3']) np_test.assert_array_equal(self.phi1.values, np.array(66)) self.phi5.marginalize([self.tup1]) np_test.assert_array_equal(self.phi5.values, np.array([[12, 14, 16, 18], [20, 22, 24, 26], [28, 30, 32, 34]])) self.phi5.marginalize([self.tup2]) np_test.assert_array_equal(self.phi5.values, np.array([60, 66, 72, 78])) self.phi5.marginalize([self.tup3]) np_test.assert_array_equal(self.phi5.values, np.array([276])) def test_marginalize_scopeerror(self): self.assertRaises(ValueError, self.phi.marginalize, ['x4']) self.phi.marginalize(['x1']) self.assertRaises(ValueError, self.phi.marginalize, ['x1']) self.assertRaises(ValueError, self.phi4.marginalize, [('x1', 'x3')]) self.phi4.marginalize([self.tup2]) self.assertRaises(ValueError, self.phi4.marginalize, [self.tup2]) def test_marginalize_typeerror(self): self.assertRaises(TypeError, self.phi.marginalize, 'x1') def test_marginalize_shape(self): values = ['A', 'D', 'F', 'H'] phi3_mar = self.phi3.marginalize(values, inplace=False) # Previously a sorting error caused these to be different np_test.assert_array_equal(phi3_mar.values.shape, phi3_mar.cardinality) phi6_mar = self.phi6.marginalize([self.tup1, self.tup2], inplace=False) np_test.assert_array_equal(phi6_mar.values.shape, phi6_mar.cardinality) self.phi6.marginalize([self.tup1, self.tup3 + self.tup1], inplace=True) np_test.assert_array_equal(self.phi6.values.shape, self.phi6.cardinality) def test_normalize(self): self.phi1.normalize() np_test.assert_almost_equal(self.phi1.values, np.array([[[0, 0.01515152], [0.03030303, 0.04545455], [0.06060606, 0.07575758]], [[0.09090909, 0.10606061], [0.12121212, 0.13636364], [0.15151515, 0.16666667]]])) self.phi5.normalize() np_test.assert_almost_equal(self.phi5.values, [[[0., 0.00362319, 0.00724638, 0.01086957], [0.01449275, 0.01811594, 0.02173913, 0.02536232], [0.02898551, 0.0326087, 0.03623188, 0.03985507]], [[0.04347826, 0.04710145, 0.05072464, 0.05434783], [0.05797101, 0.0615942, 0.06521739, 0.06884058], [0.07246377, 0.07608696, 0.07971014, 0.08333333]]]) def test_reduce(self): self.phi1.reduce([('x1', 0), ('x2', 0)]) np_test.assert_array_equal(self.phi1.values, np.array([0, 1])) self.phi5.reduce([(self.tup1, 0), (self.tup3, 1)]) np_test.assert_array_equal(self.phi5.values, np.array([1, 5, 9])) def test_reduce1(self): self.phi1.reduce([('x2', 0), ('x1', 0)]) np_test.assert_array_equal(self.phi1.values, np.array([0, 1])) self.phi5.reduce([(self.tup3, 1), (self.tup1, 0)]) np_test.assert_array_equal(self.phi5.values, np.array([1, 5, 9])) def test_reduce_shape(self): values = [('A', 0), ('D', 0), ('F', 0), ('H', 1)] phi3_reduced = self.phi3.reduce(values, inplace=False) # Previously a sorting error caused these to be different np_test.assert_array_equal(phi3_reduced.values.shape, phi3_reduced.cardinality) values = [(self.tup1, 2), (self.tup3, 0)] phi6_reduced = self.phi6.reduce(values, inplace=False) np_test.assert_array_equal(phi6_reduced.values.shape, phi6_reduced.cardinality) self.phi6.reduce(values, inplace=True) np_test.assert_array_equal(self.phi6.values.shape, self.phi6.cardinality) def test_complete_reduce(self): self.phi1.reduce([('x1', 0), ('x2', 0), ('x3', 1)]) np_test.assert_array_equal(self.phi1.values, np.array([1])) np_test.assert_array_equal(self.phi1.cardinality, np.array([])) np_test.assert_array_equal(self.phi1.variables, OrderedDict()) self.phi5.reduce([(('x1', 'x2'), 1), (('x2', 'x3'), 0), (('x3', (1, 'x4')), 3)]) np_test.assert_array_equal(self.phi5.values, np.array([15])) np_test.assert_array_equal(self.phi5.cardinality, np.array([])) np_test.assert_array_equal(self.phi5.variables, OrderedDict()) def test_reduce_typeerror(self): self.assertRaises(TypeError, self.phi1.reduce, 'x10') self.assertRaises(TypeError, self.phi1.reduce, ['x10']) self.assertRaises(TypeError, self.phi1.reduce, [('x1', 'x2')]) self.assertRaises(TypeError, self.phi1.reduce, [(0, 'x1')]) self.assertRaises(TypeError, self.phi1.reduce, [(0.1, 'x1')]) self.assertRaises(TypeError, self.phi1.reduce, [(0.1, 0.1)]) self.assertRaises(TypeError, self.phi1.reduce, [('x1', 0.1)]) self.assertRaises(TypeError, self.phi5.reduce, [(('x1', 'x2'), 0), (('x2', 'x3'), 0.2)]) def test_reduce_scopeerror(self): self.assertRaises(ValueError, self.phi1.reduce, [('x4', 1)]) self.assertRaises(ValueError, self.phi5.reduce, [((('x1', 0.1), 0))]) def test_reduce_sizeerror(self): self.assertRaises(IndexError, self.phi1.reduce, [('x3', 5)]) self.assertRaises(IndexError, self.phi5.reduce, [(('x2', 'x3'), 3)]) def test_identity_factor(self): identity_factor = self.phi.identity_factor() self.assertEqual(list(identity_factor.variables), ['x1', 'x2', 'x3']) np_test.assert_array_equal(identity_factor.cardinality, [2, 2, 2]) np_test.assert_array_equal(identity_factor.values, np.ones(8).reshape(2, 2, 2)) identity_factor1 = self.phi5.identity_factor() self.assertEqual(list(identity_factor1.variables), [self.tup1, self.tup2, self.tup3]) np_test.assert_array_equal(identity_factor1.cardinality, [2, 3, 4]) np_test.assert_array_equal(identity_factor1.values, np.ones(24).reshape(2, 3, 4)) def test_factor_product(self): phi = DiscreteFactor(['x1', 'x2'], [2, 2], range(4)) phi1 = DiscreteFactor(['x3', 'x4'], [2, 2], range(4)) prod = factor_product(phi, phi1) expected_factor = DiscreteFactor(['x1', 'x2', 'x3', 'x4'], [2, 2, 2, 2], [0, 0, 0, 0, 0, 1, 2, 3, 0, 2, 4, 6, 0, 3, 6, 9]) self.assertEqual(prod, expected_factor) self.assertEqual(sorted(prod.variables), ['x1', 'x2', 'x3', 'x4']) phi = DiscreteFactor(['x1', 'x2'], [3, 2], range(6)) phi1 = DiscreteFactor(['x2', 'x3'], [2, 2], range(4)) prod = factor_product(phi, phi1) expected_factor = DiscreteFactor(['x1', 'x2', 'x3'], [3, 2, 2], [0, 0, 2, 3, 0, 2, 6, 9, 0, 4, 10, 15]) self.assertEqual(prod, expected_factor) self.assertEqual(prod.variables, expected_factor.variables) prod = factor_product(self.phi7, self.phi8) expected_factor = DiscreteFactor([self.var1, self.var2, self.var3], [3, 2, 2], [6, 3, 10, 12, 8, 4, 25, 30, 18, 9, 40, 48]) self.assertEqual(prod, expected_factor) self.assertEqual(prod.variables, expected_factor.variables) def test_product(self): phi = DiscreteFactor(['x1', 'x2'], [2, 2], range(4)) phi1 = DiscreteFactor(['x3', 'x4'], [2, 2], range(4)) prod = phi.product(phi1, inplace=False) expected_factor = DiscreteFactor(['x1', 'x2', 'x3', 'x4'], [2, 2, 2, 2], [0, 0, 0, 0, 0, 1, 2, 3, 0, 2, 4, 6, 0, 3, 6, 9]) self.assertEqual(prod, expected_factor) self.assertEqual(sorted(prod.variables), ['x1', 'x2', 'x3', 'x4']) phi = DiscreteFactor(['x1', 'x2'], [3, 2], range(6)) phi1 = DiscreteFactor(['x2', 'x3'], [2, 2], range(4)) prod = phi.product(phi1, inplace=False) expected_factor = DiscreteFactor(['x1', 'x2', 'x3'], [3, 2, 2], [0, 0, 2, 3, 0, 2, 6, 9, 0, 4, 10, 15]) self.assertEqual(prod, expected_factor) self.assertEqual(sorted(prod.variables), ['x1', 'x2', 'x3']) phi7_copy = self.phi7 phi7_copy.product(self.phi8, inplace=True) expected_factor = DiscreteFactor([self.var1, self.var2, self.var3], [3, 2, 2], [6, 3, 10, 12, 8, 4, 25, 30, 18, 9, 40, 48]) self.assertEqual(expected_factor, phi7_copy) self.assertEqual(phi7_copy.variables, [self.var1, self.var2, self.var3]) def test_factor_product_non_factor_arg(self):<|fim▁hole|> def test_factor_mul(self): phi = DiscreteFactor(['x1', 'x2'], [2, 2], range(4)) phi1 = DiscreteFactor(['x3', 'x4'], [2, 2], range(4)) prod = phi * phi1 sorted_vars = ['x1', 'x2', 'x3', 'x4'] for axis in range(prod.values.ndim): exchange_index = prod.variables.index(sorted_vars[axis]) prod.variables[axis], prod.variables[exchange_index] = prod.variables[exchange_index], prod.variables[axis] prod.values = prod.values.swapaxes(axis, exchange_index) np_test.assert_almost_equal(prod.values.ravel(), np.array([0, 0, 0, 0, 0, 1, 2, 3, 0, 2, 4, 6, 0, 3, 6, 9])) self.assertEqual(prod.variables, ['x1', 'x2', 'x3', 'x4']) def test_factor_divide(self): phi1 = DiscreteFactor(['x1', 'x2'], [2, 2], [1, 2, 2, 4]) phi2 = DiscreteFactor(['x1'], [2], [1, 2]) expected_factor = phi1.divide(phi2, inplace=False) phi3 = DiscreteFactor(['x1', 'x2'], [2, 2], [1, 2, 1, 2]) self.assertEqual(phi3, expected_factor) self.phi9.divide(self.phi10, inplace=True) np_test.assert_array_almost_equal(self.phi9.values, np.array([1.000000, 0.333333, 1.333333, 0.833333, 3.000000, 1.333333]).reshape(3, 2)) self.assertEqual(self.phi9.variables, [self.var1, self.var3]) def test_factor_divide_truediv(self): phi1 = DiscreteFactor(['x1', 'x2'], [2, 2], [1, 2, 2, 4]) phi2 = DiscreteFactor(['x1'], [2], [1, 2]) div = phi1 / phi2 phi3 = DiscreteFactor(['x1', 'x2'], [2, 2], [1, 2, 1, 2]) self.assertEqual(phi3, div) self.phi9 = self.phi9 / self.phi10 np_test.assert_array_almost_equal(self.phi9.values, np.array([1.000000, 0.333333, 1.333333, 0.833333, 3.000000, 1.333333]).reshape(3, 2)) self.assertEqual(self.phi9.variables, [self.var1, self.var3]) def test_factor_divide_invalid(self): phi1 = DiscreteFactor(['x1', 'x2'], [2, 2], [1, 2, 3, 4]) phi2 = DiscreteFactor(['x1'], [2], [0, 2]) div = phi1.divide(phi2, inplace=False) np_test.assert_array_equal(div.values.ravel(), np.array([np.inf, np.inf, 1.5, 2])) def test_factor_divide_no_common_scope(self): phi1 = DiscreteFactor(['x1', 'x2'], [2, 2], [1, 2, 3, 4]) phi2 = DiscreteFactor(['x3'], [2], [0, 2]) self.assertRaises(ValueError, factor_divide, phi1, phi2) phi2 = DiscreteFactor([self.var3], [2], [2, 1]) self.assertRaises(ValueError, factor_divide, self.phi7, phi2) def test_factor_divide_non_factor_arg(self): self.assertRaises(TypeError, factor_divide, 1, 1) def test_eq(self): self.assertFalse(self.phi == self.phi1) self.assertTrue(self.phi == self.phi) self.assertTrue(self.phi1 == self.phi1) self.assertTrue(self.phi5 == self.phi5) self.assertFalse(self.phi5 == self.phi6) self.assertTrue(self.phi6 == self.phi6) def test_eq1(self): phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 4, 3], range(24)) phi2 = DiscreteFactor(['x2', 'x1', 'x3'], [4, 2, 3], [0, 1, 2, 12, 13, 14, 3, 4, 5, 15, 16, 17, 6, 7, 8, 18, 19, 20, 9, 10, 11, 21, 22, 23]) self.assertTrue(phi1 == phi2) self.assertEqual(phi2.variables, ['x2', 'x1', 'x3']) phi3 = DiscreteFactor([self.tup1, self.tup2, self.tup3], [2, 4, 3], range(24)) phi4 = DiscreteFactor([self.tup2, self.tup1, self.tup3], [4, 2, 3], [0, 1, 2, 12, 13, 14, 3, 4, 5, 15, 16, 17, 6, 7, 8, 18, 19, 20, 9, 10, 11, 21, 22, 23]) self.assertTrue(phi3 == phi4) def test_hash(self): phi1 = DiscreteFactor(['x1', 'x2'], [2, 2], [1, 2, 3, 4]) phi2 = DiscreteFactor(['x2', 'x1'], [2, 2], [1, 3, 2, 4]) self.assertEqual(hash(phi1), hash(phi2)) phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 2, 2], range(8)) phi2 = DiscreteFactor(['x3', 'x1', 'x2'], [2, 2, 2], [0, 2, 4, 6, 1, 3, 5, 7]) self.assertEqual(hash(phi1), hash(phi2)) var1 = TestHash(1, 2) phi3 = DiscreteFactor([var1, self.var2, self.var3], [2, 4, 3], range(24)) phi4 = DiscreteFactor([self.var2, var1, self.var3], [4, 2, 3], [0, 1, 2, 12, 13, 14, 3, 4, 5, 15, 16, 17, 6, 7, 8, 18, 19, 20, 9, 10, 11, 21, 22, 23]) self.assertEqual(hash(phi3), hash(phi4)) var1 = TestHash(2, 3) var2 = TestHash('x2', 1) phi3 = DiscreteFactor([var1, var2, self.var3], [2, 2, 2], range(8)) phi4 = DiscreteFactor([self.var3, var1, var2], [2, 2, 2], [0, 2, 4, 6, 1, 3, 5, 7]) self.assertEqual(hash(phi3), hash(phi4)) def test_maximize_single(self): self.phi1.maximize(['x1']) self.assertEqual(self.phi1, DiscreteFactor(['x2', 'x3'], [3, 2], [6, 7, 8, 9, 10, 11])) self.phi1.maximize(['x2']) self.assertEqual(self.phi1, DiscreteFactor(['x3'], [2], [10, 11])) self.phi2 = DiscreteFactor(['x1', 'x2', 'x3'], [3, 2, 2], [0.25, 0.35, 0.08, 0.16, 0.05, 0.07, 0.00, 0.00, 0.15, 0.21, 0.08, 0.18]) self.phi2.maximize(['x2']) self.assertEqual(self.phi2, DiscreteFactor(['x1', 'x3'], [3, 2], [0.25, 0.35, 0.05, 0.07, 0.15, 0.21])) self.phi5.maximize([('x1', 'x2')]) self.assertEqual(self.phi5, DiscreteFactor([('x2', 'x3'), ('x3', (1, 'x4'))], [3, 4], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])) self.phi5.maximize([('x2', 'x3')]) self.assertEqual(self.phi5, DiscreteFactor([('x3', (1, 'x4'))], [4], [20, 21, 22, 23])) def test_maximize_list(self): self.phi1.maximize(['x1', 'x2']) self.assertEqual(self.phi1, DiscreteFactor(['x3'], [2], [10, 11])) self.phi5.maximize([('x1', 'x2'), ('x2', 'x3')]) self.assertEqual(self.phi5, DiscreteFactor([('x3', (1, 'x4'))], [4], [20, 21, 22, 23])) def test_maximize_shape(self): values = ['A', 'D', 'F', 'H'] phi3_max = self.phi3.maximize(values, inplace=False) # Previously a sorting error caused these to be different np_test.assert_array_equal(phi3_max.values.shape, phi3_max.cardinality) phi = DiscreteFactor([self.var1, self.var2, self.var3], [3, 2, 2], [3, 2, 4, 5, 9, 8, 3, 2, 4, 5, 9, 8]) phi_max = phi.marginalize([self.var1, self.var2], inplace=False) np_test.assert_array_equal(phi_max.values.shape, phi_max.cardinality) def test_maximize_scopeerror(self): self.assertRaises(ValueError, self.phi.maximize, ['x10']) def test_maximize_typeerror(self): self.assertRaises(TypeError, self.phi.maximize, 'x1') def tearDown(self): del self.phi del self.phi1 del self.phi2 del self.phi3 del self.phi4 del self.phi5 del self.phi6 del self.phi7 del self.phi8 del self.phi9 del self.phi10 class TestHash: # Used to check the hash function of DiscreteFactor class. def __init__(self, x, y): self.x = x self.y = y def __hash__(self): return hash(str(self.x) + str(self.y)) def __eq__(self, other): return isinstance(other, self.__class__) and self.x == other.x and self.y == other.y class TestTabularCPDInit(unittest.TestCase): def test_cpd_init(self): cpd = TabularCPD('grade', 3, [[0.1, 0.1, 0.1]]) self.assertEqual(cpd.variable, 'grade') self.assertEqual(cpd.variable_card, 3) self.assertEqual(list(cpd.variables), ['grade']) np_test.assert_array_equal(cpd.cardinality, np.array([3])) np_test.assert_array_almost_equal(cpd.values, np.array([0.1, 0.1, 0.1])) values = [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]] evidence = ['intel', 'diff'] evidence_card = [3, 2] valid_value_inputs = [values, np.asarray(values)] valid_evidence_inputs = [evidence, set(evidence), np.asarray(evidence)] valid_evidence_card_inputs = [evidence_card, np.asarray(evidence_card)] for value in valid_value_inputs: for evidence in valid_evidence_inputs: for evidence_card in valid_evidence_card_inputs: cpd = TabularCPD('grade', 3, values, evidence=['intel', 'diff'], evidence_card=[3, 2]) self.assertEqual(cpd.variable, 'grade') self.assertEqual(cpd.variable_card, 3) np_test.assert_array_equal(cpd.cardinality, np.array([3, 3, 2])) self.assertListEqual(list(cpd.variables), ['grade', 'intel', 'diff']) np_test.assert_array_equal(cpd.values, np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8]).reshape(3, 3, 2)) cpd = TabularCPD('grade', 3, [[0.1, 0.1], [0.1, 0.1], [0.8, 0.8]], evidence=['evi1'], evidence_card=[2.0]) self.assertEqual(cpd.variable, 'grade') self.assertEqual(cpd.variable_card, 3) np_test.assert_array_equal(cpd.cardinality, np.array([3, 2])) self.assertListEqual(list(cpd.variables), ['grade', 'evi1']) np_test.assert_array_equal(cpd.values, np.array([0.1, 0.1, 0.1, 0.1, 0.8, 0.8]).reshape(3, 2)) def test_cpd_init_event_card_not_int(self): self.assertRaises(TypeError, TabularCPD, 'event', '2', [[0.1, 0.9]]) def test_cpd_init_cardinality_not_specified(self): self.assertRaises(ValueError, TabularCPD, 'event', 3, [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], ['evi1', 'evi2'], [5]) self.assertRaises(ValueError, TabularCPD, 'event', 3, [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], ['evi1', 'evi2'], [5.0]) self.assertRaises(ValueError, TabularCPD, 'event', 3, [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], ['evi1'], [5, 6]) self.assertRaises(TypeError, TabularCPD, 'event', 3, [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], 'evi1', [5, 6]) def test_cpd_init_value_not_2d(self): self.assertRaises(TypeError, TabularCPD, 'event', 3, [[[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]]], ['evi1', 'evi2'], [5, 6]) class TestTabularCPDMethods(unittest.TestCase): def setUp(self): self.cpd = TabularCPD('grade', 3, [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], evidence=['intel', 'diff'], evidence_card=[3, 2]) self.cpd2 = TabularCPD('J', 2, [[0.9, 0.3, 0.9, 0.3, 0.8, 0.8, 0.4, 0.4], [0.1, 0.7, 0.1, 0.7, 0.2, 0.2, 0.6, 0.6]], evidence=['A', 'B', 'C'], evidence_card=[2, 2, 2]) def test_marginalize_1(self): self.cpd.marginalize(['diff']) self.assertEqual(self.cpd.variable, 'grade') self.assertEqual(self.cpd.variable_card, 3) self.assertListEqual(list(self.cpd.variables), ['grade', 'intel']) np_test.assert_array_equal(self.cpd.cardinality, np.array([3, 3])) np_test.assert_array_equal(self.cpd.values.ravel(), np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.8, 0.8, 0.8])) def test_marginalize_2(self): self.assertRaises(ValueError, self.cpd.marginalize, ['grade']) def test_marginalize_3(self): copy_cpd = self.cpd.copy() copy_cpd.marginalize(['intel', 'diff']) self.cpd.marginalize(['intel']) self.cpd.marginalize(['diff']) np_test.assert_array_almost_equal(self.cpd.values, copy_cpd.values) def test_normalize(self): cpd_un_normalized = TabularCPD('grade', 2, [[0.7, 0.2, 0.6, 0.2], [0.4, 0.4, 0.4, 0.8]], ['intel', 'diff'], [2, 2]) cpd_un_normalized.normalize() np_test.assert_array_almost_equal(cpd_un_normalized.values, np.array([[[0.63636364, 0.33333333], [0.6, 0.2]], [[0.36363636, 0.66666667], [0.4, 0.8]]])) def test_normalize_not_in_place(self): cpd_un_normalized = TabularCPD('grade', 2, [[0.7, 0.2, 0.6, 0.2], [0.4, 0.4, 0.4, 0.8]], ['intel', 'diff'], [2, 2]) np_test.assert_array_almost_equal(cpd_un_normalized.normalize(inplace=False).values, np.array([[[0.63636364, 0.33333333], [0.6, 0.2]], [[0.36363636, 0.66666667], [0.4, 0.8]]])) def test_normalize_original_safe(self): cpd_un_normalized = TabularCPD('grade', 2, [[0.7, 0.2, 0.6, 0.2], [0.4, 0.4, 0.4, 0.8]], ['intel', 'diff'], [2, 2]) cpd_un_normalized.normalize(inplace=False) np_test.assert_array_almost_equal(cpd_un_normalized.values, np.array([[[0.7, 0.2], [0.6, 0.2]], [[0.4, 0.4], [0.4, 0.8]]])) def test__repr__(self): grade_cpd = TabularCPD('grade', 3, [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], evidence=['intel', 'diff'], evidence_card=[3, 2]) intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]]) diff_cpd = TabularCPD('grade', 3, [[0.1, 0.1], [0.1, 0.1], [0.8, 0.8]], evidence=['diff'], evidence_card=[2]) self.assertEqual(repr(grade_cpd), '<TabularCPD representing P(grade:3 | intel:3, diff:2) at {address}>' .format(address=hex(id(grade_cpd)))) self.assertEqual(repr(intel_cpd), '<TabularCPD representing P(intel:3) at {address}>' .format(address=hex(id(intel_cpd)))) self.assertEqual(repr(diff_cpd), '<TabularCPD representing P(grade:3 | diff:2) at {address}>' .format(address=hex(id(diff_cpd)))) def test_copy(self): copy_cpd = self.cpd.copy() np_test.assert_array_equal(self.cpd.get_values(), copy_cpd.get_values()) def test_copy_original_safe(self): copy_cpd = self.cpd.copy() copy_cpd.reorder_parents(['diff', 'intel']) np_test.assert_array_equal(self.cpd.get_values(), np.array([[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]])) def test_reduce_1(self): self.cpd.reduce([('diff', 0)]) np_test.assert_array_equal(self.cpd.get_values(), np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.8, 0.8, 0.8]])) def test_reduce_2(self): self.cpd.reduce([('intel', 0)]) np_test.assert_array_equal(self.cpd.get_values(), np.array([[0.1, 0.1], [0.1, 0.1], [0.8, 0.8]])) def test_reduce_3(self): self.cpd.reduce([('intel', 0), ('diff', 0)]) np_test.assert_array_equal(self.cpd.get_values(), np.array([[0.1], [0.1], [0.8]])) def test_reduce_4(self): self.assertRaises(ValueError, self.cpd.reduce, [('grade', 0)]) def test_reduce_5(self): copy_cpd = self.cpd.copy() copy_cpd.reduce([('intel', 2), ('diff', 1)]) self.cpd.reduce([('intel', 2)]) self.cpd.reduce([('diff', 1)]) np_test.assert_array_almost_equal(self.cpd.values, copy_cpd.values) def test_get_values(self): np_test.assert_array_equal(self.cpd.get_values(), np.array([[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]])) def test_reorder_parents_inplace(self): new_vals = self.cpd2.reorder_parents(['B', 'A', 'C']) np_test.assert_array_equal(new_vals, np.array([[0.9, 0.3, 0.8, 0.8, 0.9, 0.3, 0.4, 0.4], [0.1, 0.7, 0.2, 0.2, 0.1, 0.7, 0.6, 0.6]])) np_test.assert_array_equal(self.cpd2.get_values(), np.array([[0.9, 0.3, 0.8, 0.8, 0.9, 0.3, 0.4, 0.4], [0.1, 0.7, 0.2, 0.2, 0.1, 0.7, 0.6, 0.6]])) def test_reorder_parents(self): new_vals = self.cpd2.reorder_parents(['B', 'A', 'C']) np_test.assert_array_equal(new_vals, np.array([[0.9, 0.3, 0.8, 0.8, 0.9, 0.3, 0.4, 0.4], [0.1, 0.7, 0.2, 0.2, 0.1, 0.7, 0.6, 0.6]])) def test_reorder_parents_no_effect(self): self.cpd2.reorder_parents(['C', 'A', 'B'], inplace=False) np_test.assert_array_equal(self.cpd2.get_values(), np.array([[0.9, 0.3, 0.9, 0.3, 0.8, 0.8, 0.4, 0.4], [0.1, 0.7, 0.1, 0.7, 0.2, 0.2, 0.6, 0.6]])) def test_reorder_parents_warning(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") self.cpd2.reorder_parents(['A', 'B', 'C'], inplace=False) assert("Same ordering provided as current" in str(w[-1].message)) np_test.assert_array_equal(self.cpd2.get_values(), np.array([[0.9, 0.3, 0.9, 0.3, 0.8, 0.8, 0.4, 0.4], [0.1, 0.7, 0.1, 0.7, 0.2, 0.2, 0.6, 0.6]])) def tearDown(self): del self.cpd class TestJointProbabilityDistributionInit(unittest.TestCase): def test_jpd_init(self): jpd = JPD(['x1', 'x2', 'x3'], [2, 3, 2], np.ones(12) / 12) np_test.assert_array_equal(jpd.cardinality, np.array([2, 3, 2])) np_test.assert_array_equal(jpd.values, np.ones(12).reshape(2, 3, 2) / 12) self.assertEqual(jpd.get_cardinality(['x1', 'x2', 'x3']), {'x1': 2, 'x2': 3, 'x3': 2}) def test_jpd_init_exception(self): self.assertRaises(ValueError, JPD, ['x1', 'x2', 'x3'], [2, 2, 2], np.ones(8)) class TestJointProbabilityDistributionMethods(unittest.TestCase): def setUp(self): self.jpd = JPD(['x1', 'x2', 'x3'], [2, 3, 2], values=np.ones(12) / 12) self.jpd1 = JPD(['x1', 'x2', 'x3'], [2, 3, 2], values=np.ones(12) / 12) self.jpd2 = JPD(['x1', 'x2', 'x3'], [2, 2, 3], [0.126, 0.168, 0.126, 0.009, 0.045, 0.126, 0.252, 0.0224, 0.0056, 0.06, 0.036, 0.024]) self.jpd3 = JPD(['x1', 'x2', 'x3'], [2, 2, 2], [5.0e-04, 5.225e-04, 0.00, 8.9775e-03, 9.9e-03, 5.39055e-02, 0.00, 9.261945e-01]) def test_jpd_marginal_distribution_list(self): self.jpd.marginal_distribution(['x1', 'x2']) np_test.assert_array_almost_equal(self.jpd.values, np.array([[0.16666667, 0.16666667, 0.16666667], [0.16666667, 0.16666667, 0.16666667]])) np_test.assert_array_equal(self.jpd.cardinality, np.array([2, 3])) dic = {'x1': 2, 'x2': 3} self.assertEqual(self.jpd.get_cardinality(['x1', 'x2']), dic) self.assertEqual(self.jpd.scope(), ['x1', 'x2']) np_test.assert_almost_equal(np.sum(self.jpd.values), 1) new_jpd = self.jpd1.marginal_distribution(['x1', 'x2'], inplace=False) self.assertTrue(self.jpd1 != self.jpd) self.assertTrue(new_jpd == self.jpd) def test_marginal_distribution_str(self): self.jpd.marginal_distribution('x1') np_test.assert_array_almost_equal(self.jpd.values, np.array([0.5, 0.5])) np_test.assert_array_equal(self.jpd.cardinality, np.array([2])) self.assertEqual(self.jpd.scope(), ['x1']) np_test.assert_almost_equal(np.sum(self.jpd.values), 1) new_jpd = self.jpd1.marginal_distribution('x1', inplace=False) self.assertTrue(self.jpd1 != self.jpd) self.assertTrue(self.jpd == new_jpd) def test_conditional_distribution_list(self): self.jpd = self.jpd1.copy() self.jpd.conditional_distribution([('x1', 1), ('x2', 0)]) np_test.assert_array_almost_equal(self.jpd.values, np.array([0.5, 0.5])) np_test.assert_array_equal(self.jpd.cardinality, np.array([2])) self.assertEqual(self.jpd.scope(), ['x3']) np_test.assert_almost_equal(np.sum(self.jpd.values), 1) new_jpd = self.jpd1.conditional_distribution([('x1', 1), ('x2', 0)], inplace=False) self.assertTrue(self.jpd1 != self.jpd) self.assertTrue(self.jpd == new_jpd) def test_check_independence(self): self.assertTrue(self.jpd2.check_independence(['x1'], ['x2'])) self.assertRaises(TypeError, self.jpd2.check_independence, 'x1', ['x2']) self.assertRaises(TypeError, self.jpd2.check_independence, ['x1'], 'x2') self.assertRaises(TypeError, self.jpd2.check_independence, ['x1'], ['x2'], 'x3') self.assertFalse(self.jpd2.check_independence(['x1'], ['x2'], ('x3',), condition_random_variable=True)) self.assertFalse(self.jpd2.check_independence(['x1'], ['x2'], [('x3', 0)])) self.assertTrue(self.jpd1.check_independence(['x1'], ['x2'], ('x3',), condition_random_variable=True)) self.assertTrue(self.jpd1.check_independence(['x1'], ['x2'], [('x3', 1)])) self.assertTrue(self.jpd3.check_independence(['x1'], ['x2'], ('x3',), condition_random_variable=True)) def test_get_independencies(self): independencies = Independencies(['x1', 'x2'], ['x2', 'x3'], ['x3', 'x1']) independencies1 = Independencies(['x1', 'x2']) self.assertEqual(self.jpd1.get_independencies(), independencies) self.assertEqual(self.jpd2.get_independencies(), independencies1) self.assertEqual(self.jpd1.get_independencies([('x3', 0)]), independencies1) self.assertEqual(self.jpd2.get_independencies([('x3', 0)]), Independencies()) def test_minimal_imap(self): bm = self.jpd1.minimal_imap(order=['x1', 'x2', 'x3']) self.assertEqual(sorted(bm.edges()), sorted([('x1', 'x3'), ('x2', 'x3')])) bm = self.jpd1.minimal_imap(order=['x2', 'x3', 'x1']) self.assertEqual(sorted(bm.edges()), sorted([('x2', 'x1'), ('x3', 'x1')])) bm = self.jpd2.minimal_imap(order=['x1', 'x2', 'x3']) self.assertEqual(list(bm.edges()), []) bm = self.jpd2.minimal_imap(order=['x1', 'x2']) self.assertEqual(list(bm.edges()), []) def test_repr(self): self.assertEqual(repr(self.jpd1), '<Joint Distribution representing P(x1:2, x2:3, x3:2) at {address}>'.format( address=hex(id(self.jpd1)))) def test_is_imap(self): G1 = BayesianModel([('diff', 'grade'), ('intel', 'grade')]) diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]]) intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]]) grade_cpd = TabularCPD('grade', 3, [[0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8, 0.8, 0.8]], evidence=['diff', 'intel'], evidence_card=[2, 3]) G1.add_cpds(diff_cpd, intel_cpd, grade_cpd) val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032, 0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128] jpd = JPD(['diff', 'intel', 'grade'], [2, 3, 3], val) self.assertTrue(jpd.is_imap(G1)) self.assertRaises(TypeError, jpd.is_imap, MarkovModel()) def tearDown(self): del self.jpd del self.jpd1 del self.jpd2 del self.jpd3 # # class TestTreeCPDInit(unittest.TestCase): # def test_init_single_variable_nodes(self): # tree = TreeCPD([('B', DiscreteFactor(['A'], [2], [0.8, 0.2]), 0), # ('B', 'C', 1), # ('C', DiscreteFactor(['A'], [2], [0.1, 0.9]), 0), # ('C', 'D', 1), # ('D', DiscreteFactor(['A'], [2], [0.9, 0.1]), 0), # ('D', DiscreteFactor(['A'], [2], [0.4, 0.6]), 1)]) # # self.assertTrue('B' in tree.nodes()) # self.assertTrue('C' in tree.nodes()) # self.assertTrue('D' in tree.nodes()) # self.assertTrue(DiscreteFactor(['A'], [2], [0.8, 0.2]) in tree.nodes()) # self.assertTrue(DiscreteFactor(['A'], [2], [0.1, 0.9]) in tree.nodes()) # self.assertTrue(DiscreteFactor(['A'], [2], [0.9, 0.1]) in tree.nodes()) # self.assertTrue(DiscreteFactor(['A'], [2], [0.4, 0.6]) in tree.nodes()) # # self.assertTrue(('B', DiscreteFactor(['A'], [2], [0.8, 0.2]) in tree.edges())) # self.assertTrue(('B', DiscreteFactor(['A'], [2], [0.1, 0.9]) in tree.edges())) # self.assertTrue(('B', DiscreteFactor(['A'], [2], [0.9, 0.1]) in tree.edges())) # self.assertTrue(('B', DiscreteFactor(['A'], [2], [0.4, 0.6]) in tree.edges())) # self.assertTrue(('C', 'D') in tree.edges()) # self.assertTrue(('B', 'C') in tree.edges()) # # self.assertEqual(tree['B'][DiscreteFactor(['A'], [2], [0.8, 0.2])]['label'], 0) # self.assertEqual(tree['B']['C']['label'], 1) # self.assertEqual(tree['C'][DiscreteFactor(['A'], [2], [0.1, 0.9])]['label'], 0) # self.assertEqual(tree['C']['D']['label'], 1) # self.assertEqual(tree['D'][DiscreteFactor(['A'], [2], [0.9, 0.1])]['label'], 0) # self.assertEqual(tree['D'][DiscreteFactor(['A'], [2], [0.4, 0.6])]['label'], 1) # # self.assertRaises(ValueError, tree.add_edges_from, [('F', 'G')]) # # def test_init_self_loop(self): # self.assertRaises(ValueError, TreeCPD, [('B', 'B', 0)]) # # def test_init_cycle(self): # self.assertRaises(ValueError, TreeCPD, [('A', 'B', 0), ('B', 'C', 1), ('C', 'A', 0)]) # # def test_init_multi_variable_nodes(self): # tree = TreeCPD([(('B', 'C'), DiscreteFactor(['A'], [2], [0.8, 0.2]), (0, 0)), # (('B', 'C'), 'D', (0, 1)), # (('B', 'C'), DiscreteFactor(['A'], [2], [0.1, 0.9]), (1, 0)), # (('B', 'C'), 'E', (1, 1)), # ('D', DiscreteFactor(['A'], [2], [0.9, 0.1]), 0), # ('D', DiscreteFactor(['A'], [2], [0.4, 0.6]), 1), # ('E', DiscreteFactor(['A'], [2], [0.3, 0.7]), 0), # ('E', DiscreteFactor(['A'], [2], [0.8, 0.2]), 1) # ]) # # self.assertTrue(('B', 'C') in tree.nodes()) # self.assertTrue('D' in tree.nodes()) # self.assertTrue('E' in tree.nodes()) # self.assertTrue(DiscreteFactor(['A'], [2], [0.8, 0.2]) in tree.nodes()) # self.assertTrue(DiscreteFactor(['A'], [2], [0.9, 0.1]) in tree.nodes()) # # self.assertTrue((('B', 'C'), DiscreteFactor(['A'], [2], [0.8, 0.2]) in tree.edges())) # self.assertTrue((('B', 'C'), 'E') in tree.edges()) # self.assertTrue(('D', DiscreteFactor(['A'], [2], [0.4, 0.6])) in tree.edges()) # self.assertTrue(('E', DiscreteFactor(['A'], [2], [0.8, 0.2])) in tree.edges()) # # self.assertEqual(tree[('B', 'C')][DiscreteFactor(['A'], [2], [0.8, 0.2])]['label'], (0, 0)) # self.assertEqual(tree[('B', 'C')]['D']['label'], (0, 1)) # self.assertEqual(tree['D'][DiscreteFactor(['A'], [2], [0.9, 0.1])]['label'], 0) # self.assertEqual(tree['E'][DiscreteFactor(['A'], [2], [0.3, 0.7])]['label'], 0) # # # class TestTreeCPD(unittest.TestCase): # def setUp(self): # self.tree1 = TreeCPD([('B', DiscreteFactor(['A'], [2], [0.8, 0.2]), '0'), # ('B', 'C', '1'), # ('C', DiscreteFactor(['A'], [2], [0.1, 0.9]), '0'), # ('C', 'D', '1'), # ('D', DiscreteFactor(['A'], [2], [0.9, 0.1]), '0'), # ('D', DiscreteFactor(['A'], [2], [0.4, 0.6]), '1')]) # # self.tree2 = TreeCPD([('C','A','0'),('C','B','1'), # ('A', DiscreteFactor(['J'], [2], [0.9, 0.1]), '0'), # ('A', DiscreteFactor(['J'], [2], [0.3, 0.7]), '1'), # ('B', DiscreteFactor(['J'], [2], [0.8, 0.2]), '0'), # ('B', DiscreteFactor(['J'], [2], [0.4, 0.6]), '1')]) # # def test_add_edge(self): # self.tree1.add_edge('yolo', 'yo', 0) # self.assertTrue('yolo' in self.tree1.nodes() and 'yo' in self.tree1.nodes()) # self.assertTrue(('yolo', 'yo') in self.tree1.edges()) # self.assertEqual(self.tree1['yolo']['yo']['label'], 0) # # def test_add_edges_from(self): # self.tree1.add_edges_from([('yolo', 'yo', 0), ('hello', 'world', 1)]) # self.assertTrue('yolo' in self.tree1.nodes() and 'yo' in self.tree1.nodes() and # 'hello' in self.tree1.nodes() and 'world' in self.tree1.nodes()) # self.assertTrue(('yolo', 'yo') in self.tree1.edges()) # self.assertTrue(('hello', 'world') in self.tree1.edges()) # self.assertEqual(self.tree1['yolo']['yo']['label'], 0) # self.assertEqual(self.tree1['hello']['world']['label'], 1) # # def test_to_tabular_cpd(self): # tabular_cpd = self.tree1.to_tabular_cpd() # self.assertEqual(tabular_cpd.evidence, ['D', 'C', 'B']) # self.assertEqual(tabular_cpd.evidence_card, [2, 2, 2]) # self.assertEqual(list(tabular_cpd.variables), ['A', 'B', 'C', 'D']) # np_test.assert_array_equal(tabular_cpd.values, # np.array([0.8, 0.8, 0.8, 0.8, 0.1, 0.1, 0.9, 0.4, # 0.2, 0.2, 0.2, 0.2, 0.9, 0.9, 0.1, 0.6])) # # tabular_cpd = self.tree2.to_tabular_cpd() # self.assertEqual(tabular_cpd.evidence, ['A', 'B', 'C']) # self.assertEqual(tabular_cpd.evidence_card, [2, 2, 2]) # self.assertEqual(list(tabular_cpd.variables), ['J', 'C', 'B', 'A']) # np_test.assert_array_equal(tabular_cpd.values, # np.array([ 0.9, 0.3, 0.9, 0.3, 0.8, 0.8, 0.4, 0.4, # 0.1, 0.7, 0.1, 0.7, 0.2, 0.2, 0.6, 0.6])) # # @unittest.skip('Not implemented yet') # def test_to_tabular_cpd_parent_order(self): # tabular_cpd = self.tree1.to_tabular_cpd('A', parents_order=['D', 'C', 'B']) # self.assertEqual(tabular_cpd.evidence, ['D', 'C', 'B']) # self.assertEqual(tabular_cpd.evidence_card, [2, 2, 2]) # self.assertEqual(list(tabular_cpd.variables), ['A', 'D', 'C', 'B']) # np_test.assert_array_equal(tabular_cpd.values, # np.array([0.8, 0.1, 0.8, 0.9, 0.8, 0.1, 0.8, 0.4, # 0.2, 0.9, 0.2, 0.1, 0.2, 0.9, 0.2, 0.6])) # # tabular_cpd = self.tree2.to_tabular_cpd('A', parents_order=['E', 'D', 'C', 'B']) # # @unittest.skip('Not implemented yet') # def test_to_rule_cpd(self): # rule_cpd = self.tree1.to_rule_cpd() # self.assertEqual(rule_cpd.cardinality(), {'A': 2, 'B': 2, 'C': 2, 'D': 2}) # self.assertEqual(rule_cpd.scope(), {'A', 'B', 'C', 'D'}) # self.assertEqual(rule_cpd.variable, 'A') # self.assertEqual(rule_cpd.rules, {('A_0', 'B_0'): 0.8, # ('A_1', 'B_0'): 0.2, # ('A_0', 'B_1', 'C_0'): 0.1, # ('A_0', 'B_1', 'C_1', 'D_0'): 0.9, # ('A_1', 'B_1', 'C_1', 'D_0'): 0.1, # ('A_0', 'B_1', 'C_1', 'D_1'): 0.4, # ('A_1', 'B_!', 'C_1', 'D_1'): 0.6}) # # rule_cpd = self.tree2.to_rule_cpd() # self.assertEqual(rule_cpd.cardinality(), {'A': 2, 'B': 2, 'C': 2, 'D': 2, 'E': 2}) # self.assertEqual(rule_cpd.scope(), {'A', 'B', 'C', 'D', 'E'}) # self.assertEqual(rule_cpd.variable, 'A') # self.assertEqual(rule_cpd.rules, {('A_0', 'B_0', 'C_0'): 0.8, # ('A_1', 'B_0', 'C_0'): 0.2, # ('A_0', 'B_0', 'C_1', 'D_0'): 0.9, # ('A_1', 'B_0', 'C_1', 'D_0'): 0.1, # ('A_0', 'B_0', 'C_1', 'D_1'): 0.4, # ('A_1', 'B_0', 'C_1', 'D_1'): 0.6, # ('A_0', 'B_1', 'C_0'): 0.1, # ('A_1', 'B_1', 'C_0'): 0.9, # ('A_0', 'B_1', 'C_1', 'E_0'): 0.3, # ('A_1', 'B_1', 'C_1', 'E_0'): 0.7, # ('A_0', 'B_1', 'C_1', 'E_1'): 0.8, # ('A_1', 'B_1', 'C_1', 'E_1'): 0.2}) # # # class TestRuleCPDInit(unittest.TestCase): # def test_init_without_errors_rules_none(self): # rule_cpd = RuleCPD('A') # self.assertEqual(rule_cpd.variable, 'A') # # def test_init_without_errors_rules_not_none(self): # rule_cpd = RuleCPD('A', {('A_0', 'B_0'): 0.8, # ('A_1', 'B_0'): 0.2, # ('A_0', 'B_1', 'C_0'): 0.4, # ('A_1', 'B_1', 'C_0'): 0.6, # ('A_0', 'B_1', 'C_1'): 0.9, # ('A_1', 'B_1', 'C_1'): 0.1}) # self.assertEqual(rule_cpd.variable, 'A') # self.assertEqual(rule_cpd.rules, {('A_0', 'B_0'): 0.8, # ('A_1', 'B_0'): 0.2, # ('A_0', 'B_1', 'C_0'): 0.4, # ('A_1', 'B_1', 'C_0'): 0.6, # ('A_0', 'B_1', 'C_1'): 0.9, # ('A_1', 'B_1', 'C_1'): 0.1}) # # def test_init_with_errors(self): # self.assertRaises(ValueError, RuleCPD, 'A', {('A_0',): 0.5, # ('A_0', 'B_0'): 0.8, # ('A_1', 'B_0'): 0.2, # ('A_0', 'B_1', 'C_0'): 0.4, # ('A_1', 'B_1', 'C_0'): 0.6, # ('A_0', 'B_1', 'C_1'): 0.9, # ('A_1', 'B_1', 'C_1'): 0.1}) # # # class TestRuleCPDMethods(unittest.TestCase): # def setUp(self): # self.rule_cpd_with_rules = RuleCPD('A', {('A_0', 'B_0'): 0.8, # ('A_1', 'B_0'): 0.2, # ('A_0', 'B_1', 'C_0'): 0.4, # ('A_1', 'B_1', 'C_0'): 0.6}) # self.rule_cpd_without_rules = RuleCPD('A') # # def test_add_rules_single(self): # self.rule_cpd_with_rules.add_rules({('A_0', 'B_1', 'C_1'): 0.9}) # self.assertEqual(self.rule_cpd_with_rules.rules, {('A_0', 'B_0'): 0.8, # ('A_1', 'B_0'): 0.2, # ('A_0', 'B_1', 'C_0'): 0.4, # ('A_1', 'B_1', 'C_0'): 0.6, # ('A_0', 'B_1', 'C_1'): 0.9}) # self.assertEqual(self.rule_cpd_with_rules.variable, 'A') # self.rule_cpd_without_rules.add_rules({('A_0', 'B_1', 'C_1'): 0.9}) # self.assertEqual(self.rule_cpd_without_rules.rules, {('A_0', 'B_1', 'C_1'): 0.9}) # self.assertEqual(self.rule_cpd_without_rules.variable, 'A') # # def test_add_rules_multiple(self): # self.rule_cpd_with_rules.add_rules({('A_0', 'B_1', 'C_1'): 0.9, # ('A_1', 'B_1', 'C_1'): 0.1}) # self.assertEqual(self.rule_cpd_with_rules.rules, {('A_0', 'B_0'): 0.8, # ('A_1', 'B_0'): 0.2, # ('A_0', 'B_1', 'C_0'): 0.4, # ('A_1', 'B_1', 'C_0'): 0.6, # ('A_0', 'B_1', 'C_1'): 0.9, # ('A_1', 'B_1', 'C_1'): 0.1}) # self.assertEqual(self.rule_cpd_with_rules.variable, 'A') # self.rule_cpd_without_rules.add_rules({('A_0', 'B_1', 'C_1'): 0.9, # ('A_1', 'B_1', 'C_1'): 0.1}) # self.assertEqual(self.rule_cpd_without_rules.rules, {('A_0', 'B_1', 'C_1'): 0.9, # ('A_1', 'B_1', 'C_1'): 0.1}) # self.assertEqual(self.rule_cpd_without_rules.variable, 'A') # # def test_add_rules_error(self): # self.assertRaises(ValueError, self.rule_cpd_with_rules.add_rules, {('A_0',): 0.8}) # # def test_scope(self): # self.assertEqual(self.rule_cpd_with_rules.scope(), {'A', 'B', 'C'}) # self.assertEqual(self.rule_cpd_without_rules.scope(), set()) # # def test_cardinality(self): # self.assertEqual(self.rule_cpd_with_rules.cardinality(), {'A': 2, 'B': 2, 'C': 1}) # self.assertEqual(self.rule_cpd_without_rules.cardinality(), {}) # # def tearDown(self): # del self.rule_cpd_without_rules #<|fim▁end|>
self.assertRaises(TypeError, factor_product, 1, 2)
<|file_name|>genoa.py<|end_file_name|><|fim▁begin|><|fim▁hole|> sys.exit(0)<|fim▁end|>
import sys if __name__ == "__main__": print("Genoa python script")
<|file_name|>arv-enum-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Aravis - Digital camera library # # Copyright (c) 2011-2012 Emmanuel Pacaud # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General # Public License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, # Boston, MA 02111-1307, USA. # # Author: Emmanuel Pacaud <[email protected]><|fim▁hole|># If you have installed aravis in a non standard location, you may need # to make GI_TYPELIB_PATH point to the correct location. For example: # # export GI_TYPELIB_PATH=$GI_TYPELIB_PATH:/opt/bin/lib/girepositry-1.0/ # # You may also have to give the path to libaravis.so, using LD_PRELOAD or # LD_LIBRARY_PATH. import gi gi.require_version ('Aravis', '0.2') from gi.repository import Aravis print Aravis.Auto print Aravis.Auto.OFF print Aravis.BufferStatus print Aravis.DebugLevel print Aravis.DomNodeType print Aravis.GvStreamPacketResend print Aravis.GvspPacketType print Aravis.PixelFormat print Aravis.PixelFormat.MONO_8<|fim▁end|>
<|file_name|>ExamplePartialBeanImplementation.java<|end_file_name|><|fim▁begin|>/* * JBoss, Home of Professional Open Source * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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. */ package org.jboss.as.quickstart.deltaspike.partialbean; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import javax.enterprise.context.ApplicationScoped; /** * This class implements a dynamic DeltaSpike Partial Bean. It is bound to * one or more abstract classes or interfaces via the Binding Annotation * (@ExamplePartialBeanBinding below).<|fim▁hole|> * * All abstract, unimplemented methods from those beans will be implemented * via the invoke method. * */ @ExamplePartialBeanBinding @ApplicationScoped public class ExamplePartialBeanImplementation implements InvocationHandler { /** * In our example, this method will be invoked when the "sayHello" method is called. * * @param proxy The object upon which the method is being invoked. * @param method The method being invoked (sayHello in this QuickStart) * @param args The arguments being passed in to the invoked method */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return "Hello " + args[0]; } }<|fim▁end|>
<|file_name|>0004_auto__add_field_application_content_type__add_field_application_object.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Application.content_type' db.add_column('applications_application', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False) # Adding field 'Application.object_id' db.add_column('applications_application', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Deleting field 'UserApplication.object_id' db.delete_column('applications_userapplication', 'object_id') # Deleting field 'UserApplication.content_type' db.delete_column('applications_userapplication', 'content_type_id') def backwards(self, orm): # Deleting field 'Application.content_type' db.delete_column('applications_application', 'content_type_id') # Deleting field 'Application.object_id' db.delete_column('applications_application', 'object_id') # Adding field 'UserApplication.object_id' db.add_column('applications_userapplication', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Adding field 'UserApplication.content_type' db.add_column('applications_userapplication', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False) models = { 'applications.applicant': { 'Meta': {'object_name': 'Applicant'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),<|fim▁hole|> 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']", 'null': 'True', 'blank': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}), 'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '16', 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, 'applications.application': { 'Meta': {'object_name': 'Application'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}), 'content_type_temp': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'app_temp_obj'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Person']", 'null': 'True', 'blank': 'True'}), 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateTimeField', [], {}), 'header_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'object_id_temp': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'secret_token': ('django.db.models.fields.CharField', [], {'default': "'f0369b28f1adc73f2c0c351ed377febb0fa872d4'", 'unique': 'True', 'max_length': '64'}), 'state': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}), 'submitted_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'applications.projectapplication': { 'Meta': {'object_name': 'ProjectApplication', '_ormbases': ['applications.Application']}, 'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['applications.Application']", 'unique': 'True', 'primary_key': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['machines.MachineCategory']", 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'user_applications': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['applications.UserApplication']", 'null': 'True', 'blank': 'True'}) }, 'applications.userapplication': { 'Meta': {'object_name': 'UserApplication', '_ormbases': ['applications.Application']}, 'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['applications.Application']", 'unique': 'True', 'primary_key': 'True'}), 'make_leader': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'needs_account': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']", 'null': 'True', 'blank': 'True'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'machines.machinecategory': { 'Meta': {'object_name': 'MachineCategory', 'db_table': "'machine_category'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'people.institute': { 'Meta': {'object_name': 'Institute', 'db_table': "'institute'"}, 'active_delegate': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'active_delegate'", 'null': 'True', 'to': "orm['people.Person']"}), 'delegate': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'delegate'", 'null': 'True', 'to': "orm['people.Person']"}), 'gid': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'sub_delegates': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'sub_delegates'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['people.Person']"}) }, 'people.person': { 'Meta': {'object_name': 'Person', 'db_table': "'person'"}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_approver'", 'null': 'True', 'to': "orm['people.Person']"}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_deletor'", 'null': 'True', 'to': "orm['people.Person']"}), 'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}), 'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'projects.project': { 'Meta': {'object_name': 'Project', 'db_table': "'project'"}, 'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_approver'", 'null': 'True', 'to': "orm['people.Person']"}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_deletor'", 'null': 'True', 'to': "orm['people.Person']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_expertise': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'leaders': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'leaders'", 'symmetrical': 'False', 'to': "orm['people.Person']"}), 'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'projects'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['machines.MachineCategory']"}), 'machine_category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.MachineCategory']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'pid': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['people.Person']", 'null': 'True', 'blank': 'True'}) } } complete_apps = ['applications']<|fim▁end|>
'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
<|file_name|>gazelleSchema.js<|end_file_name|><|fim▁begin|>/* global GazelleSchema :true */ // obj2 is merged into obj1, replacing duplicate keys. function merge (obj2, obj1) { for (var k in obj2) { try { if (obj2[k].constructor === Object) { obj1[k] = merge(obj1[k], obj2[k]); } else { obj1[k] = obj2[k]; } } catch (e) { obj1[k] = obj2[k]; } } return obj1; } var formatLabel = function (identifier, label) { return 'The ' + (identifier ? identifier + '\'s ' : ' ') + label; }; GazelleSchema = function (identifier) { this.identifier = identifier; }; GazelleSchema.prototype.formatLabel = function (label) { return formatLabel(this.identifier, label); }; GazelleSchema.prototype.id = function (extra) { return merge(extra, { type: String, label: this.formatLabel('id'), index: true, unique: true, autoValue: function () { if (this.isInsert) { return Random.id(); } else { this.unset(); } } }); }; GazelleSchema.prototype.foreignId = function (identifier, extra) { return merge(extra, { type: String, label: formatLabel(identifier, 'id'), index: true, unique: false, optional: false }); }; GazelleSchema.prototype.title = function (extra) { return merge(extra, { type: String, label: this.formatLabel('title'), index: true }); }; GazelleSchema.prototype.name = function (extra) { return merge(extra, this.title({ label: this.formatLabel('name') })); }; GazelleSchema.prototype.createdAt = function (extra) { return merge(extra, { type: Date, label: this.formatLabel('created at timestamp'), autoValue: function () { if (this.isInsert) { return new Date; } else if (this.isUpsert) { return { $setOnInsert: new Date }; } else { this.unset(); } } }); }; GazelleSchema.prototype.updatedAt = function (extra) { return merge(extra, { type: Date, label: this.formatLabel('updated at timestamp'), autoValue: function () { if (this.isUpdate) { return new Date(); } }, denyInsert: true, optional: true }); }; GazelleSchema.prototype.createdBy = function (extra) { return merge(extra, {<|fim▁hole|> autoValue: function () { if (this.isInsert) { return this.userId; } else if (this.isUpsert) { return { $setOnInsert: this.userId }; } else { this.unset(); } } }); }; GazelleSchema.prototype.images = function (extra) { return merge(extra, { type: [new SimpleSchema({ title: this.images({ index: false }), url: { type: String, label: 'The url of the image' }, createdAt: this.createdAt('image'), createdBy: this.createdBy('image') })], label: 'The images', optional: true }); }; GazelleSchema.prototype.description = function (extra) { return merge(extra, { type: String, label: this.formatLabel('description'), optional: true }); }; GazelleSchema.prototype.body = function (extra) { return merge(extra, this.description({ label: this.formatLabel('body') })); }; GazelleSchema.prototype.tags = function (extra) { return merge(extra, { type: [new SimpleSchema({ id: this.id('tag'), createdAt: this.createdAt('tag'), createdBy: this.createdBy('tag') })], label: this.formatLabel('tag'), optional: true }); }; GazelleSchema.prototype.leechType = function (extra) { return merge(extra, { type: String, label: this.formatLabel('leech type'), defaultValue: function () { return 'Regular'; }, allowedValues: ['Regular', 'Free Leech', 'Neutral Leech'] }); }; GazelleSchema.year = function (extra) { return { type: Number, label: 'The ' + (entity ? entity + '\s ' : ' ') + 'year', optional: false }; };<|fim▁end|>
type: String, label: this.formatLabel('created by user id'),
<|file_name|>client_manager.cc<|end_file_name|><|fim▁begin|>#include "client_manager.hh" #include "buffer_manager.hh" #include "command_manager.hh" #include "containers.hh" #include "event_manager.hh" #include "face_registry.hh" #include "file.hh" #include "user_interface.hh" #include "window.hh" namespace Kakoune { ClientManager::ClientManager() = default; ClientManager::~ClientManager() = default; String ClientManager::generate_name() const { for (int i = 0; true; ++i) { String name = format("unnamed{}", i); if (validate_client_name(name)) return name; } } Client* ClientManager::create_client(std::unique_ptr<UserInterface>&& ui, EnvVarMap env_vars, StringView init_commands) { Buffer& buffer = **BufferManager::instance().begin();<|fim▁hole|> generate_name()}; m_clients.emplace_back(client); try { CommandManager::instance().execute(init_commands, client->context()); } catch (Kakoune::runtime_error& error) { client->context().print_status({ error.what().str(), get_face("Error") }); client->context().hooks().run_hook("RuntimeError", error.what(), client->context()); } catch (Kakoune::client_removed&) { m_clients.pop_back(); return nullptr; } client->ui().set_input_callback([client](EventMode mode) { client->handle_available_input(mode); }); return client; } void ClientManager::handle_pending_inputs() const { for (auto& client : m_clients) client->handle_available_input(EventMode::Pending); } void ClientManager::remove_client(Client& client) { for (auto it = m_clients.begin(); it != m_clients.end(); ++it) { if (it->get() == &client) { m_clients.erase(it); return; } } kak_assert(false); } WindowAndSelections ClientManager::get_free_window(Buffer& buffer) { auto it = find_if(reversed(m_free_windows), [&](const WindowAndSelections& ws) { return &ws.window->buffer() == &buffer; }); if (it == m_free_windows.rend()) return { make_unique<Window>(buffer), { buffer, Selection{} } }; it->window->force_redraw(); WindowAndSelections res = std::move(*it); m_free_windows.erase(it.base()-1); res.selections.update(); return res; } void ClientManager::add_free_window(std::unique_ptr<Window>&& window, SelectionList selections) { window->clear_display_buffer(); Buffer& buffer = window->buffer(); m_free_windows.push_back({ std::move(window), SelectionList{ std::move(selections) }, buffer.timestamp() }); } void ClientManager::ensure_no_client_uses_buffer(Buffer& buffer) { for (auto& client : m_clients) { client->context().forget_jumps_to_buffer(buffer); if (&client->context().buffer() != &buffer) continue; if (client->context().is_editing()) throw runtime_error(format("client '{}' is inserting in buffer '{}'", client->context().name(), buffer.display_name())); // change client context to edit the first buffer which is not the // specified one. As BufferManager stores buffer according to last // access, this selects a sensible buffer to display. for (auto& buf : BufferManager::instance()) { if (buf.get() != &buffer) { client->context().change_buffer(*buf); break; } } } auto end = std::remove_if(m_free_windows.begin(), m_free_windows.end(), [&buffer](const WindowAndSelections& ws) { return &ws.window->buffer() == &buffer; }); m_free_windows.erase(end, m_free_windows.end()); } bool ClientManager::validate_client_name(StringView name) const { return const_cast<ClientManager*>(this)->get_client_ifp(name) == nullptr; } Client* ClientManager::get_client_ifp(StringView name) { for (auto& client : m_clients) { if (client->context().name() == name) return client.get(); } return nullptr; } Client& ClientManager::get_client(StringView name) { if (Client* client = get_client_ifp(name)) return *client; throw runtime_error(format("no client named '{}'", name)); } void ClientManager::redraw_clients() const { for (auto& client : m_clients) client->redraw_ifn(); } CandidateList ClientManager::complete_client_name(StringView prefix, ByteCount cursor_pos) const { auto c = transformed(m_clients, [](const std::unique_ptr<Client>& c){ return c->context().name(); }); return complete(prefix, cursor_pos, c, prefix_match, subsequence_match); } }<|fim▁end|>
WindowAndSelections ws = get_free_window(buffer); Client* client = new Client{std::move(ui), std::move(ws.window), std::move(ws.selections), std::move(env_vars),
<|file_name|>uiProgressBar.cpp<|end_file_name|><|fim▁begin|>/*** * Inferno Engine v4 2015-2017 * Written by Tomasz "Rex Dex" Jonarski * * [# filter: elements\controls\simple #] ***/ #include "build.h" #include "uiProgressBar.h" #include "ui/toolkit/include/uiStaticContent.h" namespace ui { //--- // active area element, does nothing but is class ProgressBarArea : public IElement { RTTI_DECLARE_VIRTUAL_CLASS(ProgressBarArea, IElement); public: ProgressBarArea() {} };<|fim▁hole|> //-- RTTI_BEGIN_TYPE_NOCOPY_CLASS(ProgressBar); RTTI_METADATA(ElementClassName).setName("ProgressBar"); RTTI_END_TYPE(); ProgressBar::ProgressBar() : m_pos(0.5f) { setLayoutMode(LayoutMode::Vertical); m_bar = base::CreateSharedPtr<ProgressBarArea>(); m_bar->setIgnoredInAutomaticLayout(true); attachChild(m_bar); } void ProgressBar::setPosition(const Float pos) { const auto clampedPos = std::clamp<Float>(pos, 0.0f, 1.0f); if (m_pos != clampedPos) { m_pos = clampedPos; if (m_bar) m_bar->setCustomProportion(m_pos); if (m_text) m_text->setText(base::TempString("{}%", pos * 100.0f)); invalidateLayout(); } } Bool ProgressBar::handleTemplateProperty(const base::StringView<AnsiChar>& name, const base::StringView<AnsiChar>& value) { if (name == "showPercents" || name == "text" || name == "showPercent") { Bool flag = false; if (base::MatchResult::OK != value.match(flag)) return false; if (flag && !m_text) { m_text = base::CreateSharedPtr<StaticContent>(); m_text->setName("ProgressCaption"); m_text->setText(base::TempString("{}%", m_pos * 100.0f)); attachChild(m_text); } return true; } else if (name == "value") { Float pos = 0.0f; if (base::MatchResult::OK != value.match(pos)) return false; setPosition(pos); return true; } return TBaseClass::handleTemplateProperty(name, value); } void ProgressBar::arrangeChildren(const ElementArea& innerArea, const ElementArea& clipArea, ArrangedChildren& outArrangedChildren, const ElementDynamicSizing* dynamicSizing) const { if (m_pos > 0.0f) { const auto pos = innerArea.getLeft() + (Float)(innerArea.getSize().x * m_pos); const auto area = ElementArea(innerArea.getLeft(), innerArea.getTop(), pos, innerArea.getBottom()); outArrangedChildren.add(m_bar, area, clipArea); } return TBaseClass::arrangeChildren(innerArea, clipArea, outArrangedChildren, dynamicSizing); } //--- } // ui<|fim▁end|>
RTTI_BEGIN_TYPE_NOCOPY_CLASS(ProgressBarArea); RTTI_METADATA(ElementClassName).setName("ProgressBarArea"); RTTI_END_TYPE();
<|file_name|>grid_x_y_viewbox.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # vispy: gallery 2 # ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """ +----+-------------+ | | | | y | viewbox | | | | +----+-------------+ | sp | x | +----+-------------+ """ import sys<|fim▁hole|> from vispy import scene, app canvas = scene.SceneCanvas(keys='interactive') canvas.size = 600, 600 canvas.show() grid = canvas.central_widget.add_grid() widget_y_axis = grid.add_widget(row=0, col=0) widget_y_axis.bgcolor = "#999999" widget_viewbox = grid.add_widget(row=0, col=1) widget_viewbox.bgcolor = "#dd0000" widget_spacer_bottom = grid.add_widget(row=1, col=0) widget_spacer_bottom.bgcolor = "#efefef" widget_x_axis = grid.add_widget(row=1, col=1) widget_x_axis.bgcolor = "#0000dd" widget_y_axis.width_min = 50 widget_y_axis.width_max = 50 widget_x_axis.height_min = 50 widget_x_axis.height_max = 50 if __name__ == '__main__' and sys.flags.interactive == 0: app.run()<|fim▁end|>
<|file_name|>actions.go<|end_file_name|><|fim▁begin|>package files import ( "bytes" "io" "io/ioutil" "strings" "github.com/golang/protobuf/proto" "github.com/octavore/nagax/util/errors" uuid "github.com/satori/go.uuid" "github.com/willnorris/imageproxy" "github.com/ketchuphq/ketchup/proto/ketchup/models" ) func (m *Module) Upload(filename string, wr io.Reader) (*models.File, error) { // files are assigned a random id when stored to discourage manual renaming of files filename = strings.TrimPrefix(filename, "/") file, err := m.DB.GetFileByName(filename) if err != nil { return nil, errors.Wrap(err) } if file == nil || file.GetUuid() == "" { file = &models.File{ Uuid: proto.String(uuid.NewV4().String()), Name: proto.String(filename), } } err = m.store.Upload(file.GetUuid(), wr) if err != nil { return nil, errors.Wrap(err) } err = m.DB.UpdateFile(file) if err != nil { return nil, errors.Wrap(err) } return file, nil } // Get returns a reader, and nil, nil if file is not found func (m *Module) Get(filename string) (io.ReadCloser, error) { filename = strings.TrimPrefix(filename, "/") file, err := m.DB.GetFileByName(filename) if err != nil { return nil, errors.Wrap(err) } if file == nil { return nil, nil<|fim▁hole|> } return m.store.Get(file.GetUuid()) } // Get returns a reader, and nil, nil if file is not found func (m *Module) Delete(uuid string) error { file, err := m.DB.GetFile(uuid) if err != nil { return errors.Wrap(err) } if file == nil { return nil } err = m.DB.DeleteFile(file) if err != nil { return errors.Wrap(err) } return m.store.Delete(file.GetUuid()) } // GetWithTransform attempts to transform the image func (m *Module) GetWithTransform(filename string, optStr string) (io.ReadCloser, error) { filename = strings.TrimPrefix(filename, "/") r, err := m.Get(filename) if r == nil || err != nil || optStr == "" { return r, err } defer r.Close() data, err := ioutil.ReadAll(r) if err != nil { return nil, errors.Wrap(err) } opts := imageproxy.ParseOptions(optStr) output, err := imageproxy.Transform(data, opts) if err != nil { return nil, errors.Wrap(err) } return ioutil.NopCloser(bytes.NewBuffer(output)), nil }<|fim▁end|>
<|file_name|>user-profile.js<|end_file_name|><|fim▁begin|>import DS from 'ember-data'; export default DS.Model.extend({<|fim▁hole|> user: DS.belongsTo('user'), userUsername: DS.attr('string'), emailNotifications: DS.attr('boolean') });<|fim▁end|>
<|file_name|>FileScanner.cpp<|end_file_name|><|fim▁begin|>//*************************************************************************** // // Copyright (c) 1999 - 2006 Intel Corporation // // 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. // //*************************************************************************** /** @file FileScanner.cpp This module defines ... */ //*************************************************************************** // Defines //*************************************************************************** //*************************************************************************** // Includes //*************************************************************************** #include "FileScanner.h" #include "IFXException.h" #include "IFXMatrix4x4.h" #include "Color.h" #include "Quat.h" #include "Point.h" #include "Int3.h" #include "Int2.h" #include "MetaDataList.h" #include "Tokens.h" #include <ctype.h> #include <wchar.h> using namespace U3D_IDTF; //*************************************************************************** // Constants //*************************************************************************** //*************************************************************************** // Enumerations //*************************************************************************** //*************************************************************************** // Classes, structures and types //*************************************************************************** //*************************************************************************** // Global data //*************************************************************************** //*************************************************************************** // Local data //*************************************************************************** //*************************************************************************** // Local function prototypes //*************************************************************************** //*************************************************************************** // Public methods //*************************************************************************** FileScanner::FileScanner() { m_currentCharacter[0] = 0; m_currentCharacter[1] = 0; m_used = TRUE; } FileScanner::~FileScanner() { } IFXRESULT FileScanner::Initialize( const IFXCHAR* pFileName ) { IFXRESULT result = IFX_OK; result = m_file.Initialize( pFileName ); if( IFXSUCCESS( result ) ) m_currentCharacter[0] = m_file.ReadCharacter(); return result; } IFXRESULT FileScanner::Scan( IFXString* pToken, U32 scanLine ) { // try to use fscanf IFXRESULT result = IFX_OK; if( NULL != pToken ) { if( scanLine ) SkipBlanks(); else SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { U8 i = 0; U8 buffer[MAX_STRING_LENGTH] = {0}; while( 0 == IsSpace( GetCurrentCharacter() ) && !IsEndOfFile() ) { buffer[i++] = GetCurrentCharacter(); NextCharacter(); } result = pToken->Assign(buffer); } } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanString( IFXString* pString ) { IFXRESULT result = IFX_OK; if( NULL == pString ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) { SkipSpaces(); if( '"' == GetCurrentCharacter() ) { // found string, skip first quote NextCharacter(); U32 i = 0; U8 scanBuffer[MAX_STRING_LENGTH+2]; while( '"' != GetCurrentCharacter() && i < MAX_STRING_LENGTH ) { if( '\\' == GetCurrentCharacter()) { NextCharacter(); U8 currentCharacter = GetCurrentCharacter(); switch (currentCharacter) { case '\\': scanBuffer[i++] = '\\'; break; case 'n': scanBuffer[i++] = '\n'; break; case 't': scanBuffer[i++] = '\t'; break; case 'r': scanBuffer[i++] = '\r'; break; case '"': scanBuffer[i++] = '"'; break; default: scanBuffer[i++] = currentCharacter; } } else scanBuffer[i++] = GetCurrentCharacter(); NextCharacter(); } NextCharacter(); // skip last double quote scanBuffer[i] = 0; /// @todo: Converter Unicode support // convert one byte string to unicode pString->Assign( scanBuffer ); } else { result = IFX_E_STRING_NOT_FOUND; } } return result; } IFXRESULT FileScanner::ScanFloat( F32* pNumber ) { IFXRESULT result = IFX_OK; if( NULL == pNumber ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) { //this F32 format is preferred #ifdef F32_EXPONENTIAL IFXString buffer; U32 fpos; result = m_file.GetPosition( &fpos ); if( IFXSUCCESS( result ) ) result = Scan( &buffer, 1 ); if( IFXSUCCESS( result ) ) { I32 scanResult = swscanf( buffer.Raw(), L"%g", pNumber ); if( 0 == scanResult || EOF == scanResult ) { result = IFX_E_FLOAT_NOT_FOUND; // new token found, not float // do not allow client to continue scan for new tokens m_used = TRUE; m_currentToken = buffer; fpos--; m_file.SetPosition( fpos ); NextCharacter(); } } #else I32 sign = 1; U32 value = 0; SkipBlanks(); if( '-' == GetCurrentCharacter() ) { sign = -1; NextCharacter(); } if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() ) NextCharacter(); while( isdigit( GetCurrentCharacter() ) ) { value = ( value*10 ) + ( GetCurrentCharacter() - '0' ); NextCharacter(); } // there should be fraction part of float if( '.' == GetCurrentCharacter() ) { F32 fraction = 0.0f; F32 divisor = 10.0f; if( '.' == GetCurrentCharacter() ) NextCharacter(); while( isdigit( GetCurrentCharacter() ) ) { fraction += ( GetCurrentCharacter() - '0' ) / divisor; divisor *=10.0f; NextCharacter(); } *pNumber = static_cast<float>(value); *pNumber += fraction; *pNumber *= sign; } else { result = IFX_E_FLOAT_NOT_FOUND; } #endif } return result; } IFXRESULT FileScanner::ScanInteger( I32* pNumber ) { IFXRESULT result = IFX_OK; IFXString buffer; if( NULL == pNumber ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) { I32 sign = 1; I32 value = 0; SkipSpaces(); if( '-' == GetCurrentCharacter() ) { sign = -1; } if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() ) { NextCharacter(); } while( isdigit( GetCurrentCharacter() ) ) { value = (value*10) + (GetCurrentCharacter() - '0'); NextCharacter(); } *pNumber = value * sign; } return result; } IFXRESULT FileScanner::ScanHex( I32* pNumber ) { IFXRESULT result = IFX_OK; IFXString buffer; if( NULL == pNumber ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) result = Scan( &buffer ); if( IFXSUCCESS( result ) ) { buffer.ForceUppercase(); int scanResult = swscanf( buffer.Raw(), L"%X", pNumber ); if( 0 == scanResult || EOF == scanResult ) { result = IFX_E_INT_NOT_FOUND; } } return result; } IFXRESULT FileScanner::ScanTM( IFXMatrix4x4* pMatrix ) { IFXRESULT result = IFX_OK; F32 matrix[16]; U32 i; for( i = 0; i < 16 && IFXSUCCESS( result ); ++i ) { result = ScanFloat( &matrix[i] ); if( 0 == (i + 1)%4 ) { // skip end of line SkipSpaces(); } } if( IFXSUCCESS( result ) ) { *pMatrix = matrix; SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanColor( Color* pColor ) { IFXRESULT result = IFX_OK; F32 red = 0.0f, green = 0.0f, blue = 0.0f, alpha = 0.0f; result = ScanFloat( &red ); if( IFXSUCCESS( result ) ) result = ScanFloat( &green ); if( IFXSUCCESS( result ) ) result = ScanFloat( &blue ); if( IFXSUCCESS( result ) ) { result = ScanFloat( &alpha ); if( IFXSUCCESS( result ) ) { // 4 component color IFXVector4 color( red, green, blue, alpha ); pColor->SetColor( color ); } else if( IFX_E_FLOAT_NOT_FOUND == result ) { // 3 component color IFXVector4 color( red, green, blue ); pColor->SetColor( color ); result = IFX_OK; } SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanQuat( Quat* pQuat ) { IFXRESULT result = IFX_OK; F32 w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f; result = ScanFloat( &w ); if( IFXSUCCESS( result ) ) result = ScanFloat( &x ); if( IFXSUCCESS( result ) ) result = ScanFloat( &y ); if( IFXSUCCESS( result ) ) { result = ScanFloat( &z ); if( IFXSUCCESS( result ) ) { IFXVector4 quat( w, x, y, z ); pQuat->SetQuat( quat ); SkipSpaces(); } } return result; } IFXRESULT FileScanner::ScanPoint( Point* pPoint ) { IFXRESULT result = IFX_OK; F32 x = 0.0f, y = 0.0f, z = 0.0f; result = ScanFloat( &x ); if( IFXSUCCESS( result ) ) result = ScanFloat( &y ); if( IFXSUCCESS( result ) ) result = ScanFloat( &z ); if( IFXSUCCESS( result ) ) { IFXVector3 point( x, y, z ); pPoint->SetPoint( point ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanVector4( IFXVector4* pVector4 ) { IFXRESULT result = IFX_OK; F32 x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f; result = ScanFloat( &x ); if( IFXSUCCESS( result ) ) result = ScanFloat( &y ); if( IFXSUCCESS( result ) ) result = ScanFloat( &z ); if( IFXSUCCESS( result ) ) result = ScanFloat( &w ); if( IFXSUCCESS( result ) ) { pVector4->Set( x, y, z, w ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanInt3( Int3* pData ) { IFXRESULT result = IFX_OK; I32 x = 0, y = 0, z = 0; result = ScanInteger( &x ); if( IFXSUCCESS( result ) ) result = ScanInteger( &y ); if( IFXSUCCESS( result ) ) result = ScanInteger( &z ); if( IFXSUCCESS( result ) ) { pData->SetData( x, y, z ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanInt2( Int2* pData ) { IFXRESULT result = IFX_OK; I32 x = 0, y = 0; result = ScanInteger( &x ); if( IFXSUCCESS( result ) ) result = ScanInteger( &y ); if( IFXSUCCESS( result ) ) { pData->SetData( x, y ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanToken( const IFXCHAR* pToken ) { // try to use fscanf IFXRESULT result = IFX_OK; if( NULL != pToken ) { if( TRUE == m_used ) { // previous token was successfuly used and we can scan next SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { U8 buffer[MAX_STRING_LENGTH]; U32 i = 0; if( IDTF_END_BLOCK != GetCurrentCharacter() ) { while( ( 0 == IsSpace( GetCurrentCharacter() ) ) && !IsEndOfFile() && i < MAX_STRING_LENGTH ) { buffer[i++] = GetCurrentCharacter(); NextCharacter(); } buffer[i] = 0; /// @todo: Converter unicode support m_currentToken.Assign( buffer ); } else { // block terminator found // do not allow client to continue scan for new tokens<|fim▁hole|> } } /// @todo: Converter Unicode support // convert one byte token to unicode IFXString token( pToken ); if( m_currentToken != token ) { m_used = FALSE; result = IFX_E_TOKEN_NOT_FOUND; } else m_used = TRUE; } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanStringToken( const IFXCHAR* pToken, IFXString* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanString( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanIntegerToken( const IFXCHAR* pToken, I32* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanInteger( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanHexToken( const IFXCHAR* pToken, I32* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanHex( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanFloatToken( const IFXCHAR* pToken, F32* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanFloat( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanTMToken( const IFXCHAR* pToken, IFXMatrix4x4* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = FindBlockStarter(); if( IFXSUCCESS( result ) ) result = ScanTM( pValue ); if( IFXSUCCESS( result ) ) result = FindBlockTerminator(); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanColorToken( const IFXCHAR* pToken, Color* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanColor( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanQuatToken( const IFXCHAR* pToken, Quat* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanQuat( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanPointToken( const IFXCHAR* pToken, Point* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanPoint( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::FindBlockStarter() { IFXRESULT result = IFX_OK; SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { if( GetCurrentCharacter() == IDTF_BEGIN_BLOCK ) { NextCharacter(); SkipSpaces(); } else result = IFX_E_STARTER_NOT_FOUND; } return result; } IFXRESULT FileScanner::FindBlockTerminator() { IFXRESULT result = IFX_OK; SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { if( GetCurrentCharacter() == IDTF_END_BLOCK ) { // block terminator found // allow client to scan for next token m_used = TRUE; NextCharacter(); } else result = IFX_E_TERMINATOR_NOT_FOUND; } return result; } //*************************************************************************** // Protected methods //*************************************************************************** BOOL FileScanner::IsSpace( I8 character ) { return isspace( character ); } BOOL FileScanner::IsEndOfFile() { return m_file.IsEndOfFile(); } void FileScanner::SkipSpaces() { while( 0 != isspace( GetCurrentCharacter() ) && !m_file.IsEndOfFile() ) NextCharacter(); } void FileScanner::SkipBlanks() { while( ( ' ' == GetCurrentCharacter() || '\t' == GetCurrentCharacter() ) && !m_file.IsEndOfFile() ) NextCharacter(); } U8 FileScanner::NextCharacter() { return m_currentCharacter[0] = m_file.ReadCharacter(); } //*************************************************************************** // Private methods //*************************************************************************** //*************************************************************************** // Global functions //*************************************************************************** //*************************************************************************** // Local functions //***************************************************************************<|fim▁end|>
m_used = FALSE; }
<|file_name|>gear_transformTools.py<|end_file_name|><|fim▁begin|>''' This file is part of GEAR_mc. GEAR_mc is a fork of Jeremie Passerin's GEAR project. GEAR is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/lgpl.html>. Author: Jeremie Passerin [email protected] www.jeremiepasserin.com Fork Author: Miquel Campos [email protected] www.miqueltd.com Date: 2013 / 08 / 16 ''' ## @package gear_transformTools.py # @author Jeremie Passerin # @version 1.0 # ########################################################## # GLOBAL ########################################################## # Built_in from gear.xsi import xsi, c import gear.xsi.uitoolkit as uit import gear.xsi.transform as tra ########################################################## # XSI LOAD / UNLOAD PLUGIN ########################################################## # ======================================================== def XSILoadPlugin(in_reg): in_reg.Author = "Jeremie Passerin, Miquel Campos" in_reg.Name = "gear_transformTools" in_reg.Email = "[email protected], [email protected]" in_reg.URL = "http://www.jeremiepasserin.com, http://www.miqueltd.com " in_reg.Major = 1 in_reg.Minor = 0 # Commands in_reg.RegisterCommand("gear_MatchSRT","gear_MatchSRT") in_reg.RegisterCommand("gear_MatchT","gear_MatchT") in_reg.RegisterCommand("gear_MatchR","gear_MatchR") in_reg.RegisterCommand("gear_MatchS","gear_MatchS") in_reg.RegisterCommand("gear_MatchRT","gear_MatchRT") in_reg.RegisterCommand("gear_MatchSR","gear_MatchSR") in_reg.RegisterCommand("gear_MatchST","gear_MatchST") return True # ======================================================== def XSIUnloadPlugin(in_reg): strPluginName = in_reg.Name xsi.LogMessage(str(strPluginName) + str(" has been unloaded."), c.siVerbose) return True<|fim▁hole|>########################################################## # ======================================================== def gear_MatchSRT_Execute(): if not xsi.Selection.Count: gear.log("No Selection", gear.sev_error) return source_object = xsi.Selection(0) target_object = uit.pickSession() if not target_object: return tra.matchGlobalTransform(source_object, target_object) # ======================================================== def gear_MatchT_Execute(): if not xsi.Selection.Count: gear.log("No Selection", gear.sev_error) return source_object = xsi.Selection(0) target_object = uit.pickSession() if not target_object: return tra.matchGlobalTransform(source_object, target_object, True, False, False) # ======================================================== def gear_MatchR_Execute(): if not xsi.Selection.Count: gear.log("No Selection", gear.sev_error) return source_object = xsi.Selection(0) target_object = uit.pickSession() if not target_object: return tra.matchGlobalTransform(source_object, target_object, False, True, False) # ======================================================== def gear_MatchS_Execute(): if not xsi.Selection.Count: gear.log("No Selection", gear.sev_error) return source_object = xsi.Selection(0) target_object = uit.pickSession() if not target_object: return tra.matchGlobalTransform(source_object, target_object, False, False, True) # ======================================================== def gear_MatchRT_Execute(): if not xsi.Selection.Count: gear.log("No Selection", gear.sev_error) return source_object = xsi.Selection(0) target_object = uit.pickSession() if not target_object: return tra.matchGlobalTransform(source_object, target_object, True, True, False) # ======================================================== def gear_MatchSR_Execute(): source_object = xsi.Selection(0) target_object = uit.pickSession() if not target_object: return tra.matchGlobalTransform(source_object, target_object, False, True, True) # ======================================================== def gear_MatchST_Execute(): if not xsi.Selection.Count: gear.log("No Selection", gear.sev_error) return source_object = xsi.Selection(0) target_object = uit.pickSession() if not target_object: return tra.matchGlobalTransform(source_object, target_object, True, False, True)<|fim▁end|>
########################################################## # MATCH TRANSFORM
<|file_name|>base64.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Base64 binary-to-text encoding use std::str; use std::fmt; /// Available encoding character sets pub enum CharacterSet { /// The standard character set (uses `+` and `/`) Standard, /// The URL safe character set (uses `-` and `_`) UrlSafe } /// Contains configuration parameters for `to_base64`. pub struct Config { /// Character set to use pub char_set: CharacterSet, /// True to pad output with `=` characters pub pad: bool, /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping pub line_length: Option<uint> } /// Configuration for RFC 4648 standard base64 encoding pub static STANDARD: Config = Config {char_set: Standard, pad: true, line_length: None}; /// Configuration for RFC 4648 base64url encoding pub static URL_SAFE: Config = Config {char_set: UrlSafe, pad: false, line_length: None}; /// Configuration for RFC 2045 MIME base64 encoding pub static MIME: Config = Config {char_set: Standard, pad: true, line_length: Some(76)}; static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789+/"); static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789-_"); /// A trait for converting a value to base64 encoding. pub trait ToBase64 { /// Converts the value of `self` to a base64 value following the specified /// format configuration, returning the owned string. fn to_base64(&self, config: Config) -> StrBuf; } impl<'a> ToBase64 for &'a [u8] { /** * Turn a vector of `u8` bytes into a base64 string. * * # Example * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, STANDARD}; * * fn main () { * let str = [52,32].to_base64(STANDARD); * println!("base 64 output: {}", str); * } * ``` */ fn to_base64(&self, config: Config) -> StrBuf { let bytes = match config.char_set { Standard => STANDARD_CHARS, UrlSafe => URLSAFE_CHARS }; let mut v = Vec::new(); let mut i = 0; let mut cur_length = 0; let len = self.len(); while i < len - (len % 3) { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); cur_length = 0; }, None => () } let n = (self[i] as u32) << 16 | (self[i + 1] as u32) << 8 | (self[i + 2] as u32); // This 24-bit number gets separated into four 6-bit numbers. v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); v.push(bytes[(n & 63) as uint]); cur_length += 4; i += 3; } if len % 3 != 0 { match config.line_length { Some(line_length) => if cur_length >= line_length { v.push('\r' as u8); v.push('\n' as u8); }, None => () } } // Heh, would be cool if we knew this was exhaustive // (the dream of bounded integer types) match len % 3 { 0 => (), 1 => { let n = (self[i] as u32) << 16; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); if config.pad { v.push('=' as u8); v.push('=' as u8); } } 2 => { let n = (self[i] as u32) << 16 | (self[i + 1u] as u32) << 8; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); if config.pad { v.push('=' as u8); } } _ => fail!("Algebra is broken, please alert the math police") } unsafe { str::raw::from_utf8(v.as_slice()).to_strbuf() }<|fim▁hole|> } } /// A trait for converting from base64 encoded values. pub trait FromBase64 { /// Converts the value of `self`, interpreted as base64 encoded data, into /// an owned vector of bytes, returning the vector. fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>; } /// Errors that can occur when decoding a base64 encoded string pub enum FromBase64Error { /// The input contained a character not part of the base64 format InvalidBase64Character(char, uint), /// The input had an invalid length InvalidBase64Length, } impl fmt::Show for FromBase64Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Character(ch, idx) => write!(f, "Invalid character '{}' at position {}", ch, idx), InvalidBase64Length => write!(f, "Invalid length"), } } } impl<'a> FromBase64 for &'a str { /** * Convert any base64 encoded string (literal, `@`, `&`, or `~`) * to the byte values it encodes. * * You can use the `StrBuf::from_utf8` function in `std::strbuf` to turn a * `Vec<u8>` into a string with characters corresponding to those values. * * # Example * * This converts a string literal to base64 and back. * * ```rust * extern crate serialize; * use serialize::base64::{ToBase64, FromBase64, STANDARD}; * * fn main () { * let hello_str = bytes!("Hello, World").to_base64(STANDARD); * println!("base64 output: {}", hello_str); * let res = hello_str.as_slice().from_base64(); * if res.is_ok() { * let opt_bytes = StrBuf::from_utf8(res.unwrap()); * if opt_bytes.is_ok() { * println!("decoded from base64: {}", opt_bytes.unwrap()); * } * } * } * ``` */ fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { let mut r = Vec::new(); let mut buf: u32 = 0; let mut modulus = 0; let mut it = self.bytes().enumerate(); for (idx, byte) in it { let val = byte as u32; match byte as char { 'A'..'Z' => buf |= val - 0x41, 'a'..'z' => buf |= val - 0x47, '0'..'9' => buf |= val + 0x04, '+'|'-' => buf |= 0x3E, '/'|'_' => buf |= 0x3F, '\r'|'\n' => continue, '=' => break, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } buf <<= 6; modulus += 1; if modulus == 4 { modulus = 0; r.push((buf >> 22) as u8); r.push((buf >> 14) as u8); r.push((buf >> 6 ) as u8); } } for (idx, byte) in it { match byte as char { '='|'\r'|'\n' => continue, _ => return Err(InvalidBase64Character(self.char_at(idx), idx)), } } match modulus { 2 => { r.push((buf >> 10) as u8); } 3 => { r.push((buf >> 16) as u8); r.push((buf >> 8 ) as u8); } 0 => (), _ => return Err(InvalidBase64Length), } Ok(r) } } #[cfg(test)] mod tests { extern crate test; extern crate rand; use self::test::Bencher; use base64::{Config, FromBase64, ToBase64, STANDARD, URL_SAFE}; #[test] fn test_to_base64_basic() { assert_eq!("".as_bytes().to_base64(STANDARD), "".to_strbuf()); assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_strbuf()); assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_strbuf()); assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_strbuf()); assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_strbuf()); assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_strbuf()); } #[test] fn test_to_base64_line_break() { assert!(![0u8, ..1000].to_base64(Config {line_length: None, ..STANDARD}) .as_slice() .contains("\r\n")); assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4), ..STANDARD}), "Zm9v\r\nYmFy".to_strbuf()); } #[test] fn test_to_base64_padding() { assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg".to_strbuf()); assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8".to_strbuf()); } #[test] fn test_to_base64_url_safe() { assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_strbuf()); assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_strbuf()); } #[test] fn test_from_base64_basic() { assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes()); assert_eq!("Zg==".from_base64().unwrap().as_slice(), "f".as_bytes()); assert_eq!("Zm8=".from_base64().unwrap().as_slice(), "fo".as_bytes()); assert_eq!("Zm9v".from_base64().unwrap().as_slice(), "foo".as_bytes()); assert_eq!("Zm9vYg==".from_base64().unwrap().as_slice(), "foob".as_bytes()); assert_eq!("Zm9vYmE=".from_base64().unwrap().as_slice(), "fooba".as_bytes()); assert_eq!("Zm9vYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); } #[test] fn test_from_base64_newlines() { assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(), "foob".as_bytes()); } #[test] fn test_from_base64_urlsafe() { assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap()); } #[test] fn test_from_base64_invalid_char() { assert!("Zm$=".from_base64().is_err()) assert!("Zg==$".from_base64().is_err()); } #[test] fn test_from_base64_invalid_padding() { assert!("Z===".from_base64().is_err()); } #[test] fn test_base64_random() { use self::rand::{task_rng, random, Rng}; for _ in range(0, 1000) { let times = task_rng().gen_range(1u, 100); let v = Vec::from_fn(times, |_| random::<u8>()); assert_eq!(v.as_slice() .to_base64(STANDARD) .as_slice() .from_base64() .unwrap() .as_slice(), v.as_slice()); } } #[bench] pub fn bench_to_base64(b: &mut Bencher) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] pub fn bench_from_base64(b: &mut Bencher) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; let sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.as_slice().from_base64().unwrap(); }); b.bytes = sb.len() as u64; } }<|fim▁end|>
<|file_name|>change_edges.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012 Santosh Philip # ======================================================================= # Distributed under the MIT License. # (See accompanying file LICENSE or copy at # http://opensource.org/licenses/MIT) # ======================================================================= """change the edges in loopdaigram so that there are no names with colons (:) """ def replace_colon(s, replacewith='__'): """replace the colon with something""" return s.replace(":", replacewith) def clean_edges(arg): if isinstance(arg, basestring): # Python 3: isinstance(arg, str) return replace_colon(arg) try: return tuple(clean_edges(x) for x in arg) except TypeError: # catch when for loop fails return replace_colon(arg) # not a sequence so just return repr # start pytests +++++++++++++++++++++++ def test_replace_colon(): """py.test for replace_colon""" data = (("zone:aap", '@', "zone@aap"),# s, r, replaced ) for s, r, replaced in data: result = replace_colon(s, r) assert result == replaced def test_cleanedges(): """py.test for cleanedges""" data = (([('a:a', 'a'), (('a', 'a'), 'a:a'), ('a:a', ('a', 'a'))], (('a__a', 'a'), (('a', 'a'), 'a__a'), ('a__a', ('a', 'a')))), # edg, clean_edg<|fim▁hole|> result = clean_edges(edg) assert result == clean_edg # end pytests +++++++++++++++++++++++<|fim▁end|>
) for edg, clean_edg in data:
<|file_name|>IDocument.java<|end_file_name|><|fim▁begin|>/** * */ package org.jbpt.pm.bpmn; <|fim▁hole|> * * @author Cindy F�hnrich */ public interface IDocument extends IDataNode { /** * Marks this Document as list. */ public void markAsList(); /** * Unmarks this Document as list. */ public void unmarkAsList(); /** * Checks whether the current Document is a list. * @return */ public boolean isList(); }<|fim▁end|>
import org.jbpt.pm.IDataNode; /** * Interface class for BPMN Document.
<|file_name|>LexModelBuildingServiceErrorMarshaller.cpp<|end_file_name|><|fim▁begin|>/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #include <aws/core/client/AWSError.h> #include <aws/lex-models/LexModelBuildingServiceErrorMarshaller.h> #include <aws/lex-models/LexModelBuildingServiceErrors.h> using namespace Aws::Client; using namespace Aws::LexModelBuildingService; AWSError<CoreErrors> LexModelBuildingServiceErrorMarshaller::FindErrorByName(const char* errorName) const { AWSError<CoreErrors> error = LexModelBuildingServiceErrorMapper::GetErrorForName(errorName); if(error.GetErrorType() != CoreErrors::UNKNOWN) { return error; }<|fim▁hole|><|fim▁end|>
return AWSErrorMarshaller::FindErrorByName(errorName); }
<|file_name|>imageprocess.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os.path import time import urllib import json import requests from tencentyun import conf from .auth import Auth class ImageProcess(object): def __init__(self, appid, secret_id, secret_key, bucket): self.IMAGE_FILE_NOT_EXISTS = -1 self._secret_id,self._secret_key = secret_id,secret_key conf.set_app_info(appid, secret_id, secret_key, bucket) def porn_detect(self, porn_detect_url): auth = Auth(self._secret_id, self._secret_key) sign = auth.get_porn_detect_sign(porn_detect_url) app_info = conf.get_app_info() if False == sign: return { 'code':9, 'message':'Secret id or key is empty.', 'data':{}, } url = app_info['end_point_porndetect'] payload = { 'bucket':app_info['bucket'], 'appid':int(app_info['appid']), 'url':(porn_detect_url).encode("utf-8"), } header = { 'Authorization':sign, 'Content-Type':'application/json', } r = {} r = requests.post(url, data=json.dumps(payload), headers=header) ret = r.json() return ret def porn_detect_url(self, porn_url): auth = Auth(self._secret_id, self._secret_key) sign = auth.get_porn_detect_sign() app_info = conf.get_app_info() if False == sign: return { 'code':9, 'message':'Secret id or key is empty.', 'data':{}, } url = app_info['end_point_porndetect'] payload = { 'bucket':app_info['bucket'], 'appid':int(app_info['appid']), 'url_list':porn_url, } header = { 'Authorization':sign, 'Content-Type':'application/json', } r = {}<|fim▁hole|> def porn_detect_file(self, porn_file): auth = Auth(self._secret_id, self._secret_key) sign = auth.get_porn_detect_sign() app_info = conf.get_app_info() if False == sign: return { 'code':9, 'message':'Secret id or key is empty.', 'data':{}, } url = app_info['end_point_porndetect'] header = { 'Authorization':sign, } files = { 'appid':(None,app_info['appid'],None), 'bucket':(None,app_info['bucket'],None), } i=0 for pfile in porn_file: pfile = pfile.decode('utf-8') local_path = os.path.abspath(pfile) if not os.path.exists(local_path): return {'httpcode':0, 'code':self.IMAGE_FILE_NOT_EXISTS, 'message':'file ' + pfile + ' not exists', 'data':{}} i+=1 files['image['+str(i-1)+']']=(pfile, open(pfile,'rb')) r = requests.post(url, headers=header, files=files) ret = r.json() return ret<|fim▁end|>
r = requests.post(url, data=json.dumps(payload), headers=header) ret = r.json() return ret
<|file_name|>canned_sentiment_analysis.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from input_functions import get_input_fn import tensorflow as tf from tensorflow.contrib.keras.python.keras.datasets import imdb from tensorflow.contrib.learn.python.learn import learn_runner from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators.dynamic_rnn_estimator import PredictionType print('TensorFlow version', tf.__version__) parser = argparse.ArgumentParser() parser.add_argument( '--model_dir', type=str, default='sentiment_analysis_output', help='The directory where the model outputs should be stored') parser.add_argument( '--batch_by_seq_len', type=bool, default=False, help='If True each bath will have sequences of similar length.' 'This makes the model train faster') parser.add_argument( '--max_len', type=int, default=250, help='Sentences will be truncated at max_len') parser.add_argument( '--num_words', type=int, default=1000, help='Only num_words more frequent words will be used for testing') parser.add_argument( '--train_batch_size', type=int, default=16, help='Batch size used for training') parser.add_argument( '--eval_batch_size', type=int, default=16, help='Batch size used for evaluation') parser.add_argument( '--embed_dim', type=int, default=30, help='Embedding dimension') parser.add_argument( '--learning_rate', type=int, default=0.001, help='Learning rate') parser.add_argument( '--num_epochs', type=int, default=10, help='Num epochs used for training (for evaluation is always 1)') parser.add_argument( '--cell_type', type=str, default='lstm', help='RNN cell type') parser.add_argument( '--optimizer', type=str, default='Adam', help='Optimizer used for training') parser.add_argument( '--num_rnn_units', nargs='+', type=int, default=[256, 128], help='Size of the hidden state for each RNN cell') parser.add_argument( '--dropout_keep_probabilities', nargs='+', type=int, default=[0.9, 0.9, 0.9], help='Dropout probabilities to keep the cell. ' 'If provided the length should be num_rnn_units + 1') parser.add_argument( '--num_classes', type=int, default=2,<|fim▁hole|> 'For sentiment analysis is 2 (positive and negative)') FLAGS = parser.parse_args() # create experiment def generate_experiment_fn(x_train, y_train, x_test, y_test): def _experiment_fn(run_config, hparams): del hparams # unused arg # feature sequences xc = tf.contrib.layers.sparse_column_with_integerized_feature( 'x', FLAGS.num_words) xc = tf.contrib.layers.embedding_column(xc, FLAGS.embed_dim) # creates estimator estimator = tf.contrib.learn.DynamicRnnEstimator( config=run_config, problem_type=constants.ProblemType.CLASSIFICATION, prediction_type=PredictionType.SINGLE_VALUE, sequence_feature_columns=[xc], context_feature_columns=None, num_units=FLAGS.num_rnn_units, cell_type=FLAGS.cell_type, optimizer=FLAGS.optimizer, learning_rate=FLAGS.learning_rate, num_classes=FLAGS.num_classes, dropout_keep_probabilities=FLAGS.dropout_keep_probabilities) # input functions train_input = get_input_fn(x_train, y_train, FLAGS.train_batch_size, epochs=FLAGS.num_epochs, max_length=FLAGS.max_len, batch_by_seq_len=FLAGS.batch_by_seq_len) test_input = get_input_fn(x_test, y_test, FLAGS.eval_batch_size, epochs=1, max_length=FLAGS.max_len) # returns Experiment return tf.contrib.learn.Experiment( estimator, train_input_fn=train_input, eval_input_fn=test_input, ) return _experiment_fn def main(unused_argv): # Loading the data # data from: https://keras.io/datasets/ # Dataset of 25,000 movies reviews from IMDB, labeled by sentiment # (positive/negative). # Reviews have been preprocessed, and each review is encoded as a sequence # of word indexes (integers). # For convenience, words are indexed by overall frequency in the dataset. print('Loading data...') (x_train, y_train), (x_test, y_test) = imdb.load_data( num_words=FLAGS.num_words) print('size of the train dataset:', x_train.shape[0]) print('size of the test dataset:', x_test.shape[0]) # run experiment run_config = tf.contrib.learn.RunConfig(model_dir=FLAGS.model_dir) learn_runner.run(generate_experiment_fn(x_train, y_train, x_test, y_test), run_config=run_config) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) # enable TensorFlow logs tf.app.run()<|fim▁end|>
help='Number of output classes. '
<|file_name|>model.rs<|end_file_name|><|fim▁begin|>//! Struct and enum definitions of values in the Discord model. #![allow(missing_docs)] use super::{Error, Result}; use serde_json::Value; use std::collections::BTreeMap; use std::fmt; use std::borrow::Cow; pub use self::permissions::Permissions; macro_rules! req { ($opt:expr) => { try!($opt.ok_or(Error::Decode(concat!("Type mismatch in model:", line!(), ": ", stringify!($opt)), Value::Null))) } } macro_rules! warn_json { (@ $name:expr, $json:ident, $value:expr) => { (Ok($value), warn_field($name, $json)).0 }; ($json:ident, $ty:ident $(::$ext:ident)* ( $($value:expr),*$(,)* ) ) => { (Ok($ty$(::$ext)* ( $($value),* )), warn_field(stringify!($ty$(::$ext)*), $json)).0 }; ($json:ident, $ty:ident $(::$ext:ident)* { $($name:ident: $value:expr),*$(,)* } ) => { (Ok($ty$(::$ext)* { $($name: $value),* }), warn_field(stringify!($ty$(::$ext)*), $json)).0 }; } macro_rules! map_names { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn name(&self) -> &'static str { match *self { $($typ::$entry => $value,)* } } pub fn from_str(name: &str) -> Option<Self> { match name { $($value => Some($typ::$entry),)* _ => None, } } #[allow(dead_code)] fn decode_str(value: Value) -> Result<Self> { let name = try!(into_string(value)); Self::from_str(&name).ok_or(Error::Decode( concat!("Expected valid ", stringify!($typ)), Value::String(name) )) } } } } macro_rules! map_numbers { ($typ:ident; $($entry:ident, $value:expr;)*) => { impl $typ { pub fn num(&self) -> u64 { match *self { $($typ::$entry => $value,)* } } pub fn from_num(num: u64) -> Option<Self> { match num { $($value => Some($typ::$entry),)* _ => None, } } fn decode(value: Value) -> Result<Self> { value.as_u64().and_then(Self::from_num).ok_or(Error::Decode( concat!("Expected valid ", stringify!($typ)), value )) } } } } //================= // Discord identifier types fn decode_id(value: Value) -> Result<u64> { match value { Value::U64(num) => Ok(num), Value::String(text) => match text.parse::<u64>() { Ok(num) => Ok(num), Err(_) => Err(Error::Decode("Expected numeric ID", Value::String(text))) }, value => Err(Error::Decode("Expected numeric ID", value)) } } macro_rules! id { ($(#[$attr:meta] $name:ident;)*) => { $( #[$attr] /// /// Identifiers can be debug-printed using the `{:?}` specifier, or their /// raw number value printed using the `{}` specifier. /// Some identifiers have `mention()` methods as well. #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug, Ord, PartialOrd)] pub struct $name(pub u64); impl $name { #[inline] fn decode(value: Value) -> Result<Self> { decode_id(value).map($name) } /// Get the creation date of the object referred to by this ID. /// /// Discord generates identifiers using a scheme based on [Twitter Snowflake] /// (https://github.com/twitter/snowflake/tree/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231#snowflake). pub fn creation_date(&self) -> ::time::Timespec { ::time::Timespec::new((1420070400 + (self.0 >> 22) / 1000) as i64, 0) } } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } )* } } id! { /// An identifier for a User UserId; /// An identifier for a Server ServerId; /// An identifier for a Channel ChannelId; /// An identifier for a Message MessageId; /// An identifier for a Role RoleId; /// An identifier for an Emoji EmojiId; } /// A mention targeted at a specific user, channel, or other entity. /// /// A mention can be constructed by calling `.mention()` on a mentionable item /// or an ID type which refers to it, and can be formatted into a string using /// the `format!` macro: /// /// ```ignore /// let message = format!("Hey, {}, ping!", user.mention()); /// ``` /// /// If a `String` is required, call `mention.to_string()`. pub struct Mention { prefix: &'static str, id: u64, } impl fmt::Display for Mention { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.prefix)); try!(fmt::Display::fmt(&self.id, f)); fmt::Write::write_char(f, '>') } } impl UserId { /// Return a `Mention` which will ping this user. #[inline(always)] pub fn mention(&self) -> Mention { Mention { prefix: "<@", id: self.0 } } } impl RoleId { /// Return a `Mention` which will ping members of this role. #[inline(always)] pub fn mention(&self) -> Mention { Mention { prefix: "<@&", id: self.0 } } } impl ChannelId { /// Return a `Mention` which will link to this channel. #[inline(always)] pub fn mention(&self) -> Mention { Mention { prefix: "<#", id: self.0 } } } #[test] fn mention_test() { assert_eq!(UserId(1234).mention().to_string(), "<@1234>"); assert_eq!(RoleId(1234).mention().to_string(), "<@&1234>"); assert_eq!(ChannelId(1234).mention().to_string(), "<#1234>"); } //================= // Rest model /// The type of a channel #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum ChannelType { /// A group channel, separate from a server Group, /// A private channel with only one other person Private, /// A text channel in a server Text, /// A voice channel Voice, } map_names! { ChannelType; Group, "group"; Private, "private"; Text, "text"; Voice, "voice"; } map_numbers! { ChannelType; Text, 0; Private, 1; Voice, 2; Group, 3; } /// The basic information about a server only #[derive(Debug, Clone)] pub struct ServerInfo { pub id: ServerId, pub name: String, pub icon: Option<String>, pub owner: bool, pub permissions: Permissions, } impl ServerInfo { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, ServerInfo { id: try!(remove(&mut value, "id").and_then(ServerId::decode)), name: try!(remove(&mut value, "name").and_then(into_string)), icon: try!(opt(&mut value, "icon", into_string)), owner: req!(try!(remove(&mut value, "owner")).as_bool()), permissions: try!(remove(&mut value, "permissions").and_then(Permissions::decode)), }) } /// Returns the formatted URL of the server's icon. /// /// Returns None if the server does not have an icon. pub fn icon_url(&self) -> Option<String> { self.icon.as_ref().map(|icon| format!(cdn_concat!("/icons/{}/{}.jpg"), self.id, icon)) } } /// Static information about a server #[derive(Debug, Clone)] pub struct Server { pub id: ServerId, pub name: String, pub afk_timeout: u64, pub afk_channel_id: Option<ChannelId>, pub icon: Option<String>, pub roles: Vec<Role>, pub region: String, pub embed_enabled: bool, pub embed_channel_id: Option<ChannelId>, pub owner_id: UserId, pub verification_level: VerificationLevel, pub emojis: Vec<Emoji>, pub features: Vec<String>, pub splash: Option<String>, pub default_message_notifications: u64, pub mfa_level: u64, } impl Server { pub fn decode(value: Value) -> Result<Server> { let mut value = try!(into_map(value)); warn_json!(value, Server { id: try!(remove(&mut value, "id").and_then(ServerId::decode)), name: try!(remove(&mut value, "name").and_then(into_string)), icon: try!(opt(&mut value, "icon", into_string)), afk_timeout: req!(try!(remove(&mut value, "afk_timeout")).as_u64()), afk_channel_id: try!(opt(&mut value, "afk_channel_id", ChannelId::decode)), embed_enabled: req!(try!(remove(&mut value, "embed_enabled")).as_bool()), embed_channel_id: try!(opt(&mut value, "embed_channel_id", ChannelId::decode)), owner_id: try!(remove(&mut value, "owner_id").and_then(UserId::decode)), region: try!(remove(&mut value, "region").and_then(into_string)), roles: try!(decode_array(try!(remove(&mut value, "roles")), Role::decode)), verification_level: try!(remove(&mut value, "verification_level").and_then(VerificationLevel::decode)), emojis: try!(remove(&mut value, "emojis").and_then(|v| decode_array(v, Emoji::decode))), features: try!(remove(&mut value, "features").and_then(|v| decode_array(v, into_string))), splash: try!(opt(&mut value, "splash", into_string)), default_message_notifications: req!(try!(remove(&mut value, "default_message_notifications")).as_u64()), mfa_level: req!(try!(remove(&mut value, "mfa_level")).as_u64()), }) } /// Returns the formatted URL of the server's icon. /// /// Returns None if the server does not have an icon. pub fn icon_url(&self) -> Option<String> { self.icon.as_ref().map(|icon| format!(cdn_concat!("/icons/{}/{}.jpg"), self.id, icon)) } } /// Representation of the number of member that would be pruned by a server /// prune operation. #[derive(Debug, Clone)] pub struct ServerPrune { pub pruned: u64, } impl ServerPrune { pub fn decode(value: Value) -> Result<ServerPrune> { let mut value = try!(into_map(value)); warn_json!(value, ServerPrune { pruned: req!(try!(remove(&mut value, "pruned")).as_u64()), }) } } /// Information about a role #[derive(Debug, Clone)] pub struct Role { pub id: RoleId, pub name: String, /// Color in `0xRRGGBB` form pub color: u64, pub hoist: bool, pub managed: bool, pub position: i64, pub mentionable: bool, pub permissions: Permissions, } impl Role { pub fn decode(value: Value) -> Result<Role> { let mut value = try!(into_map(value)); warn_json!(value, Role { id: try!(remove(&mut value, "id").and_then(RoleId::decode)), name: try!(remove(&mut value, "name").and_then(into_string)), permissions: try!(remove(&mut value, "permissions").and_then(Permissions::decode)), color: req!(try!(remove(&mut value, "color")).as_u64()), hoist: req!(try!(remove(&mut value, "hoist")).as_bool()), managed: req!(try!(remove(&mut value, "managed")).as_bool()), position: req!(try!(remove(&mut value, "position")).as_i64()), mentionable: try!(opt(&mut value, "mentionable", |v| Ok(req!(v.as_bool())))).unwrap_or(false), }) } /// Return a `Mention` which will ping members of this role. #[inline(always)] pub fn mention(&self) -> Mention { self.id.mention() } } /// A banning of a user #[derive(Debug, Clone)] pub struct Ban { reason: Option<String>, user: User, } impl Ban { pub fn decode(value: Value) -> Result<Ban> { let mut value = try!(into_map(value)); warn_json!(value, Ban { reason: try!(opt(&mut value, "reason", into_string)), user: try!(remove(&mut value, "user").and_then(User::decode)), }) } } /// Broadly-applicable user information #[derive(Debug, Clone)] pub struct User { pub id: UserId, pub name: String, pub discriminator: u16, pub avatar: Option<String>, pub bot: bool, } impl User { pub fn decode(value: Value) -> Result<User> { let mut value = try!(into_map(value)); warn_json!(value, User { id: try!(remove(&mut value, "id").and_then(UserId::decode)), name: try!(remove(&mut value, "username").and_then(into_string)), discriminator: try!(remove(&mut value, "discriminator").and_then(decode_discriminator)), avatar: try!(opt(&mut value, "avatar", into_string)), bot: try!(opt(&mut value, "bot", |v| Ok(req!(v.as_bool())))).unwrap_or(false), }) } /// Return a `Mention` which will ping this user. #[inline(always)] pub fn mention(&self) -> Mention { self.id.mention() } /// Returns the formatted URL of the user's icon. /// /// Returns None if the user does not have an avatar. pub fn avatar_url(&self) -> Option<String> { self.avatar.as_ref().map(|av| format!(cdn_concat!("/avatars/{}/{}.jpg"), self.id, av)) } } /// Information about a member of a server #[derive(Debug, Clone)] pub struct Member { pub user: User, pub roles: Vec<RoleId>, pub nick: Option<String>, pub joined_at: String, pub mute: bool, pub deaf: bool, } impl Member { pub fn decode(value: Value) -> Result<Member> { let mut value = try!(into_map(value)); warn_json!(value, Member { user: try!(remove(&mut value, "user").and_then(User::decode)), roles: try!(decode_array(try!(remove(&mut value, "roles")), RoleId::decode)), nick: try!(opt(&mut value, "nick", into_string)), joined_at: try!(remove(&mut value, "joined_at").and_then(into_string)), mute: req!(try!(remove(&mut value, "mute")).as_bool()), deaf: req!(try!(remove(&mut value, "deaf")).as_bool()), }) } pub fn display_name(&self) -> &str { if let Some(name) = self.nick.as_ref() { name } else { &self.user.name } } } /// A private or public channel #[derive(Debug, Clone)] pub enum Channel { /// A group channel separate from a server Group(Group), /// Text channel to another user Private(PrivateChannel), /// Voice or text channel within a server Public(PublicChannel), } impl Channel { pub fn decode(value: Value) -> Result<Channel> { let map = try!(into_map(value)); match req!(map.get("type").and_then(|x| x.as_u64())) { 0 | 2 => PublicChannel::decode(Value::Object(map)).map(Channel::Public), 1 => PrivateChannel::decode(Value::Object(map)).map(Channel::Private), 3 => Group::decode(Value::Object(map)).map(Channel::Group), other => Err(Error::Decode("Expected value Channel type", Value::U64(other))), } } } /// A group channel, potentially including other users, separate from a server. #[derive(Debug, Clone)] pub struct Group { pub channel_id: ChannelId, pub icon: Option<String>, pub last_message_id: Option<MessageId>, pub last_pin_timestamp: Option<String>, pub name: Option<String>, pub owner_id: UserId, pub recipients: Vec<User>, } impl Group { pub fn decode(value: Value) -> Result<Group> { let mut value = try!(into_map(value)); let _ = remove(&mut value, "type"); // ignore "type" field warn_json!(value, Group { channel_id: try!(remove(&mut value, "id").and_then(ChannelId::decode)), icon: try!(opt(&mut value, "icon", into_string)), last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)), last_pin_timestamp: try!(opt(&mut value, "last_pin_timestamp", into_string)), name: try!(opt(&mut value, "name", into_string)), owner_id: try!(remove(&mut value, "owner_id").and_then(UserId::decode)), recipients: try!(opt(&mut value, "recipients", |r| decode_array(r, User::decode))).unwrap_or(Vec::new()), }) } /// Get this group's name, building a default if needed pub fn name(&self) -> Cow<str> { match self.name { Some(ref name) => Cow::Borrowed(name), None => { if self.recipients.is_empty() { return Cow::Borrowed("Empty Group"); } let mut result = self.recipients[0].name.clone(); for user in &self.recipients[1..] { use std::fmt::Write; let _ = write!(result, ", {}", user.name); } Cow::Owned(result) } } } /// Returns the formatted URL of the group's icon. /// /// Returns None if the group does not have an icon. pub fn icon_url(&self) -> Option<String> { self.icon.as_ref().map(|icon| format!(cdn_concat!("/channel-icons/{}/{}.jpg"), self.channel_id, icon)) } } /// An active group or private call #[derive(Debug, Clone)] pub struct Call { pub channel_id: ChannelId, pub message_id: MessageId, pub region: String, pub ringing: Vec<UserId>, pub unavailable: bool, pub voice_states: Vec<VoiceState>, } impl Call { pub fn decode(value: Value) -> Result<Call> { let mut value = try!(into_map(value)); warn_json!(value, Call { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), message_id: try!(remove(&mut value, "message_id").and_then(MessageId::decode)), region: try!(remove(&mut value, "region").and_then(into_string)), ringing: try!(decode_array(try!(remove(&mut value, "ringing")), UserId::decode)), unavailable: req!(try!(remove(&mut value, "unavailable")).as_bool()), voice_states: try!(decode_array(try!(remove(&mut value, "voice_states")), VoiceState::decode)), }) } } /// Private text channel to another user #[derive(Debug, Clone)] pub struct PrivateChannel { pub id: ChannelId, pub kind: ChannelType, pub recipient: User, pub last_message_id: Option<MessageId>, pub last_pin_timestamp: Option<String>, } impl PrivateChannel { pub fn decode(value: Value) -> Result<PrivateChannel> { let mut value = try!(into_map(value)); let mut recipients = try!(decode_array(try!(remove(&mut value, "recipients")), User::decode)); if recipients.len() != 1 { warn!("expected 1 recipient, found {}: {:?}", recipients.len(), recipients); } warn_json!(value, PrivateChannel { id: try!(remove(&mut value, "id").and_then(ChannelId::decode)), kind: try!(remove(&mut value, "type").and_then(ChannelType::decode)), recipient: recipients.remove(0), last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)), last_pin_timestamp: try!(opt(&mut value, "last_pin_timestamp", into_string)), }) } } /// Public voice or text channel within a server #[derive(Debug, Clone)] pub struct PublicChannel { pub id: ChannelId, pub name: String, pub server_id: ServerId, pub kind: ChannelType, pub permission_overwrites: Vec<PermissionOverwrite>, pub topic: Option<String>, pub position: i64, pub last_message_id: Option<MessageId>, pub bitrate: Option<u64>, pub user_limit: Option<u64>, pub last_pin_timestamp: Option<String>, } impl PublicChannel { pub fn decode(value: Value) -> Result<PublicChannel> { let mut value = try!(into_map(value)); let id = try!(remove(&mut value, "guild_id").and_then(ServerId::decode)); PublicChannel::decode_server(Value::Object(value), id) } pub fn decode_server(value: Value, server_id: ServerId) -> Result<PublicChannel> { let mut value = try!(into_map(value)); warn_json!(value, PublicChannel { id: try!(remove(&mut value, "id").and_then(ChannelId::decode)), name: try!(remove(&mut value, "name").and_then(into_string)), server_id: server_id, topic: try!(opt(&mut value, "topic", into_string)), position: req!(try!(remove(&mut value, "position")).as_i64()), kind: try!(remove(&mut value, "type").and_then(ChannelType::decode)), last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)), permission_overwrites: try!(decode_array(try!(remove(&mut value, "permission_overwrites")), PermissionOverwrite::decode)), bitrate: remove(&mut value, "bitrate").ok().and_then(|v| v.as_u64()), user_limit: remove(&mut value, "user_limit").ok().and_then(|v| v.as_u64()), last_pin_timestamp: try!(opt(&mut value, "last_pin_timestamp", into_string)), }) } /// Return a `Mention` which will link to this channel. #[inline(always)] pub fn mention(&self) -> Mention { self.id.mention() } } /// The type of edit being made to a Channel's permissions. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum PermissionOverwriteType { Member(UserId), Role(RoleId), } /// A channel-specific permission overwrite for a role or member. #[derive(Debug, Clone)] pub struct PermissionOverwrite { pub kind: PermissionOverwriteType, pub allow: Permissions, pub deny: Permissions, } impl PermissionOverwrite { pub fn decode(value: Value) -> Result<PermissionOverwrite> { let mut value = try!(into_map(value)); let id = try!(remove(&mut value, "id").and_then(decode_id)); let kind = try!(remove(&mut value, "type").and_then(into_string)); let kind = match &*kind { "member" => PermissionOverwriteType::Member(UserId(id)), "role" => PermissionOverwriteType::Role(RoleId(id)), _ => return Err(Error::Decode("Expected valid PermissionOverwrite type", Value::String(kind))), }; warn_json!(value, PermissionOverwrite { kind: kind, allow: try!(remove(&mut value, "allow").and_then(Permissions::decode)), deny: try!(remove(&mut value, "deny").and_then(Permissions::decode)), }) } } pub mod permissions { use ::{Error, Result}; use serde_json::Value; bitflags! { /// Set of permissions assignable to a Role or PermissionOverwrite pub flags Permissions: u64 { const CREATE_INVITE = 1 << 0, const KICK_MEMBERS = 1 << 1, const BAN_MEMBERS = 1 << 2, /// Grant all permissions, bypassing channel-specific permissions const ADMINISTRATOR = 1 << 3, /// Modify roles below their own const MANAGE_ROLES = 1 << 28, /// Create channels or edit existing ones const MANAGE_CHANNELS = 1 << 4, /// Change the server's name or move regions const MANAGE_SERVER = 1 << 5, /// Change their own nickname const CHANGE_NICKNAMES = 1 << 26, /// Change the nickname of other users const MANAGE_NICKNAMES = 1 << 27, /// Manage the emojis in a a server. const MANAGE_EMOJIS = 1 << 30, /// Manage channel webhooks const MANAGE_WEBHOOKS = 1 << 29, const READ_MESSAGES = 1 << 10, const SEND_MESSAGES = 1 << 11, /// Send text-to-speech messages to those focused on the channel const SEND_TTS_MESSAGES = 1 << 12, /// Delete messages by other users const MANAGE_MESSAGES = 1 << 13, const EMBED_LINKS = 1 << 14, const ATTACH_FILES = 1 << 15, const READ_HISTORY = 1 << 16, /// Trigger a push notification for an entire channel with "@everyone" const MENTION_EVERYONE = 1 << 17, /// Use emojis from other servers const EXTERNAL_EMOJIS = 1 << 18, /// Add emoji reactions to messages const ADD_REACTIONS = 1 << 6, const VOICE_CONNECT = 1 << 20, const VOICE_SPEAK = 1 << 21, const VOICE_MUTE_MEMBERS = 1 << 22, const VOICE_DEAFEN_MEMBERS = 1 << 23, /// Move users out of this channel into another const VOICE_MOVE_MEMBERS = 1 << 24, /// When denied, members must use push-to-talk const VOICE_USE_VAD = 1 << 25, } } impl Permissions { pub fn decode(value: Value) -> Result<Permissions> { Ok(Self::from_bits_truncate(req!(value.as_u64()))) } } } /// File upload attached to a message #[derive(Debug, Clone)] pub struct Attachment { pub id: String, /// Short filename for the attachment pub filename: String, /// Shorter URL with message and attachment id pub url: String, /// Longer URL with large hash pub proxy_url: String, /// Size of the file in bytes pub size: u64, /// Dimensions if the file is an image pub dimensions: Option<(u64, u64)>, } impl Attachment { pub fn decode(value: Value) -> Result<Attachment> { let mut value = try!(into_map(value)); let width = remove(&mut value, "width").ok().and_then(|x| x.as_u64()); let height = remove(&mut value, "height").ok().and_then(|x| x.as_u64()); warn_json!(value, Attachment { id: try!(remove(&mut value, "id").and_then(into_string)), filename: try!(remove(&mut value, "filename").and_then(into_string)), url: try!(remove(&mut value, "url").and_then(into_string)), proxy_url: try!(remove(&mut value, "proxy_url").and_then(into_string)), size: req!(try!(remove(&mut value, "size")).as_u64()), dimensions: width.and_then(|w| height.map(|h| (w, h))), }) } } /// Message transmitted over a text channel #[derive(Debug, Clone)] pub struct Message { pub id: MessageId, pub channel_id: ChannelId, pub content: String, pub nonce: Option<String>, pub tts: bool, pub timestamp: String, pub edited_timestamp: Option<String>, pub pinned: bool, pub kind: MessageType, pub author: User, pub mention_everyone: bool, pub mentions: Vec<User>, pub mention_roles: Vec<RoleId>, pub reactions: Vec<MessageReaction>, pub attachments: Vec<Attachment>, /// Follows OEmbed standard pub embeds: Vec<Value>, } impl Message { pub fn decode(value: Value) -> Result<Message> { let mut value = try!(into_map(value)); warn_json!(value, Message { id: try!(remove(&mut value, "id").and_then(MessageId::decode)), channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), nonce: remove(&mut value, "nonce").and_then(into_string).ok(), // nb: swallow errors content: try!(remove(&mut value, "content").and_then(into_string)), tts: req!(try!(remove(&mut value, "tts")).as_bool()), timestamp: try!(remove(&mut value, "timestamp").and_then(into_string)), edited_timestamp: try!(opt(&mut value, "edited_timestamp", into_string)), pinned: req!(try!(remove(&mut value, "pinned")).as_bool()), kind: try!(remove(&mut value, "type").and_then(MessageType::decode)), mention_everyone: req!(try!(remove(&mut value, "mention_everyone")).as_bool()), mentions: try!(decode_array(try!(remove(&mut value, "mentions")), User::decode)), mention_roles: try!(decode_array(try!(remove(&mut value, "mention_roles")), RoleId::decode)), author: try!(remove(&mut value, "author").and_then(User::decode)), attachments: try!(decode_array(try!(remove(&mut value, "attachments")), Attachment::decode)), embeds: try!(decode_array(try!(remove(&mut value, "embeds")), Ok)), reactions: try!(opt(&mut value, "reactions", |x| decode_array(x, MessageReaction::decode))).unwrap_or(Vec::new()), }) } } /// The type of a message #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum MessageType { /// A regular, text-based message Regular, /// A recipient was added to the group GroupRecipientAddition, /// A recipient was removed from the group GroupRecipientRemoval, /// A group call was created GroupCallCreation, /// A group name was updated GroupNameUpdate, /// A group icon was updated GroupIconUpdate, /// A message was pinned MessagePinned, } map_numbers! { MessageType; Regular, 0; GroupRecipientAddition, 1; GroupRecipientRemoval, 2; GroupCallCreation, 3; GroupNameUpdate, 4; GroupIconUpdate, 5; MessagePinned, 6; } /// Information about an invite #[derive(Debug, Clone)] pub struct Invite { pub code: String, pub server_id: ServerId, pub server_name: String, pub channel_type: ChannelType, pub channel_id: ChannelId, pub channel_name: String, } impl Invite { pub fn decode(value: Value) -> Result<Invite> { let mut value = try!(into_map(value)); let mut server = try!(remove(&mut value, "guild").and_then(into_map)); let server_id = try!(remove(&mut server, "id").and_then(ServerId::decode)); let server_name = try!(remove(&mut server, "name").and_then(into_string)); warn_field("Invite/guild", server); let mut channel = try!(remove(&mut value, "channel").and_then(into_map)); let channel_type = try!(remove(&mut channel, "type").and_then(ChannelType::decode)); let channel_id = try!(remove(&mut channel, "id").and_then(ChannelId::decode)); let channel_name = try!(remove(&mut channel, "name").and_then(into_string)); warn_field("Invite/channel", channel); warn_json!(value, Invite { code: try!(remove(&mut value, "code").and_then(into_string)), server_id: server_id, server_name: server_name, channel_type: channel_type, channel_id: channel_id, channel_name: channel_name, }) } } /// Detailed information about an invite, available to server managers #[derive(Debug, Clone)] pub struct RichInvite { pub code: String, pub server_icon: Option<String>, pub server_id: ServerId, pub server_name: String, pub server_splash_hash: Option<String>, pub channel_type: ChannelType, pub channel_id: ChannelId, pub channel_name: String, pub inviter: User, pub created_at: String, pub max_age: u64, pub max_uses: u64, pub temporary: bool, pub uses: u64, } impl RichInvite { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); let mut server = try!(remove(&mut value, "guild").and_then(into_map)); let server_icon_hash = try!(opt(&mut server, "icon", into_string)); let server_id = try!(remove(&mut server, "id").and_then(ServerId::decode)); let server_name = try!(remove(&mut server, "name").and_then(into_string)); let server_splash_hash = try!(opt(&mut server, "splash_hash", into_string)); warn_field("RichInvite/guild", server); let mut channel = try!(remove(&mut value, "channel").and_then(into_map)); let channel_type = try!(remove(&mut channel, "type").and_then(ChannelType::decode)); let channel_id = try!(remove(&mut channel, "id").and_then(ChannelId::decode)); let channel_name = try!(remove(&mut channel, "name").and_then(into_string)); warn_field("RichInvite/channel", channel); warn_json!(value, RichInvite { code: try!(remove(&mut value, "code").and_then(into_string)), server_icon: server_icon_hash, server_id: server_id, server_name: server_name, server_splash_hash: server_splash_hash, channel_type: channel_type, channel_id: channel_id, channel_name: channel_name, inviter: try!(remove(&mut value, "inviter").and_then(User::decode)), created_at: try!(remove(&mut value, "created_at").and_then(into_string)), max_age: req!(try!(remove(&mut value, "max_age")).as_u64()), max_uses: req!(try!(remove(&mut value, "max_uses")).as_u64()), temporary: req!(try!(remove(&mut value, "temporary")).as_bool()), uses: req!(try!(remove(&mut value, "uses")).as_u64()), }) } } /// Information about an available voice region #[derive(Debug, Clone)] pub struct VoiceRegion { pub id: String, pub name: String, pub sample_hostname: String, pub sample_port: u16, pub optimal: bool, pub vip: bool, } impl VoiceRegion { pub fn decode(value: Value) -> Result<VoiceRegion> { let mut value = try!(into_map(value)); warn_json!(value, VoiceRegion { id: try!(remove(&mut value, "id").and_then(into_string)), name: try!(remove(&mut value, "name").and_then(into_string)), sample_hostname: try!(remove(&mut value, "sample_hostname").and_then(into_string)), sample_port: req!(try!(remove(&mut value, "sample_port")).as_u64()) as u16, optimal: req!(try!(remove(&mut value, "optimal")).as_bool()), vip: req!(try!(remove(&mut value, "vip")).as_bool()), }) } } //================= // Event model /// Summary of messages since last login #[derive(Debug, Clone)] pub struct ReadState { /// Id of the relevant channel pub id: ChannelId, /// Last seen message in this channel pub last_message_id: Option<MessageId>, /// Mentions since that message in this channel pub mention_count: u64, } impl ReadState { pub fn decode(value: Value) -> Result<ReadState> { let mut value = try!(into_map(value)); warn_json!(value, ReadState { id: try!(remove(&mut value, "id").and_then(ChannelId::decode)), last_message_id: try!(opt(&mut value, "last_message_id", MessageId::decode)), mention_count: try!(opt(&mut value, "mention_count", |v| Ok(req!(v.as_u64())))).unwrap_or(0), }) } } /// A user's online presence status #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum OnlineStatus { DoNotDisturb, Invisible, Offline, Online, Idle, } map_names! { OnlineStatus; DoNotDisturb, "dnd"; Invisible, "invisible"; Offline, "offline"; Online, "online"; Idle, "idle"; } /// A type of game being played. #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum GameType { Playing, Streaming, } map_numbers! { GameType; Playing, 0; Streaming, 1; } /// Information about a game being played #[derive(Debug, Clone)] pub struct Game { pub name: String, pub url: Option<String>, pub kind: GameType, } impl Game { pub fn playing(name: String) -> Game { Game { kind: GameType::Playing, name: name, url: None } } pub fn streaming(name: String, url: String) -> Game { Game { kind: GameType::Streaming, name: name, url: Some(url) } } pub fn decode(value: Value) -> Result<Option<Game>> { let mut value = try!(into_map(value)); let name = match value.remove("name") { None | Some(Value::Null) => return Ok(None), Some(val) => try!(into_string(val)), }; if name.trim().is_empty() { return Ok(None) } warn_json!(@"Game", value, Some(Game { name: name, kind: try!(opt(&mut value, "type", GameType::decode)).unwrap_or(GameType::Playing), url: try!(opt(&mut value, "url", into_string)), })) } } /// A members's online status #[derive(Debug, Clone)] pub struct Presence { pub user_id: UserId, pub status: OnlineStatus, pub last_modified: Option<u64>, pub game: Option<Game>, pub user: Option<User>, pub nick: Option<String>, } impl Presence { pub fn decode(value: Value) -> Result<Presence> { let mut value = try!(into_map(value)); let mut user_map = try!(remove(&mut value, "user").and_then(into_map)); let (user_id, user) = if user_map.len() > 1 { let user = try!(User::decode(Value::Object(user_map))); (user.id, Some(user)) } else { (try!(remove(&mut user_map, "id").and_then(UserId::decode)), None) }; warn_json!(@"Presence", value, Presence { user_id: user_id, status: try!(remove(&mut value, "status").and_then(OnlineStatus::decode_str)), last_modified: try!(opt(&mut value, "last_modified", |v| Ok(req!(v.as_u64())))), game: match value.remove("game") { None | Some(Value::Null) => None, Some(val) => try!(Game::decode(val)), }, user: user, nick: try!(opt(&mut value, "nick", into_string)), }) } } /// A member's state within a voice channel #[derive(Debug, Clone)] pub struct VoiceState { pub user_id: UserId, pub channel_id: Option<ChannelId>, pub session_id: String, pub token: Option<String>, pub suppress: bool, pub self_mute: bool, pub self_deaf: bool, pub mute: bool, pub deaf: bool, } impl VoiceState { pub fn decode(value: Value) -> Result<VoiceState> { let mut value = try!(into_map(value)); warn_json!(value, VoiceState { user_id: try!(remove(&mut value, "user_id").and_then(UserId::decode)), channel_id: try!(opt(&mut value, "channel_id", ChannelId::decode)), session_id: try!(remove(&mut value, "session_id").and_then(into_string)), token: try!(opt(&mut value, "token", into_string)), suppress: req!(try!(remove(&mut value, "suppress")).as_bool()), self_mute: req!(try!(remove(&mut value, "self_mute")).as_bool()), self_deaf: req!(try!(remove(&mut value, "self_deaf")).as_bool()), mute: req!(try!(remove(&mut value, "mute")).as_bool()), deaf: req!(try!(remove(&mut value, "deaf")).as_bool()), }) } } /// A condition that new users must satisfy before posting in text channels #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum VerificationLevel { /// No verification is needed None, /// Must have a verified email on their Discord account Low, /// Must also be registered on Discord for longer than 5 minutes Medium, /// Must also be a member of this server for longer than 10 minutes High, } map_numbers! { VerificationLevel; None, 0; Low, 1; Medium, 2; High, 3; } /// A parter custom emoji #[derive(Debug, Clone)] pub struct Emoji { pub id: EmojiId, pub name: String, pub managed: bool, pub require_colons: bool, pub roles: Vec<RoleId>, } impl Emoji { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, Emoji { id: try!(remove(&mut value, "id").and_then(EmojiId::decode)), name: try!(remove(&mut value, "name").and_then(into_string)), managed: req!(try!(remove(&mut value, "managed")).as_bool()), require_colons: req!(try!(remove(&mut value, "require_colons")).as_bool()), roles: try!(remove(&mut value, "roles").and_then(|v| decode_array(v, RoleId::decode))), }) } } /// A full single reaction #[derive(Debug, Clone)] pub struct Reaction { pub channel_id: ChannelId, pub message_id: MessageId, pub user_id: UserId, pub emoji: ReactionEmoji, } impl Reaction { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, Reaction { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), emoji: try!(remove(&mut value, "emoji").and_then(ReactionEmoji::decode)), user_id: try!(remove(&mut value, "user_id").and_then(UserId::decode)), message_id: try!(remove(&mut value, "message_id").and_then(MessageId::decode)), }) } } /// Information on a reaction as available at a glance on a message. #[derive(Debug, Clone)] pub struct MessageReaction { pub count: u64, pub me: bool, pub emoji: ReactionEmoji, } impl MessageReaction { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, MessageReaction { emoji: try!(remove(&mut value, "emoji").and_then(ReactionEmoji::decode)), count: req!(try!(remove(&mut value, "count")).as_u64()), me: req!(try!(remove(&mut value, "me")).as_bool()), }) } } /// Emoji information sent only from reaction events #[derive(Debug, Clone)] pub enum ReactionEmoji { Unicode(String), Custom { name: String, id: EmojiId }, } impl ReactionEmoji { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); let name = try!(remove(&mut value, "name").and_then(into_string)); match try!(opt(&mut value, "id", EmojiId::decode)) { Some(id) => Ok(ReactionEmoji::Custom { name: name, id: id }), None => Ok(ReactionEmoji::Unicode(name)), } } } /// Live server information #[derive(Debug, Clone)] pub struct LiveServer { pub id: ServerId, pub name: String, pub owner_id: UserId, pub voice_states: Vec<VoiceState>, pub roles: Vec<Role>, pub region: String, pub presences: Vec<Presence>, pub member_count: u64, pub members: Vec<Member>, pub joined_at: String, pub icon: Option<String>, pub large: bool, pub channels: Vec<PublicChannel>, pub afk_timeout: u64, pub afk_channel_id: Option<ChannelId>, pub verification_level: VerificationLevel, pub emojis: Vec<Emoji>, pub features: Vec<String>, pub splash: Option<String>, pub default_message_notifications: u64, pub mfa_level: u64, } impl LiveServer { pub fn decode(value: Value) -> Result<LiveServer> { let mut value = try!(into_map(value)); let id = try!(remove(&mut value, "id").and_then(ServerId::decode)); warn_json!(value, LiveServer { name: try!(remove(&mut value, "name").and_then(into_string)), owner_id: try!(remove(&mut value, "owner_id").and_then(UserId::decode)), voice_states: try!(decode_array(try!(remove(&mut value, "voice_states")), VoiceState::decode)), roles: try!(decode_array(try!(remove(&mut value, "roles")), Role::decode)), region: try!(remove(&mut value, "region").and_then(into_string)), // these presences don't contain a whole User, so discard that presences: try!(decode_array(try!(remove(&mut value, "presences")), Presence::decode)), member_count: req!(try!(remove(&mut value, "member_count")).as_u64()), members: try!(decode_array(try!(remove(&mut value, "members")), Member::decode)), joined_at: try!(remove(&mut value, "joined_at").and_then(into_string)), icon: try!(opt(&mut value, "icon", into_string)), large: req!(try!(remove(&mut value, "large")).as_bool()), afk_timeout: req!(try!(remove(&mut value, "afk_timeout")).as_u64()), afk_channel_id: try!(opt(&mut value, "afk_channel_id", ChannelId::decode)), channels: try!(decode_array(try!(remove(&mut value, "channels")), |v| PublicChannel::decode_server(v, id.clone()))), verification_level: try!(remove(&mut value, "verification_level").and_then(VerificationLevel::decode)), emojis: try!(remove(&mut value, "emojis").and_then(|v| decode_array(v, Emoji::decode))), features: try!(remove(&mut value, "features").and_then(|v| decode_array(v, into_string))), splash: try!(opt(&mut value, "splash", into_string)), default_message_notifications: req!(try!(remove(&mut value, "default_message_notifications")).as_u64()), mfa_level: req!(try!(remove(&mut value, "mfa_level")).as_u64()), id: id, }) } /// Returns the formatted URL of the server's icon. /// /// Returns None if the server does not have an icon. pub fn icon_url(&self) -> Option<String> { self.icon.as_ref().map(|icon| format!(cdn_concat!("/icons/{}/{}.jpg"), self.id, icon)) } /// Calculate the effective permissions for a specific user in a specific /// channel on this server. pub fn permissions_for(&self, channel: ChannelId, user: UserId) -> Permissions { use self::permissions::*; // Owner has all permissions if user == self.owner_id { return Permissions::all(); } // OR together all the user's roles let everyone = match self.roles.iter().find(|r| r.id.0 == self.id.0) { Some(r) => r, None => { error!("Missing @everyone role in permissions lookup on {} ({})", self.name, self.id); return Permissions::empty(); } }; let mut permissions = everyone.permissions; let member = match self.members.iter().find(|u| u.user.id == user) { Some(u) => u, None => return everyone.permissions, }; for &role in &member.roles { if let Some(role) = self.roles.iter().find(|r| r.id == role) { permissions |= role.permissions; } else { warn!("perms: {:?} on {:?} has non-existent role {:?}", member.user.id, self.id, role); } } // Administrators have all permissions in any channel if permissions.contains(ADMINISTRATOR) { return Permissions::all(); } let mut text_channel = false; if let Some(channel) = self.channels.iter().find(|c| c.id == channel) { text_channel = channel.kind == ChannelType::Text; // Apply role overwrites, denied then allowed for overwrite in &channel.permission_overwrites { if let PermissionOverwriteType::Role(role) = overwrite.kind { // if the member has this role, or it is the @everyone role if member.roles.contains(&role) || role.0 == self.id.0 { permissions = (permissions & !overwrite.deny) | overwrite.allow; } } } // Apply member overwrites, denied then allowed for overwrite in &channel.permission_overwrites { if PermissionOverwriteType::Member(user) == overwrite.kind { permissions = (permissions & !overwrite.deny) | overwrite.allow; } } } else { warn!("perms: {:?} does not contain {:?}", self.id, channel); } // Default channel is always readable if channel.0 == self.id.0 { permissions |= READ_MESSAGES; } // No SEND_MESSAGES => no message-sending-related actions if !permissions.contains(SEND_MESSAGES) { permissions &= !(SEND_TTS_MESSAGES | MENTION_EVERYONE | EMBED_LINKS | ATTACH_FILES); } // No READ_MESSAGES => no channel actions if !permissions.contains(READ_MESSAGES) { permissions &= KICK_MEMBERS | BAN_MEMBERS | ADMINISTRATOR | MANAGE_SERVER | CHANGE_NICKNAMES | MANAGE_NICKNAMES; } // Text channel => no voice actions if text_channel { permissions &= !(VOICE_CONNECT | VOICE_SPEAK | VOICE_MUTE_MEMBERS | VOICE_DEAFEN_MEMBERS | VOICE_MOVE_MEMBERS | VOICE_USE_VAD); } permissions } } /// A server which may be unavailable #[derive(Debug, Clone)] pub enum PossibleServer<T> { /// An offline server, the ID of which is known Offline(ServerId), /// An online server, for which more information is available Online(T), } impl PossibleServer<LiveServer> { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); if remove(&mut value, "unavailable").ok().and_then(|v| v.as_bool()).unwrap_or(false) { remove(&mut value, "id").and_then(ServerId::decode).map(PossibleServer::Offline) } else { LiveServer::decode(Value::Object(value)).map(PossibleServer::Online) } } pub fn id(&self) -> ServerId { match *self { PossibleServer::Offline(id) => id, PossibleServer::Online(ref ls) => ls.id, } } } impl PossibleServer<Server> { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); if remove(&mut value, "unavailable").ok().and_then(|v| v.as_bool()).unwrap_or(false) { remove(&mut value, "id").and_then(ServerId::decode).map(PossibleServer::Offline) } else { Server::decode(Value::Object(value)).map(PossibleServer::Online) } } pub fn id(&self) -> ServerId { match *self {<|fim▁hole|> PossibleServer::Offline(id) => id, PossibleServer::Online(ref ls) => ls.id, } } } /// Information about the logged-in user #[derive(Debug, Clone)] pub struct CurrentUser { pub id: UserId, pub username: String, pub discriminator: u16, pub avatar: Option<String>, pub email: Option<String>, pub verified: bool, pub bot: bool, pub mfa_enabled: bool, } impl CurrentUser { pub fn decode(value: Value) -> Result<CurrentUser> { let mut value = try!(into_map(value)); warn_json!(value, CurrentUser { id: try!(remove(&mut value, "id").and_then(UserId::decode)), username: try!(remove(&mut value, "username").and_then(into_string)), discriminator: try!(remove(&mut value, "discriminator").and_then(decode_discriminator)), email: try!(opt(&mut value, "email", into_string)), avatar: try!(opt(&mut value, "avatar", into_string)), verified: req!(try!(remove(&mut value, "verified")).as_bool()), bot: try!(opt(&mut value, "bot", |v| Ok(req!(v.as_bool())))).unwrap_or(false), mfa_enabled: req!(try!(remove(&mut value, "mfa_enabled")).as_bool()), }) } } /// Information about the current application and the owner. #[derive(Debug, Clone)] pub struct ApplicationInfo { pub description: String, pub flags: u64, pub icon: Option<String>, pub id: UserId, pub name: String, pub rpc_origins: Vec<String>, pub owner: User, } impl ApplicationInfo { pub fn decode(value: Value) -> Result<ApplicationInfo> { let mut value = try!(into_map(value)); warn_json!(value, ApplicationInfo { description: try!(remove(&mut value, "description").and_then(into_string)), flags: req!(try!(remove(&mut value, "flags")).as_u64()), icon: try!(opt(&mut value, "icon", into_string)), id: try!(remove(&mut value, "id").and_then(UserId::decode)), name: try!(remove(&mut value, "name").and_then(into_string)), owner: try!(remove(&mut value, "owner").and_then(User::decode)), rpc_origins: try!(remove(&mut value, "rpc_origins").and_then(|v| decode_array(v, into_string))), }) } } /// A type of relationship this user has with another. #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum RelationshipType { Ignored, Friends, Blocked, IncomingRequest, OutgoingRequest, } impl RelationshipType { pub fn from_num(kind: u64) -> Option<Self> { match kind { 0 => Some(RelationshipType::Ignored), 1 => Some(RelationshipType::Friends), 2 => Some(RelationshipType::Blocked), 3 => Some(RelationshipType::IncomingRequest), 4 => Some(RelationshipType::OutgoingRequest), _ => None, } } fn decode(value: Value) -> Result<Self> { value.as_u64().and_then(RelationshipType::from_num).ok_or(Error::Decode("Expected valid RelationshipType", value)) } } /// Information on a friendship relationship this user has with another. #[derive(Debug, Clone)] pub struct Relationship { pub id: UserId, pub kind: RelationshipType, pub user: User, } impl Relationship { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, Relationship { id: try!(remove(&mut value, "id").and_then(UserId::decode)), kind: try!(remove(&mut value, "type").and_then(RelationshipType::decode)), user: try!(remove(&mut value, "user").and_then(User::decode)), }) } } /// Flags for who may add this user as a friend. #[derive(Debug, Clone)] pub struct FriendSourceFlags { pub all: bool, pub mutual_friends: bool, pub mutual_servers: bool, } impl FriendSourceFlags { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, FriendSourceFlags { all: try!(opt(&mut value, "all", |v| Ok(req!(v.as_bool())))).unwrap_or(false), mutual_friends: try!(opt(&mut value, "mutual_friends", |v| Ok(req!(v.as_bool())))).unwrap_or(false), mutual_servers: try!(opt(&mut value, "mutual_guilds", |v| Ok(req!(v.as_bool())))).unwrap_or(false), }) } } /// User settings usually used to influence client behavior #[derive(Debug, Clone)] pub struct UserSettings { pub detect_platform_accounts: bool, pub developer_mode: bool, pub enable_tts_command: bool, pub inline_attachment_media: bool, pub inline_embed_media: bool, pub locale: String, pub message_display_compact: bool, pub render_embeds: bool, pub server_positions: Vec<ServerId>, pub show_current_game: bool, pub status: String, pub theme: String, pub convert_emoticons: bool, pub friend_source_flags: FriendSourceFlags, /// Servers whose members cannot private message this user. pub restricted_servers: Vec<ServerId>, } impl UserSettings { pub fn decode(value: Value) -> Result<Option<UserSettings>> { let mut value = try!(into_map(value)); if value.is_empty() { return Ok(None) } warn_json!(value, UserSettings { detect_platform_accounts: req!(try!(remove(&mut value, "detect_platform_accounts")).as_bool()), developer_mode: req!(try!(remove(&mut value, "developer_mode")).as_bool()), enable_tts_command: req!(try!(remove(&mut value, "enable_tts_command")).as_bool()), inline_attachment_media: req!(try!(remove(&mut value, "inline_attachment_media")).as_bool()), inline_embed_media: req!(try!(remove(&mut value, "inline_embed_media")).as_bool()), locale: try!(remove(&mut value, "locale").and_then(into_string)), message_display_compact: req!(try!(remove(&mut value, "message_display_compact")).as_bool()), render_embeds: req!(try!(remove(&mut value, "render_embeds")).as_bool()), server_positions: try!(decode_array(try!(remove(&mut value, "guild_positions")), ServerId::decode)), show_current_game: req!(try!(remove(&mut value, "show_current_game")).as_bool()), status: try!(remove(&mut value, "status").and_then(into_string)), theme: try!(remove(&mut value, "theme").and_then(into_string)), convert_emoticons: req!(try!(remove(&mut value, "convert_emoticons")).as_bool()), friend_source_flags: try!(remove(&mut value, "friend_source_flags").and_then(FriendSourceFlags::decode)), restricted_servers: try!(remove(&mut value, "restricted_guilds").and_then(|v| decode_array(v, ServerId::decode))), }).map(Some) } } /// Notification level for a channel or server #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum NotificationLevel { /// All messages trigger a notification All, /// Only @mentions trigger a notification Mentions, /// No messages, even @mentions, trigger a notification Nothing, /// Follow the parent's notification level Parent, } map_numbers! { NotificationLevel; All, 0; Mentions, 1; Nothing, 2; Parent, 3; } /// A channel-specific notification settings override #[derive(Debug, Clone)] pub struct ChannelOverride { pub channel_id: ChannelId, pub message_notifications: NotificationLevel, pub muted: bool, } impl ChannelOverride { pub fn decode(value: Value) -> Result<ChannelOverride> { let mut value = try!(into_map(value)); warn_json!(value, ChannelOverride { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), message_notifications: try!(remove(&mut value, "message_notifications").and_then(NotificationLevel::decode)), muted: req!(try!(remove(&mut value, "muted")).as_bool()), }) } } /// User settings which influence per-server notification behavior #[derive(Debug, Clone)] pub struct UserServerSettings { pub server_id: Option<ServerId>, pub message_notifications: NotificationLevel, pub mobile_push: bool, pub muted: bool, pub suppress_everyone: bool, pub channel_overrides: Vec<ChannelOverride>, } impl UserServerSettings { pub fn decode(value: Value) -> Result<UserServerSettings> { let mut value = try!(into_map(value)); warn_json!(value, UserServerSettings { server_id: try!(opt(&mut value, "guild_id", ServerId::decode)), message_notifications: try!(remove(&mut value, "message_notifications").and_then(NotificationLevel::decode)), mobile_push: req!(try!(remove(&mut value, "mobile_push")).as_bool()), muted: req!(try!(remove(&mut value, "muted")).as_bool()), suppress_everyone: req!(try!(remove(&mut value, "suppress_everyone")).as_bool()), channel_overrides: try!(remove(&mut value, "channel_overrides").and_then(|v| decode_array(v, ChannelOverride::decode))), }) } } /// Progress through the Discord tutorial #[derive(Debug, Clone)] pub struct Tutorial { pub indicators_suppressed: bool, pub indicators_confirmed: Vec<String>, } impl Tutorial { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, Tutorial { indicators_suppressed: req!(try!(remove(&mut value, "indicators_suppressed")).as_bool()), indicators_confirmed: try!(remove(&mut value, "indicators_confirmed").and_then(|v| decode_array(v, into_string))), }) } } /// Discord status maintenance message. /// /// This can be either for active maintenances or scheduled maintenances. #[derive(Debug, Clone)] pub struct Maintenance { pub description: String, pub id: String, pub name: String, pub start: String, pub stop: String, } impl Maintenance { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, Maintenance { description: try!(remove(&mut value, "description").and_then(into_string)), id: try!(remove(&mut value, "id").and_then(into_string)), name: try!(remove(&mut value, "name").and_then(into_string)), start: try!(remove(&mut value, "start").and_then(into_string)), stop: try!(remove(&mut value, "stop").and_then(into_string)), }) } } /// An incident retrieved from the Discord status page. #[derive(Debug, Clone)] pub struct Incident { pub id: String, pub impact: String, pub monitoring_at: Option<String>, pub name: String, pub page_id: String, pub short_link: String, pub status: String, pub incident_updates: Vec<IncidentUpdate>, pub created_at: String, pub resolved_at: Option<String>, pub updated_at: String, } impl Incident { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, Incident { id: try!(remove(&mut value, "id").and_then(into_string)), impact: try!(remove(&mut value, "impact").and_then(into_string)), monitoring_at: try!(opt(&mut value, "monitoring_at", into_string)), name: try!(remove(&mut value, "name").and_then(into_string)), page_id: try!(remove(&mut value, "page_id").and_then(into_string)), short_link: try!(remove(&mut value, "shortlink").and_then(into_string)), status: try!(remove(&mut value, "status").and_then(into_string)), incident_updates: try!(decode_array(try!(remove(&mut value, "incident_updates")), IncidentUpdate::decode)), created_at: try!(remove(&mut value, "created_at").and_then(into_string)), resolved_at: try!(opt(&mut value, "resolved_at", into_string)), updated_at: try!(remove(&mut value, "updated_at").and_then(into_string)), }) } } /// An update to an incident from the Discord status page. This will typically /// state what new information has been discovered about an incident. #[derive(Debug, Clone)] pub struct IncidentUpdate { pub body: String, pub id: String, pub incident_id: String, pub status: String, pub affected_components: Vec<Value>, pub created_at: String, pub display_at: String, pub updated_at: String, } impl IncidentUpdate { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); warn_json!(value, IncidentUpdate { body: try!(remove(&mut value, "body").and_then(into_string)), id: try!(remove(&mut value, "id").and_then(into_string)), incident_id: try!(remove(&mut value, "incident_id").and_then(into_string)), status: try!(remove(&mut value, "status").and_then(into_string)), affected_components: try!(decode_array(try!(remove(&mut value, "affected_components")), Ok)), created_at: try!(remove(&mut value, "created_at").and_then(into_string)), display_at: try!(remove(&mut value, "display_at").and_then(into_string)), updated_at: try!(remove(&mut value, "updated_at").and_then(into_string)), }) } } /// The "Ready" event, containing initial state #[derive(Debug, Clone)] pub struct ReadyEvent { pub version: u64, pub user: CurrentUser, pub session_id: String, pub user_settings: Option<UserSettings>, pub read_state: Option<Vec<ReadState>>, pub private_channels: Vec<Channel>, pub presences: Vec<Presence>, pub relationships: Vec<Relationship>, pub servers: Vec<PossibleServer<LiveServer>>, pub user_server_settings: Option<Vec<UserServerSettings>>, pub tutorial: Option<Tutorial>, /// The trace of servers involved in this connection. pub trace: Vec<Option<String>>, pub notes: Option<BTreeMap<UserId, String>>, /// The shard info for this session; the shard id used and the total number /// of shards. pub shard: Option<[u8; 2]>, } /// Event received over a websocket connection #[derive(Debug, Clone)] pub enum Event { /// The first event in a connection, containing the initial state. /// /// May also be received at a later time in the event of a reconnect. Ready(ReadyEvent), /// The connection has successfully resumed after a disconnect. Resumed { heartbeat_interval: u64, trace: Vec<Option<String>>, }, /// Update to the logged-in user's information UserUpdate(CurrentUser), /// Update to a note that the logged-in user has set for another user. UserNoteUpdate(UserId, String), /// Update to the logged-in user's preferences or client settings UserSettingsUpdate { detect_platform_accounts: Option<bool>, developer_mode: Option<bool>, enable_tts_command: Option<bool>, inline_attachment_media: Option<bool>, inline_embed_media: Option<bool>, locale: Option<String>, message_display_compact: Option<bool>, render_embeds: Option<bool>, server_positions: Option<Vec<ServerId>>, show_current_game: Option<bool>, status: Option<String>, theme: Option<String>, convert_emoticons: Option<bool>, friend_source_flags: Option<FriendSourceFlags>, }, /// Update to the logged-in user's server-specific notification settings UserServerSettingsUpdate(UserServerSettings), /// A member's voice state has changed VoiceStateUpdate(Option<ServerId>, VoiceState), /// Voice server information is available VoiceServerUpdate { server_id: Option<ServerId>, channel_id: Option<ChannelId>, endpoint: Option<String>, token: String, }, /// A new group call has been created CallCreate(Call), /// A group call has been updated CallUpdate { channel_id: ChannelId, message_id: MessageId, region: String, ringing: Vec<UserId>, }, /// A group call has been deleted (the call ended) CallDelete(ChannelId), /// A user has been added to a group ChannelRecipientAdd(ChannelId, User), /// A user has been removed from a group ChannelRecipientRemove(ChannelId, User), /// A user is typing; considered to last 5 seconds TypingStart { channel_id: ChannelId, user_id: UserId, timestamp: u64, }, /// A member's presence state (or username or avatar) has changed PresenceUpdate { presence: Presence, server_id: Option<ServerId>, roles: Option<Vec<RoleId>>, }, /// The precense list of the user's friends should be replaced entirely PresencesReplace(Vec<Presence>), RelationshipAdd(Relationship), RelationshipRemove(UserId, RelationshipType), MessageCreate(Message), /// A message has been edited, either by the user or the system MessageUpdate { id: MessageId, channel_id: ChannelId, kind: Option<MessageType>, content: Option<String>, nonce: Option<String>, tts: Option<bool>, pinned: Option<bool>, timestamp: Option<String>, edited_timestamp: Option<String>, author: Option<User>, mention_everyone: Option<bool>, mentions: Option<Vec<User>>, mention_roles: Option<Vec<RoleId>>, attachments: Option<Vec<Attachment>>, embeds: Option<Vec<Value>>, }, /// Another logged-in device acknowledged this message MessageAck { channel_id: ChannelId, /// May be `None` if a private channel with no messages has closed. message_id: Option<MessageId>, }, MessageDelete { channel_id: ChannelId, message_id: MessageId, }, MessageDeleteBulk { channel_id: ChannelId, ids: Vec<MessageId>, }, ServerCreate(PossibleServer<LiveServer>), ServerUpdate(Server), ServerDelete(PossibleServer<Server>), ServerMemberAdd(ServerId, Member), /// A member's roles have changed ServerMemberUpdate { server_id: ServerId, roles: Vec<RoleId>, user: User, nick: Option<String>, }, ServerMemberRemove(ServerId, User), ServerMembersChunk(ServerId, Vec<Member>), ServerSync { server_id: ServerId, large: bool, members: Vec<Member>, presences: Vec<Presence>, }, ServerRoleCreate(ServerId, Role), ServerRoleUpdate(ServerId, Role), ServerRoleDelete(ServerId, RoleId), ServerBanAdd(ServerId, User), ServerBanRemove(ServerId, User), ServerIntegrationsUpdate(ServerId), ServerEmojisUpdate(ServerId, Vec<Emoji>), ChannelCreate(Channel), ChannelUpdate(Channel), ChannelDelete(Channel), ChannelPinsAck { channel_id: ChannelId, timestamp: String, }, ChannelPinsUpdate { channel_id: ChannelId, last_pin_timestamp: Option<String>, }, ReactionAdd(Reaction), ReactionRemove(Reaction), /// An event type not covered by the above Unknown(String, BTreeMap<String, Value>), // Any other event. Should never be used directly. #[doc(hidden)] __Nonexhaustive, } impl Event { fn decode(kind: String, value: Value) -> Result<Event> { if kind == "PRESENCES_REPLACE" { return decode_array(value, Presence::decode).map(Event::PresencesReplace); } let mut value = try!(into_map(value)); if kind == "READY" { warn_json!(@"Event::Ready", value, Event::Ready(ReadyEvent { version: req!(try!(remove(&mut value, "v")).as_u64()), user: try!(remove(&mut value, "user").and_then(CurrentUser::decode)), session_id: try!(remove(&mut value, "session_id").and_then(into_string)), read_state: try!(opt(&mut value, "read_state", |v| decode_array(v, ReadState::decode))), private_channels: try!(decode_array(try!(remove(&mut value, "private_channels")), Channel::decode)), presences: try!(decode_array(try!(remove(&mut value, "presences")), Presence::decode)), relationships: try!(remove(&mut value, "relationships").and_then(|v| decode_array(v, Relationship::decode))), servers: try!(decode_array(try!(remove(&mut value, "guilds")), PossibleServer::<LiveServer>::decode)), user_settings: try!(opt(&mut value, "user_settings", UserSettings::decode)).and_then(|x| x), user_server_settings: try!(opt(&mut value, "user_guild_settings", |v| decode_array(v, UserServerSettings::decode))), tutorial: try!(opt(&mut value, "tutorial", Tutorial::decode)), notes: try!(opt(&mut value, "notes", decode_notes)), trace: try!(remove(&mut value, "_trace").and_then(|v| decode_array(v, |v| Ok(into_string(v).ok())))), shard: try!(opt(&mut value, "shard", decode_shards)), })) } else if kind == "RESUMED" { warn_json!(value, Event::Resumed { heartbeat_interval: req!(try!(remove(&mut value, "heartbeat_interval")).as_u64()), trace: try!(remove(&mut value, "_trace").and_then(|v| decode_array(v, |v| Ok(into_string(v).ok())))), }) } else if kind == "USER_UPDATE" { CurrentUser::decode(Value::Object(value)).map(Event::UserUpdate) } else if kind == "USER_NOTE_UPDATE" { warn_json!(value, Event::UserNoteUpdate( try!(remove(&mut value, "id").and_then(UserId::decode)), try!(remove(&mut value, "note").and_then(into_string)), )) } else if kind == "USER_SETTINGS_UPDATE" { warn_json!(value, Event::UserSettingsUpdate { detect_platform_accounts: remove(&mut value, "detect_platform_accounts").ok().and_then(|v| v.as_bool()), developer_mode: remove(&mut value, "developer_mode").ok().and_then(|v| v.as_bool()), enable_tts_command: remove(&mut value, "enable_tts_command").ok().and_then(|v| v.as_bool()), inline_attachment_media: remove(&mut value, "inline_attachment_media").ok().and_then(|v| v.as_bool()), inline_embed_media: remove(&mut value, "inline_embed_media").ok().and_then(|v| v.as_bool()), locale: try!(opt(&mut value, "locale", into_string)), message_display_compact: remove(&mut value, "message_display_compact").ok().and_then(|v| v.as_bool()), render_embeds: remove(&mut value, "render_embeds").ok().and_then(|v| v.as_bool()), server_positions: try!(opt(&mut value, "guild_positions", |v| decode_array(v, ServerId::decode))), show_current_game: remove(&mut value, "show_current_game").ok().and_then(|v| v.as_bool()), status: try!(opt(&mut value, "status", into_string)), theme: try!(opt(&mut value, "theme", into_string)), convert_emoticons: remove(&mut value, "convert_emoticons").ok().and_then(|v| v.as_bool()), friend_source_flags: try!(opt(&mut value, "friend_source_flags", FriendSourceFlags::decode)), }) } else if kind == "USER_GUILD_SETTINGS_UPDATE" { UserServerSettings::decode(Value::Object(value)).map(Event::UserServerSettingsUpdate) } else if kind == "VOICE_STATE_UPDATE" { let server_id = try!(opt(&mut value, "guild_id", ServerId::decode)); Ok(Event::VoiceStateUpdate(server_id, try!(VoiceState::decode(Value::Object(value))))) } else if kind == "VOICE_SERVER_UPDATE" { warn_json!(value, Event::VoiceServerUpdate { server_id: try!(opt(&mut value, "guild_id", ServerId::decode)), channel_id: try!(opt(&mut value, "channel_id", ChannelId::decode)), endpoint: try!(opt(&mut value, "endpoint", into_string)), token: try!(remove(&mut value, "token").and_then(into_string)), }) } else if kind == "CALL_CREATE" { Ok(Event::CallCreate(try!(Call::decode(Value::Object(value))))) } else if kind == "CALL_DELETE" { Ok(Event::CallDelete(try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)))) } else if kind == "CALL_UPDATE" { warn_json!(value, Event::CallUpdate { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), message_id: try!(remove(&mut value, "message_id").and_then(MessageId::decode)), region: try!(remove(&mut value, "region").and_then(into_string)), ringing: try!(decode_array(try!(remove(&mut value, "ringing")), UserId::decode)), }) } else if kind == "CHANNEL_RECIPIENT_ADD" { let channel_id = try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)); let user = try!(remove(&mut value, "user").and_then(User::decode)); Ok(Event::ChannelRecipientAdd(channel_id, user)) } else if kind == "CHANNEL_RECIPIENT_REMOVE" { let channel_id = try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)); let user = try!(remove(&mut value, "user").and_then(User::decode)); Ok(Event::ChannelRecipientRemove(channel_id, user)) } else if kind == "TYPING_START" { warn_json!(value, Event::TypingStart { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), user_id: try!(remove(&mut value, "user_id").and_then(UserId::decode)), timestamp: req!(try!(remove(&mut value, "timestamp")).as_u64()), }) } else if kind == "PRESENCE_UPDATE" { let server_id = try!(opt(&mut value, "guild_id", ServerId::decode)); let roles = try!(opt(&mut value, "roles", |v| decode_array(v, RoleId::decode))); let presence = try!(Presence::decode(Value::Object(value))); Ok(Event::PresenceUpdate { server_id: server_id, roles: roles, presence: presence, }) } else if kind == "RELATIONSHIP_ADD" { Relationship::decode(Value::Object(value)).map(Event::RelationshipAdd) } else if kind == "RELATIONSHIP_REMOVE" { warn_json!(value, Event::RelationshipRemove( try!(remove(&mut value, "id").and_then(UserId::decode)), try!(remove(&mut value, "type").and_then(RelationshipType::decode)), )) } else if kind == "MESSAGE_REACTION_ADD" { Reaction::decode(Value::Object(value)).map(Event::ReactionAdd) } else if kind == "MESSAGE_REACTION_REMOVE" { Reaction::decode(Value::Object(value)).map(Event::ReactionRemove) } else if kind == "MESSAGE_CREATE" { Message::decode(Value::Object(value)).map(Event::MessageCreate) } else if kind == "MESSAGE_UPDATE" { warn_json!(value, Event::MessageUpdate { id: try!(remove(&mut value, "id").and_then(MessageId::decode)), channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), kind: try!(opt(&mut value, "type", MessageType::decode)), content: try!(opt(&mut value, "content", into_string)), nonce: remove(&mut value, "nonce").and_then(into_string).ok(), // nb: swallow errors tts: remove(&mut value, "tts").ok().and_then(|v| v.as_bool()), pinned: remove(&mut value, "pinned").ok().and_then(|v| v.as_bool()), timestamp: try!(opt(&mut value, "timestamp", into_string)), edited_timestamp: try!(opt(&mut value, "edited_timestamp", into_string)), author: try!(opt(&mut value, "author", User::decode)), mention_everyone: remove(&mut value, "mention_everyone").ok().and_then(|v| v.as_bool()), mentions: try!(opt(&mut value, "mentions", |v| decode_array(v, User::decode))), mention_roles: try!(opt(&mut value, "mention_roles", |v| decode_array(v, RoleId::decode))), attachments: try!(opt(&mut value, "attachments", |v| decode_array(v, Attachment::decode))), embeds: try!(opt(&mut value, "embeds", |v| decode_array(v, Ok))), }) } else if kind == "MESSAGE_ACK" { warn_json!(value, Event::MessageAck { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), message_id: try!(opt(&mut value, "message_id", MessageId::decode)), }) } else if kind == "MESSAGE_DELETE" { warn_json!(value, Event::MessageDelete { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), message_id: try!(remove(&mut value, "id").and_then(MessageId::decode)), }) } else if kind == "MESSAGE_DELETE_BULK" { warn_json!(value, Event::MessageDeleteBulk { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), ids: try!(decode_array(try!(remove(&mut value, "ids")), MessageId::decode)), }) } else if kind == "GUILD_CREATE" { PossibleServer::<LiveServer>::decode(Value::Object(value)).map(Event::ServerCreate) } else if kind == "GUILD_UPDATE" { Server::decode(Value::Object(value)).map(Event::ServerUpdate) } else if kind == "GUILD_DELETE" { PossibleServer::<Server>::decode(Value::Object(value)).map(Event::ServerDelete) } else if kind == "GUILD_MEMBER_ADD" { Ok(Event::ServerMemberAdd( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(Member::decode(Value::Object(value))), )) } else if kind == "GUILD_MEMBER_UPDATE" { warn_json!(value, Event::ServerMemberUpdate { server_id: try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), roles: try!(decode_array(try!(remove(&mut value, "roles")), RoleId::decode)), user: try!(remove(&mut value, "user").and_then(User::decode)), nick: try!(opt(&mut value, "nick", into_string)), }) } else if kind == "GUILD_MEMBER_REMOVE" { warn_json!(value, Event::ServerMemberRemove( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "user").and_then(User::decode)), )) } else if kind == "GUILD_MEMBERS_CHUNK" { warn_json!(value, Event::ServerMembersChunk( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "members").and_then(|v| decode_array(v, Member::decode))), )) } else if kind == "GUILD_SYNC" { warn_json!(value, Event::ServerSync { server_id: try!(remove(&mut value, "id").and_then(ServerId::decode)), large: req!(try!(remove(&mut value, "large")).as_bool()), members: try!(remove(&mut value, "members").and_then(|v| decode_array(v, Member::decode))), presences: try!(decode_array(try!(remove(&mut value, "presences")), Presence::decode)), }) } else if kind == "GUILD_ROLE_CREATE" { warn_json!(value, Event::ServerRoleCreate( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "role").and_then(Role::decode)), )) } else if kind == "GUILD_ROLE_UPDATE" { warn_json!(value, Event::ServerRoleUpdate( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "role").and_then(Role::decode)), )) } else if kind == "GUILD_ROLE_DELETE" { warn_json!(value, Event::ServerRoleDelete( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "role_id").and_then(RoleId::decode)), )) } else if kind == "GUILD_BAN_ADD" { warn_json!(value, Event::ServerBanAdd( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "user").and_then(User::decode)), )) } else if kind == "GUILD_BAN_REMOVE" { warn_json!(value, Event::ServerBanRemove( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "user").and_then(User::decode)), )) } else if kind == "GUILD_INTEGRATIONS_UPDATE" { warn_json!(value, Event::ServerIntegrationsUpdate( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), )) } else if kind == "GUILD_EMOJIS_UPDATE" { warn_json!(value, Event::ServerEmojisUpdate( try!(remove(&mut value, "guild_id").and_then(ServerId::decode)), try!(remove(&mut value, "emojis").and_then(|v| decode_array(v, Emoji::decode))), )) } else if kind == "CHANNEL_CREATE" { Channel::decode(Value::Object(value)).map(Event::ChannelCreate) } else if kind == "CHANNEL_UPDATE" { Channel::decode(Value::Object(value)).map(Event::ChannelUpdate) } else if kind == "CHANNEL_DELETE" { Channel::decode(Value::Object(value)).map(Event::ChannelDelete) } else if kind == "CHANNEL_PINS_ACK" { warn_json!(value, Event::ChannelPinsAck { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), timestamp: try!(remove(&mut value, "timestamp").and_then(into_string)), }) } else if kind == "CHANNEL_PINS_UPDATE" { warn_json!(value, Event::ChannelPinsUpdate { channel_id: try!(remove(&mut value, "channel_id").and_then(ChannelId::decode)), last_pin_timestamp: try!(opt(&mut value, "last_pin_timestamp", into_string)), }) } else { Ok(Event::Unknown(kind, value)) } } } #[doc(hidden)] #[derive(Debug, Clone)] pub enum GatewayEvent { Dispatch(u64, Event), Heartbeat(u64), Reconnect, InvalidateSession, Hello(u64), HeartbeatAck, } impl GatewayEvent { pub fn decode(value: Value) -> Result<Self> { let mut value = try!(into_map(value)); match req!(value.get("op").and_then(|x| x.as_u64())) { 0 => Ok(GatewayEvent::Dispatch( req!(try!(remove(&mut value, "s")).as_u64()), try!(Event::decode( try!(remove(&mut value, "t").and_then(into_string)), try!(remove(&mut value, "d")) )) )), 1 => Ok(GatewayEvent::Heartbeat(req!(try!(remove(&mut value, "s")).as_u64()))), 7 => Ok(GatewayEvent::Reconnect), 9 => Ok(GatewayEvent::InvalidateSession), 10 => { let mut data = try!(remove(&mut value, "d").and_then(into_map)); let interval = req!(try!(remove(&mut data, "heartbeat_interval")).as_u64()); Ok(GatewayEvent::Hello(interval)) }, 11 => Ok(GatewayEvent::HeartbeatAck), _ => Err(Error::Decode("Unexpected opcode", Value::Object(value))), } } } //================= // Voice event model #[doc(hidden)] #[derive(Debug, Clone)] pub enum VoiceEvent { Heartbeat { heartbeat_interval: u64, }, Handshake { heartbeat_interval: u64, port: u16, ssrc: u32, modes: Vec<String>, ip: Option<String>, }, Ready { mode: String, secret_key: Vec<u8>, }, SpeakingUpdate { user_id: UserId, ssrc: u32, speaking: bool, }, KeepAlive, Unknown(u64, Value) } impl VoiceEvent { pub fn decode(value: Value) -> Result<VoiceEvent> { let mut value = try!(into_map(value)); let op = req!(try!(remove(&mut value, "op")).as_u64()); if op == 3 { return Ok(VoiceEvent::KeepAlive) } let mut value = try!(remove(&mut value, "d").and_then(into_map)); if op == 2 { warn_json!(value, VoiceEvent::Handshake { heartbeat_interval: req!(try!(remove(&mut value, "heartbeat_interval")).as_u64()), modes: try!(decode_array(try!(remove(&mut value, "modes")), into_string)), port: req!(try!(remove(&mut value, "port")).as_u64()) as u16, ssrc: req!(try!(remove(&mut value, "ssrc")).as_u64()) as u32, ip: try!(opt(&mut value, "ip", into_string)), }) } else if op == 4 { warn_json!(value, VoiceEvent::Ready { mode: try!(remove(&mut value, "mode").and_then(into_string)), secret_key: try!(decode_array(try!(remove(&mut value, "secret_key")), |v| Ok(req!(v.as_u64()) as u8) )), }) } else if op == 5 { warn_json!(value, VoiceEvent::SpeakingUpdate { user_id: try!(remove(&mut value, "user_id").and_then(UserId::decode)), ssrc: req!(try!(remove(&mut value, "ssrc")).as_u64()) as u32, speaking: req!(try!(remove(&mut value, "speaking")).as_bool()), }) } else if op == 8 { warn_json!(value, VoiceEvent::Heartbeat { heartbeat_interval: req!(try!(remove(&mut value, "heartbeat_interval")).as_u64()), }) } else { Ok(VoiceEvent::Unknown(op, Value::Object(value))) } } } //================= // Decode helpers fn remove(map: &mut BTreeMap<String, Value>, key: &str) -> Result<Value> { map.remove(key).ok_or_else(|| Error::Decode("Unexpected absent key", Value::String(key.into()))) } fn opt<T, F: FnOnce(Value) -> Result<T>>(map: &mut BTreeMap<String, Value>, key: &str, f: F) -> Result<Option<T>> { match map.remove(key) { None | Some(Value::Null) => Ok(None), Some(val) => f(val).map(Some), } } fn decode_discriminator(value: Value) -> Result<u16> { match value { Value::I64(v) => Ok(v as u16), Value::U64(v) => Ok(v as u16), Value::String(s) => s.parse::<u16>().or(Err(Error::Other("Error parsing discriminator as u16"))), value => Err(Error::Decode("Expected string or u64", value)), } } fn decode_notes(value: Value) -> Result<BTreeMap<UserId, String>> { // turn the String -> Value map into a UserId -> String map try!(into_map(value)).into_iter().map(|(key, value)| Ok(( /* key */ UserId(try!(key.parse::<u64>().map_err(|_| Error::Other("Invalid user id in notes")))), /* val */ try!(into_string(value)) ))).collect() } fn decode_shards(value: Value) -> Result<[u8; 2]> { let array = try!(into_array(value)); Ok([ req!(try!(array.get(0).ok_or(Error::Other("Expected shard number"))).as_u64()) as u8, req!(try!(array.get(1).ok_or(Error::Other("Expected total shard number"))).as_u64()) as u8 ]) } fn into_string(value: Value) -> Result<String> { match value { Value::String(s) => Ok(s), value => Err(Error::Decode("Expected string", value)), } } fn into_array(value: Value) -> Result<Vec<Value>> { match value { Value::Array(v) => Ok(v), value => Err(Error::Decode("Expected array", value)), } } fn into_map(value: Value) -> Result<BTreeMap<String, Value>> { match value { Value::Object(m) => Ok(m), value => Err(Error::Decode("Expected object", value)), } } #[doc(hidden)] pub fn decode_array<T, F: Fn(Value) -> Result<T>>(value: Value, f: F) -> Result<Vec<T>> { into_array(value).and_then(|x| x.into_iter().map(f).collect()) } fn warn_field(name: &str, map: BTreeMap<String, Value>) { if !map.is_empty() { debug!("Unhandled keys: {} has {:?}", name, Value::Object(map)) } }<|fim▁end|>
<|file_name|>dataschema-text.js<|end_file_name|><|fim▁begin|>/** * Provides a DataSchema implementation which can be used to work with * delimited text data. * * @module dataschema * @submodule dataschema-text */ /** Provides a DataSchema implementation which can be used to work with delimited text data. See the `apply` method for usage. @class DataSchema.Text @extends DataSchema.Base @static **/ var Lang = Y.Lang, isString = Lang.isString, isUndef = Lang.isUndefined, SchemaText = { //////////////////////////////////////////////////////////////////////// // // DataSchema.Text static methods // //////////////////////////////////////////////////////////////////////// /** Applies a schema to a string of delimited data, returning a normalized object with results in the `results` property. The `meta` property of the response object is present for consistency, but is assigned an empty object. If the input data is absent or not a string, an `error` property will be added. Use _schema.resultDelimiter_ and _schema.fieldDelimiter_ to instruct `apply` how to split up the string into an array of data arrays for processing. Use _schema.resultFields_ to specify the keys in the generated result objects in `response.results`. The key:value pairs will be assigned in the order of the _schema.resultFields_ array, assuming the values in the data records are defined in the same order. _schema.resultFields_ field identifiers are objects with the following properties: * `key` : <strong>(required)</strong> The property name you want the data value assigned to in the result object (String) * `parser`: A function or the name of a function on `Y.Parsers` used to convert the input value into a normalized type. Parser functions are passed the value as input and are expected to return a value. If no value parsing is needed, you can use just the desired property name string as the field identifier instead of an object (see example below).<|fim▁hole|> resultDelimiter: "\n", fieldDelimiter: ",", resultFields: [ 'fruit', 'color' ] }, data = "Banana,yellow\nOrange,orange\nEggplant,purple"; var response = Y.DataSchema.Text.apply(schema, data); // response.results[0] is { fruit: "Banana", color: "yellow" } // Use parsers schema.resultFields = [ { key: 'fruit', parser: function (val) { return val.toUpperCase(); } }, 'color' // mix and match objects and strings ]; response = Y.DataSchema.Text.apply(schema, data); // response.results[0] is { fruit: "BANANA", color: "yellow" } @method apply @param {Object} schema Schema to apply. Supported configuration properties are: @param {String} schema.resultDelimiter Character or character sequence that marks the end of one record and the start of another. @param {String} [schema.fieldDelimiter] Character or character sequence that marks the end of a field and the start of another within the same record. @param {Array} [schema.resultFields] Field identifiers to assign values in the response records. See above for details. @param {String} data Text data. @return {Object} An Object with properties `results` and `meta` @static **/ apply: function(schema, data) { var data_in = data, data_out = { results: [], meta: {} }; if (isString(data) && schema && isString(schema.resultDelimiter)) { // Parse results data data_out = SchemaText._parseResults.call(this, schema, data_in, data_out); } else { Y.log("Text data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-text"); data_out.error = new Error("Text schema parse failure"); } return data_out; }, /** * Schema-parsed list of results from full data * * @method _parseResults * @param schema {Array} Schema to parse against. * @param text_in {String} Text to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Parsed data object. * @static * @protected */ _parseResults: function(schema, text_in, data_out) { var resultDelim = schema.resultDelimiter, fieldDelim = isString(schema.fieldDelimiter) && schema.fieldDelimiter, fields = schema.resultFields || [], results = [], parse = Y.DataSchema.Base.parse, results_in, fields_in, result, item, field, key, value, i, j; // Delete final delimiter at end of string if there if (text_in.slice(-resultDelim.length) === resultDelim) { text_in = text_in.slice(0, -resultDelim.length); } // Split into results results_in = text_in.split(schema.resultDelimiter); if (fieldDelim) { for (i = results_in.length - 1; i >= 0; --i) { result = {}; item = results_in[i]; fields_in = item.split(schema.fieldDelimiter); for (j = fields.length - 1; j >= 0; --j) { field = fields[j]; key = (!isUndef(field.key)) ? field.key : field; // FIXME: unless the key is an array index, this test // for fields_in[key] is useless. value = (!isUndef(fields_in[key])) ? fields_in[key] : fields_in[j]; result[key] = parse.call(this, value, field); } results[i] = result; } } else { results = results_in; } data_out.results = results; return data_out; } }; Y.DataSchema.Text = Y.mix(SchemaText, Y.DataSchema.Base);<|fim▁end|>
@example // Process simple csv var schema = {
<|file_name|>EQSANSFlatTestAPIv2.py<|end_file_name|><|fim▁begin|># Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + #pylint: disable=no-init,attribute-defined-outside-init import systemtesting from mantid.simpleapi import * from reduction_workflow.instruments.sans.sns_command_interface import * from reduction_workflow.instruments.sans.hfir_command_interface import * FILE_LOCATION = "/SNS/EQSANS/IPTS-5636/data/" <|fim▁hole|> files.append(FILE_LOCATION+"EQSANS_5704_event.nxs") files.append(FILE_LOCATION+"EQSANS_5734_event.nxs") files.append(FILE_LOCATION+"EQSANS_5732_event.nxs") files.append(FILE_LOCATION+"EQSANS_5738_event.nxs") files.append(FILE_LOCATION+"EQSANS_5729_event.nxs") files.append(FILE_LOCATION+"EQSANS_5737_event.nxs") files.append(FILE_LOCATION+"EQSANS_5703_event.nxs") files.append("bl6_flux_at_sample") return files def runTest(self): """ System test for EQSANS. This test is meant to be run at SNS and takes a long time. It is used to verify that the complete reduction chain works and reproduces reference results. """ configI = ConfigService.Instance() configI["facilityName"]='SNS' EQSANS() SolidAngle() DarkCurrent(FILE_LOCATION+"EQSANS_5704_event.nxs") TotalChargeNormalization(beam_file="bl6_flux_at_sample") AzimuthalAverage(n_bins=100, n_subpix=1, log_binning=False) IQxQy(nbins=100) UseConfigTOFTailsCutoff(True) PerformFlightPathCorrection(True) UseConfigMask(True) SetBeamCenter(89.6749, 129.693) SensitivityCorrection(FILE_LOCATION+'EQSANS_5703_event.nxs', min_sensitivity=0.5, max_sensitivity=1.5, use_sample_dc=True) DirectBeamTransmission(FILE_LOCATION+"EQSANS_5734_event.nxs", FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3) ThetaDependentTransmission(False) AppendDataFile([FILE_LOCATION+"EQSANS_5729_event.nxs"]) CombineTransmissionFits(True) Background(FILE_LOCATION+"EQSANS_5732_event.nxs") BckDirectBeamTransmission(FILE_LOCATION+"EQSANS_5737_event.nxs", FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3) BckThetaDependentTransmission(False) BckCombineTransmissionFits(True) SaveIqAscii(process='None') SetAbsoluteScale(277.781) Reduce1D() # This reference is old, ignore the first non-zero point and # give the comparison a reasonable tolerance (less than 0.5%). mtd['EQSANS_5729_event_frame1_Iq'].dataY(0)[1] = 856.30028119108 def validate(self): self.tolerance = 5.0 self.disableChecking.append('Instrument') self.disableChecking.append('Sample') self.disableChecking.append('SpectraMap') self.disableChecking.append('Axes') return "EQSANS_5729_event_frame1_Iq", 'EQSANSFlatTest.nxs'<|fim▁end|>
class EQSANSFlatTest(systemtesting.MantidSystemTest): def requiredFiles(self): files = []
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from django import forms __all__ = ('RatingField',) <|fim▁hole|><|fim▁end|>
class RatingField(forms.ChoiceField): pass
<|file_name|>motorTemperature.js<|end_file_name|><|fim▁begin|>MotorTemperatures = new Mongo.Collection('MotorTemperatures'); // fields : value, timestamp MotorTemperatures.allow({ insert: function(userid, temp){return true;} //for now }); Meteor.methods({ motorTemperatureInsert: function(temp) { check(temp,Match.Integer); var tempObject = { value: temp,<|fim▁hole|> } }); if(Meteor.isClient){ Session.set("actualMotorTemp",MotorTemperatures.find({}, {sort: {timestamp: -1}, limit:1}).fetch()[0]); motorTemps = []; Session.set("motorTemps", motorTemps); MotorTemperatures.find().observe({ added: function(temp){ Session.set("actualMotorTemp",temp); var localMotorTemps = Session.get("motorTemps"); localMotorTemps.push({x:temp.timestamp, y:temp.value}); if(localMotorTemps.length > 50){ localMotorTemps.shift(); } Session.set("motorTemps", localMotorTemps); } }); }<|fim▁end|>
timestamp: Date.now() }; MotorTemperatures.insert(tempObject);
<|file_name|>browser.py<|end_file_name|><|fim▁begin|># Copyright (C) 2009, Thomas Leonard # See the README file for details, or visit http://0install.net. import os, sys def open_in_browser(link): browser = os.environ.get('BROWSER', 'firefox') child = os.fork() if child == 0: # We are the child<|fim▁hole|> except Exception, ex: print >>sys.stderr, "Error", ex os._exit(1) os.waitpid(child, 0)<|fim▁end|>
try: os.spawnlp(os.P_NOWAIT, browser, browser, link) os._exit(0)
<|file_name|>test_common_fields.py<|end_file_name|><|fim▁begin|>import socket import pytest import mock from pygelf import GelfTcpHandler, GelfUdpHandler, GelfHttpHandler, GelfTlsHandler, GelfHttpsHandler from tests.helper import logger, get_unique_message, log_warning, log_exception SYSLOG_LEVEL_ERROR = 3 SYSLOG_LEVEL_WARNING = 4 @pytest.fixture(params=[ GelfTcpHandler(host='127.0.0.1', port=12201), GelfUdpHandler(host='127.0.0.1', port=12202), GelfUdpHandler(host='127.0.0.1', port=12202, compress=False), GelfHttpHandler(host='127.0.0.1', port=12203), GelfHttpHandler(host='127.0.0.1', port=12203, compress=False), GelfTlsHandler(host='127.0.0.1', port=12204), GelfHttpsHandler(host='127.0.0.1', port=12205, validate=False), GelfHttpsHandler(host='localhost', port=12205, validate=True, ca_certs='tests/config/cert.pem'), GelfTlsHandler(host='127.0.0.1', port=12204, validate=True, ca_certs='tests/config/cert.pem'), ]) def handler(request): return request.param def test_simple_message(logger): message = get_unique_message() graylog_response = log_warning(logger, message) assert graylog_response['message'] == message assert graylog_response['level'] == SYSLOG_LEVEL_WARNING assert 'full_message' not in graylog_response assert 'file' not in graylog_response assert 'module' not in graylog_response assert 'func' not in graylog_response assert 'logger_name' not in graylog_response assert 'line' not in graylog_response def test_formatted_message(logger): message = get_unique_message()<|fim▁hole|> assert graylog_response['message'] == message + '_hello_gelf' assert graylog_response['level'] == SYSLOG_LEVEL_WARNING assert 'full_message' not in graylog_response def test_full_message(logger): message = get_unique_message() try: raise ValueError(message) except ValueError as e: graylog_response = log_exception(logger, message, e) assert graylog_response['message'] == message assert graylog_response['level'] == SYSLOG_LEVEL_ERROR assert message in graylog_response['full_message'] assert 'Traceback (most recent call last)' in graylog_response['full_message'] assert 'ValueError: ' in graylog_response['full_message'] assert 'file' not in graylog_response assert 'module' not in graylog_response assert 'func' not in graylog_response assert 'logger_name' not in graylog_response assert 'line' not in graylog_response def test_source(logger): original_source = socket.gethostname() with mock.patch('socket.gethostname', return_value='different_domain'): message = get_unique_message() graylog_response = log_warning(logger, message) assert graylog_response['source'] == original_source<|fim▁end|>
template = message + '_%s_%s' graylog_response = log_warning(logger, template, args=('hello', 'gelf'))
<|file_name|>elastic_profiles.tsx<|end_file_name|><|fim▁begin|>/*<|fim▁hole|> * 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 Page from "helpers/spa_base"; import {ElasticProfilesPage} from "views/pages/elastic_profiles"; export class ElasticProfilesSPA extends Page { constructor() { super(ElasticProfilesPage); } } //tslint:disable-next-line new ElasticProfilesSPA();<|fim▁end|>
* Copyright 2018 ThoughtWorks, Inc. *
<|file_name|>derive.rs<|end_file_name|><|fim▁begin|>use crate::cfg_eval::cfg_eval; use rustc_ast as ast; use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::AttributeTemplate; use rustc_parse::validate_attr; use rustc_session::Session; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; crate struct Expander; impl MultiItemModifier for Expander { fn expand( &self, ecx: &mut ExtCtxt<'_>, span: Span, meta_item: &ast::MetaItem, item: Annotatable, ) -> ExpandResult<Vec<Annotatable>, Annotatable> { let sess = ecx.sess; if report_bad_target(sess, &item, span) { // We don't want to pass inappropriate targets to derive macros to avoid // follow up errors, all other errors below are recoverable. return ExpandResult::Ready(vec![item]); } let (sess, features) = (ecx.sess, ecx.ecfg.features); let result = ecx.resolver.resolve_derives(ecx.current_expansion.id, ecx.force_mode, &|| { let template = AttributeTemplate { list: Some("Trait1, Trait2, ..."), ..Default::default() }; let attr = attr::mk_attr_outer(meta_item.clone()); validate_attr::check_builtin_attribute( &sess.parse_sess, &attr, sym::derive, template, ); let mut resolutions: Vec<_> = attr .meta_item_list() .unwrap_or_default() .into_iter() .filter_map(|nested_meta| match nested_meta { NestedMetaItem::MetaItem(meta) => Some(meta), NestedMetaItem::Literal(lit) => { // Reject `#[derive("Debug")]`. report_unexpected_literal(sess, &lit); None } }) .map(|meta| { // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the paths. report_path_args(sess, &meta); meta.path }) .map(|path| (path, dummy_annotatable(), None)) .collect(); // Do not configure or clone items unless necessary. match &mut resolutions[..] { [] => {} [(_, first_item, _), others @ ..] => { *first_item = cfg_eval(sess, features, item.clone()); for (_, item, _) in others { *item = first_item.clone(); } } } resolutions }); match result { Ok(()) => ExpandResult::Ready(vec![item]), Err(Indeterminate) => ExpandResult::Retry(item), } } } // The cheapest `Annotatable` to construct. fn dummy_annotatable() -> Annotatable { Annotatable::GenericParam(ast::GenericParam { id: ast::DUMMY_NODE_ID, ident: Ident::empty(), attrs: Default::default(), bounds: Default::default(), is_placeholder: false, kind: GenericParamKind::Lifetime, }) } fn report_bad_target(sess: &Session, item: &Annotatable, span: Span) -> bool { let item_kind = match item { Annotatable::Item(item) => Some(&item.kind), Annotatable::Stmt(stmt) => match &stmt.kind { StmtKind::Item(item) => Some(&item.kind), _ => None, }, _ => None, }; let bad_target = !matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..))); if bad_target { struct_span_err!( sess, span, E0774, "`derive` may only be applied to `struct`s, `enum`s and `union`s", )<|fim▁hole|> } bad_target } fn report_unexpected_literal(sess: &Session, lit: &ast::Lit) { let help_msg = match lit.token.kind { token::Str if rustc_lexer::is_ident(&lit.token.symbol.as_str()) => { format!("try using `#[derive({})]`", lit.token.symbol) } _ => "for example, write `#[derive(Debug)]` for `Debug`".to_string(), }; struct_span_err!(sess, lit.span, E0777, "expected path to a trait, found literal",) .span_label(lit.span, "not a trait") .help(&help_msg) .emit(); } fn report_path_args(sess: &Session, meta: &ast::MetaItem) { let report_error = |title, action| { let span = meta.span.with_lo(meta.path.span.hi()); sess.struct_span_err(span, title) .span_suggestion(span, action, String::new(), Applicability::MachineApplicable) .emit(); }; match meta.kind { MetaItemKind::Word => {} MetaItemKind::List(..) => report_error( "traits in `#[derive(...)]` don't accept arguments", "remove the arguments", ), MetaItemKind::NameValue(..) => { report_error("traits in `#[derive(...)]` don't accept values", "remove the value") } } }<|fim▁end|>
.span_label(span, "not applicable here") .span_label(item.span(), "not a `struct`, `enum` or `union`") .emit();
<|file_name|>books.py<|end_file_name|><|fim▁begin|>bookprefix = { 'Genesis' : '1', 'genesis' : '1', 'Gen' : '1', 'gen' : '1', 'Exodus' : '2', 'exodus' : '2', 'Exo' : '2', 'exo' : '2', 'Ex' : '2', 'ex' : '2', 'Leviticus' : '3', 'leviticus' : '3', 'Lev' : '3', 'lev' : '3', 'Numbers' : '4', 'numbers' : '4', 'Numb' : '4', 'numb' : '4', 'Num' : '4', 'num' : '4', 'Deuteronomy' : '5', 'deuteronomy' : '5', 'Deut' : '5', 'deut' : '5', 'Joshua' : '6', 'joshua' : '6', 'Josh' : '6', 'josh' : '6', 'Judges' : '7' , 'judges' : '7' , 'Judg' : '7', 'judg' : '7', 'Ruth' : '8', 'ruth' : '8', '1Samuel' : '9', '1samuel' : '9', '1Sam' : '9', '1sam' : '9', '2Samuel' : '10', '2samuel' : '10', '2Sam' : '10', '2sam' : '10', '1Kings' : '11', '1kings' : '11', '1King' : '11', '1king' : '11', '1Ki' : '11', '1ki' : '11', '2Kings' : '12', '2kings' : '12', '2King' : '12', '2king' : '12', '2Ki' : '12', '2ki' : '12', '1Chronicles' : '13', '1chronicles' : '13', '1Chron' : '13', '1chron' : '13', '2Chronicles' : '14', '2chronicles' : '14', '2Chron' : '14', '2chron' : '14', 'Ezra' : '15', 'ezra' : '15', 'Nehemiah' : '16', 'nehemiah' : '16', 'Neh' : '16', 'neh' : '16', 'Esther' : '17', 'esther' : '17', 'Job' : '18', 'job' : '18', 'Psalms' : '19', 'psalms' : '19', 'Psalm' : '19', 'psalm' : '19', 'Ps' : '19', 'ps' : '19', 'Proverbs' : '20', 'proverbs' : '20', 'Proverb' : '20', 'proverb' : '20', 'Prov' : '20', 'prov' : '20', 'Ecclesiastes' : '21', 'ecclesiastes' : '21', 'Eccl' : '21', 'eccl' : '21', 'SongofSolomon' : '22', 'songofSolomon' : '22', 'songofsolomon' : '22', 'SongofSol' : '22', 'songofSol' : '22', 'songofsol' : '22', 'Isaiah' : '23', 'isaiah' : '23', 'Isa' : '23', 'isa' : '23', 'Jeremiah' : '24', 'jeremiah' : '24', 'Jer' : '24', 'jer' : '24', 'Lamentations' : '25', 'lamentations' : '25', 'Lam' : '25', 'lam' : '25', 'Ezekiel' : '26', 'ezekiel' : '26', 'Ez' : '26', 'ez' : '26', 'Daniel' : '27', 'daniel' : '27', 'Dan' : '27', 'dan' : '27', 'Hosea' : '28', 'hosea' : '28', 'Hos' : '28', 'hos' : '28', 'Joel' : '29', 'joel' : '29', 'Amos' : '30', 'amos' : '30', 'Obadiah' : '31', 'obadiah' : '31', 'Obad' : '31', 'obad' : '31', 'Jonah' : '32', 'jonah' : '32', 'Micah' : '33', 'micah' : '33', 'Mic' : '33', 'mic' : '33', 'Nahum' : '34' , 'nahum' : '34' , 'Nah' : '34', 'nah' : '34', 'Habakkuk' : '35', 'habakkuk' : '35', 'Hab' : '35', 'hab' : '35',<|fim▁hole|> 'Haggai' : '37', 'haggai' : '37', 'Hag' : '37', 'hag' : '37', 'Zechariah' : '38', 'zechariah' : '38', 'Zech' : '38', 'zech' : '38', 'Malachi' : '39', 'malachi' : '39', 'Mal' : '39', 'mal' : '39', 'Matthew' : '40', 'matthew' : '40', 'Matt' : '40', 'matt' : '40', 'Mark' : '41', 'mark' : '41', 'Luke' : '42', 'luke' : '42', 'John' : '43', 'john' : '43', 'Acts' : '44', 'acts' : '44', 'Act' : '44', 'act' : '44', 'Romans' : '45', 'romans' : '45', 'Rom' : '45', 'rom' : '45', '1Corinthians' : '46', '1corinthians' : '46', '1Cor' : '46', '1cor' : '46', '2Corinthians' : '47', '2corinthians' : '47', '2Cor' : '47', '2cor' : '47', 'Galatians' : '48', 'galatians' : '48', 'Gal' : '48', 'gal' : '48', 'Ephesians' : '49', 'ephesians' : '49', 'Eph' : '49', 'eph' : '49', 'Philippians' : '50', 'philippians' : '50', 'Phil' : '50', 'phil' : '50', 'Colossians' : '51', 'colossians' : '51', 'Col' : '51', 'col' : '51', '1Thessalonians' : '52', '1thessalonians' : '52', '1Thess' : '52', '1thess' : '52', '2Thessalonians' : '53', '2thessalonians' : '53', '2Thess' : '53', '2thess' : '53', '1Timothy' : '54', '1timothy' : '54', '1Tim' : '54', '1tim' : '54', '2Timothy' : '55', '2timothy' : '55', '2Tim' : '55', '2tim' : '55', 'Titus' : '56', 'titus' : '56', 'Philemon' : '57', 'philemon' : '57', 'Philem' : '57', 'philem' : '57', 'Hebrews' : '58', 'hebrews' : '58', 'Heb' : '58', 'heb' : '58', 'James' : '59', 'james' : '59', 'Jas' : '59', 'jas' : '59', '1Peter' : '60', '1peter' : '60', '1Pet' : '60', '1pet' : '60', '2Peter' : '61', '2peter' : '61', '2Pet' : '61', '2pet' : '61', '1John' : '62', '1john' : '62', '2John' : '63', '2john' : '63', '3John' : '64', '3john' : '64', 'Jude' : '65', 'jude' : '65', 'Revelation' : '66', 'revelation' : '66', 'Rev' : '66', 'rev' : '66' }<|fim▁end|>
'Zephaniah' : '36', 'zephaniah' : '36', 'Zeph' : '36', 'zeph' : '36',
<|file_name|>cli_ssh.py<|end_file_name|><|fim▁begin|>''' Created on Jun 16, 2014 @author: lwoydziak ''' import pexpect import sys from dynamic_machine.cli_commands import assertResultNotEquals, Command class SshCli(object): LOGGED_IN = 0 def __init__(self, host, loginUser, debug = False, trace = False, log=None, port=22, pexpectObject=None): self.pexpect = pexpect if not pexpectObject else pexpectObject self.debug = debug self.trace = trace self.host = host self._port = port self._connection = None self.modeList = [] self._log = log self._bufferedCommands = None self._bufferedMode = None self._loginUser = loginUser self._resetExpect() def __del__(self): self.closeCliConnectionTo() def showOutputOnScreen(self): self.debug = True self.trace = True self._log = None self._setupLog() def connectWithSsh(self): self._debugLog("Establishing connection to " + self.host) self._connection = self.pexpect.spawn( 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s@%s -p %d' % (self._loginUser.username, self.host, self._port)) if self._connection is None: raise Exception("Unable to connect via SSH perhaps wrong IP!") self._secure = True self._setupLog() self._loginUser.commandLine(self) self.modeList = [self._loginUser] def resetLoggingTo(self, log): self._connection.logfile = log def _setupLog(self): if self.trace: class Python3BytesToStdOut: def write(self, s): sys.stdout.buffer.write(s) def flush(self): sys.stdout.flush() self._connection.logfile = Python3BytesToStdOut() if self._log is not None: self._connection.logfile = self._log def loginSsh(self): self._setupLog() self._debugLog("Login in as "+self._loginUser.username) try: self._loginUser.sendPassword() return True except Exception as e: self.forceCloseCliConnectionTo() raise Exception('Exception ('+str(e)+') '+'Expected CLI response: "Password:"' + "\n Got: \n" + self._lastExpect()) def _exit_modes_beyond(self, thisMode): if not self.modeList: return while len(self.modeList) > thisMode + 1: self.modeList.pop().exit() def exitMode(self, mode): if mode in self.modeList: self.modeList.remove(mode) def check_prereq(self, prereqMode = 0): self._exit_modes_beyond(prereqMode) if len(self.modeList) <= prereqMode: raise Exception("Attempted to enter menu when prerequist mode was not entered, expected: %d" % prereqMode) def execute_as(self, user): self.check_prereq(self.LOGGED_IN) self._exit_modes_beyond(self.LOGGED_IN) user.commandLine(self) user.login() self.modeList.append(user) return user def closeCliConnectionTo(self): if self._connection == None: return self._exit_modes_beyond(-1) self.modeList = [] self._debugLog("Exited all modes.") self.forceCloseCliConnectionTo() def forceCloseCliConnectionTo(self): self.modeList = None if self._connection: self._debugLog("Closing connection.") self._connection.close() self._connection = None def _debugLog(self, message): if self.debug: print(message) def _resetExpect(self): self.previousExpectLine = "" if self._connection is not None and isinstance(self._connection.buffer, str): self.previousExpectLine = self._connection.buffer self._connection.buffer = "" def _lastExpect(self): constructLine = self.previousExpectLine if self._connection is not None and isinstance(self._connection.before, str): constructLine += self._connection.before if self._connection is not None and isinstance(self._connection.after, str): constructLine += self._connection.after return constructLine def send(self, command): if self._bufferedCommands is None: self._bufferedCommands = command else: self._bufferedCommands += "\n" + command if self._bufferedMode is None: self.flush() else: self._debugLog("Buffering command " + command) def flush(self): if self._bufferedCommands is None: return<|fim▁hole|> def buffering(self): return self._bufferedMode def bufferedMode(self, mode = True): if mode is None: self.flush() self._bufferedMode = mode def compareReceivedAgainst(self, pattern, timeout=-1, searchwindowsize=None, indexOfSuccessfulResult=0): if self._bufferedMode is None: index = self._connection.expect(pattern, timeout, searchwindowsize) self._debugLog("\nLooking for " + str(pattern) + " Found ("+str(index)+")") self._debugLog(self._lastExpect()) return index else: return indexOfSuccessfulResult<|fim▁end|>
self._connection.sendline(str(self._bufferedCommands)) self._bufferedCommands = None
<|file_name|>gogo_octogist.py<|end_file_name|><|fim▁begin|>''' Use the Github API to get the most recent Gist for a list of users Created on 5 Nov 2019 @author: si ''' from datetime import datetime import sys import requests class OctoGist: def __init__(self): self.base_url = 'https://api.github.com' self.items_per_page = 100 self.gist_path = (f'{self.base_url}/users/' '{username}' f'/gists?per_page={self.items_per_page}' ) # support 1.1 keep alive self.requests_session = requests.Session() #self.get_headers = {'Content-type': 'application/json'} self.get_headers = {'Accept': 'application/vnd.github.v3+json'} def go(self, usernames): """ :param: usernames (str) comma separated list of user names """ # sort order doesn't exist on the per user gist endpoint. Only on /search/ # so find latest entry by iterating through all docs. target_field = 'created_at' # or could be 'updated_at' target_users = usernames.split(',') latest_gist = {} for username in target_users: for gist_doc in self.gist_documents(username): if username not in latest_gist \ or gist_doc[target_field] > latest_gist[username][target_field]: latest_gist[username] = gist_doc # overall sort for all users one_gist_per_user = [(username, gist) for username, gist in latest_gist.items()] one_gist_per_user.sort(key=lambda g: g[1][target_field], reverse=True) for username, gist in one_gist_per_user: # description is optional gist_desc = f"said something about {gist['description']}" \ if gist['description'] else "wrote a gist" self.log(f"{username} @ {gist[target_field]} {gist_desc}") for username in target_users: if username not in latest_gist: self.log(f"{username} hasn't ever written a public gist") def gist_documents(self, username, max_docs=None): """ Generator yielding (dict) as returned from github API :param: username (str) :param: max_docs (int or None) None for no limit """ r = self.requests_session.get(self.gist_path.format(username=username)) if r.status_code != 200:<|fim▁hole|> for d in r.json(): docs_fetched += 1 yield d if docs_fetched >= self.items_per_page: # this will only print once # TODO pagination msg = (f"TODO pagination not enabled so gists by user:{username} might have be " f"skipped as they have written more than {self.items_per_page} gists." ) self.log(msg, "WARNING") if max_docs is not None and docs_fetched > max_docs: return def log(self, msg, level="INFO"): """ Dependency injection ready logger. :param: msg (str) :param: level (str) , DEBUG, INFO, WARNING, ERROR, CRITICAL """ if level in ['ERROR', 'CRITICAL']: outfunc = sys.stderr.write else: outfunc = print # TODO stderr for level = "ERROR" log_time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") level_just = level.ljust(10) msg = f"{log_time} {level_just}{msg}" outfunc(msg) if __name__ == '__main__': if len(sys.argv) != 2: msg = "usage: python gogo_octogist.py <comma separated github usernames>\n" sys.stderr.write(msg) sys.exit(1) o = OctoGist() o.go(sys.argv[1])<|fim▁end|>
self.log(f"Couldn't get gists for {username}", "ERROR") return docs_fetched = 0
<|file_name|>harbour-jollagram_cs_CZ.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="cs_CZ" version="2.1"> <context> <name>About</name> <message> <location filename="../qml/pages/About.qml" line="25"/> <source>About</source> <comment>About page title</comment> <translation>O programu</translation> </message> <message> <location filename="../qml/pages/About.qml" line="47"/> <source>Donations are welcome</source> <translation>Dary jsou vítány</translation> </message> <message> <location filename="../qml/pages/About.qml" line="81"/> <source>You are welcome to contribute to translations</source> <translation>Budeme vám vděční za pomoc s překladem</translation> </message> <message> <location filename="../qml/pages/About.qml" line="98"/> <source>Author %1</source> <translation>Tvůrce %1</translation> </message> </context> <context> <name>AddContact</name> <message> <location filename="../qml/pages/AddContact.qml" line="24"/> <source>Add contact</source> <comment>Add contact page title</comment> <translation>Přidat kontakt</translation> </message> <message> <location filename="../qml/pages/AddContact.qml" line="34"/> <source>Phone number</source> <comment>Placeholder for phone number in add contact page</comment> <translation>Telefonní číslo</translation> </message> <message> <location filename="../qml/pages/AddContact.qml" line="35"/> <source>Phone number</source> <comment>Label for phone number in add contact page</comment> <translation>Telefonní číslo</translation> </message> <message> <location filename="../qml/pages/AddContact.qml" line="44"/> <source>First name</source> <comment>Placeholder for First name in add contact page</comment> <translation>Jméno</translation> </message> <message> <location filename="../qml/pages/AddContact.qml" line="45"/> <source>First name</source> <comment>Label for First name in add contact page</comment> <translation>Jméno</translation> </message> <message> <location filename="../qml/pages/AddContact.qml" line="53"/> <source>Second name</source> <comment>Placeholder for second name in add contact page</comment> <translation>Příjmení</translation> </message> <message> <location filename="../qml/pages/AddContact.qml" line="54"/> <source>Second name</source> <comment>Label for second name in add contact page</comment> <translation>Příjmení</translation> </message> </context> <context> <name>AddContactsToGroup</name> <message> <location filename="../qml/pages/AddContactsToGroup.qml" line="22"/> <source>Add contacts</source> <comment>Page title of add contacts to group</comment> <translation>Přidat kontakty</translation> </message> <message> <location filename="../qml/pages/AddContactsToGroup.qml" line="44"/> <source>No Contacts</source> <comment>Placeholder for listview of contact</comment> <translation>Žádné kontakty</translation> </message> </context> <context> <name>AddPhoneBook</name> <message> <location filename="../qml/pages/AddPhoneBook.qml" line="28"/> <source>Add contacts</source> <comment>Page title of phonebook</comment> <translation>Přidat kontakty</translation> </message> <message> <location filename="../qml/pages/AddPhoneBook.qml" line="120"/> <source>Search contacts</source> <comment>Placeholder of search line in phonebook</comment> <translation>Vyhledat kontakty</translation> </message> </context> <context> <name>CContactsModel</name> <message> <location filename="../src/ccontactmodel.cpp" line="154"/> <location filename="../src/ccontactmodel.cpp" line="266"/> <source>Unknown</source> <translation>Neznámé</translation> </message> <message> <location filename="../src/ccontactmodel.cpp" line="261"/> <source>Online</source> <translation>Online</translation> </message> <message> <location filename="../src/ccontactmodel.cpp" line="263"/> <source>Offline</source> <translation>Offline</translation> </message> </context> <context> <name>ContactList</name> <message> <location filename="../qml/pages/ContactList.qml" line="10"/> <source>Contact list</source> <comment>Page title</comment> <translation>Seznam kontaktů</translation> </message> </context> <context> <name>ContactsListView</name> <message> <location filename="../qml/pages/common/ContactsListView.qml" line="19"/> <source>New secret chat</source> <comment>Pulley menu action</comment> <translation>Nová soukromá konverzace</translation> </message> <message> <location filename="../qml/pages/common/ContactsListView.qml" line="25"/> <source>Invite friends</source> <comment>Pulley menu action</comment><|fim▁hole|> </message> <message> <location filename="../qml/pages/common/ContactsListView.qml" line="32"/> <source>Add contact</source> <comment>Pulley menu action</comment> <translation>Přidat kontakt</translation> </message> <message> <location filename="../qml/pages/common/ContactsListView.qml" line="38"/> <source>Add from phonebook</source> <comment>Pulley menu action</comment> <translation>Přidat z mobilního adresáře</translation> </message> </context> <context> <name>CreateNewGroup</name> <message> <location filename="../qml/pages/CreateNewGroup.qml" line="34"/> <source>Create new group</source> <comment>Page title</comment> <translation>Vytvořit novou skupinu</translation> </message> <message> <location filename="../qml/pages/CreateNewGroup.qml" line="43"/> <source>Choose a name for the group</source> <comment>Placeholder for text line of group name</comment> <translation>Vybrat jméno pro skupinu</translation> </message> <message> <location filename="../qml/pages/CreateNewGroup.qml" line="44"/> <source>Choose a name for the group</source> <comment>Label for text line of group name</comment> <translation>Vybrat jméno pro skupinu</translation> </message> </context> <context> <name>LoadingPage</name> <message> <location filename="../qml/pages/LoadingPage.qml" line="33"/> <source>Connecting...</source> <comment>Message label for waiting page</comment> <translation>Připojuji...</translation> </message> </context> <context> <name>MainPage</name> <message> <location filename="../qml/pages/MainPage.qml" line="29"/> <source>New Broadcast</source> <comment>Main menu action</comment> <translation>Nový přenos</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="39"/> <source>New group chat</source> <comment>Main menu action</comment> <translation>Nová skupinová konverzace</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="46"/> <source>Settings</source> <comment>Main menu action</comment> <translation>Nastavení</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="50"/> <source>Contacts</source> <comment>Main menu action</comment> <translation>Kontakty</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="63"/> <source>No items</source> <comment>Placeholder for listview of conversation</comment> <translation>Žádné položky</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="66"/> <source>jollagram isn&apos;t connected</source> <comment>Page title of conversation for not connected state</comment> <translation>Jollagram není připojen</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="82"/> <source>Remove</source> <comment>Context menu, remove conversation</comment> <translation>Odstranit</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="82"/> <source>Wait erasing previous</source> <comment>Context menu, remove conversation waiting for a previous action</comment> <translation>Počkejte, mažou se předchozí</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="86"/> <source>Unmute</source> <comment>Context menu, unmute conversation</comment> <translation>Hlasitě</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="86"/> <source>Mute</source> <comment>Context menu, mute conversation</comment> <translation>Tiše</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="101"/> <source>Deleting</source> <comment>Delete conversation remorse action text</comment> <translation>Odstraňuje se</translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="193"/> <source>you</source> <comment>Name of self-contact in conversation</comment> <translation>ty</translation> </message> </context> <context> <name>MessagesView</name> <message> <location filename="../qml/pages/conversation/MessagesView.qml" line="167"/> <source>Deleting</source> <comment>Remorse action text</comment> <translation>Odstraňuje se</translation> </message> <message> <location filename="../qml/pages/conversation/MessagesView.qml" line="192"/> <source>retry message</source> <comment>Remorse action text</comment> <translation>Znovu odeslat zprávu</translation> </message> <message> <location filename="../qml/pages/conversation/MessagesView.qml" line="197"/> <source>copy message</source> <comment>Remorse action text</comment> <translation>Kopírovat zprávu</translation> </message> <message> <location filename="../qml/pages/conversation/MessagesView.qml" line="201"/> <source>delete message</source> <comment>Remorse action text</comment> <translation>Smazat zprávu</translation> </message> </context> <context> <name>OviMapTile</name> <message> <location filename="../qml/pages/common/OviMapTile.qml" line="68"/> <source>latitude: %1</source> <comment>latitude message received</comment> <translation>Zeměpisná šířka: %1</translation> </message> <message> <location filename="../qml/pages/common/OviMapTile.qml" line="72"/> <source>longitude: %1</source> <comment>longitude message received</comment> <translation>Zeměpisná délka: %1</translation> </message> <message> <location filename="../qml/pages/common/OviMapTile.qml" line="93"/> <source>Loading map...</source> <comment>Placeholder in chat message</comment> <translation>Načítám mapu...</translation> </message> </context> <context> <name>Settings</name> <message> <location filename="../qml/pages/Settings.qml" line="22"/> <source>Logout, Erase secret and user data</source> <comment>Pulley menu action</comment> <translation>Odhlásit, smazat tajná a uživatelská data</translation> </message> <message> <location filename="../qml/pages/Settings.qml" line="24"/> <source>Clearing user data</source> <comment>Remorse popup from pulley menu</comment> <translation>Odstraňuji uživatelská data</translation> </message> <message> <location filename="../qml/pages/Settings.qml" line="28"/> <source>About</source> <translation>O produktu</translation> </message> <message> <location filename="../qml/pages/Settings.qml" line="32"/> <source>Restore Connection</source> <comment>Pulley menu action</comment> <translation>Obnovit spojení</translation> </message> <message> <location filename="../qml/pages/Settings.qml" line="54"/> <source>Settings</source> <comment>Page title</comment> <translation>Nastavení</translation> </message> <message> <location filename="../qml/pages/Settings.qml" line="81"/> <source>Open chat</source> <comment>Setting option for chat beavior</comment> <translation>Otevřená konverzace</translation> </message> <message> <location filename="../qml/pages/Settings.qml" line="81"/> <source>View conversations</source> <comment>Setting option for chat beavior</comment> <translation>Zobrazit konverzace</translation> </message> <message> <location filename="../qml/pages/Settings.qml" line="82"/> <source>Behavior of notifications</source> <comment>Description of setting option for chat beavior</comment> <translation>Vlastnosti upozornění</translation> </message> </context> <context> <name>SignIn</name> <message> <location filename="../qml/pages/SignIn.qml" line="61"/> <source>Connecting...</source> <comment>Message label for waiting page</comment> <translation>Připojuji...</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="76"/> <source>Registration</source> <comment>Page title of signin procedure</comment> <translation>Registrace</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="86"/> <source>code recived</source> <comment>Placeholder of text line for the code received during sign in procedure</comment> <translation>Kód přijat</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="87"/> <source>code recived</source> <comment>Label of text line for the code received during sign in procedure</comment> <translation>Kód přijat</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="98"/> <source>Phone number</source> <comment>Placeholder of text line for sign in procedure</comment> <translation>Telefonní číslo</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="99"/> <source>Phone number</source> <comment>Label of text line for sign in procedure</comment> <translation>Telefonní číslo</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="108"/> <source>First name</source> <comment>Placeholder of text line for sign in procedure</comment> <translation>Jméno</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="109"/> <source>First name</source> <comment>Label of text line for sign in procedure</comment> <translation>Jméno</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="118"/> <source>Last name</source> <comment>Placeholder of text line for sign in procedure</comment> <translation>Příjmení</translation> </message> <message> <location filename="../qml/pages/SignIn.qml" line="119"/> <source>Last name</source> <comment>Label of text line for sign in procedure</comment> <translation>Příjmení</translation> </message> </context> <context> <name>TelegramInterface</name> <message> <location filename="../src/telegraminterface.cpp" line="309"/> <source>Registered</source> <translation>Registrován</translation> </message> <message> <location filename="../src/telegraminterface.cpp" line="309"/> <source>Not registered</source> <translation>Neregistrován</translation> </message> <message> <location filename="../src/telegraminterface.cpp" line="310"/> <source>invited</source> <translation>Pozván</translation> </message> <message> <location filename="../src/telegraminterface.cpp" line="310"/> <source>not invited</source> <translation>Nepozván</translation> </message> <message> <location filename="../src/telegraminterface.cpp" line="591"/> <location filename="../src/telegraminterface.cpp" line="706"/> <source>Position received</source> <translation>Obdržena pozice</translation> </message> </context> </TS><|fim▁end|>
<translation>Pozvat přátele</translation>
<|file_name|>test_rfkill.py<|end_file_name|><|fim▁begin|># rfkill tests # Copyright (c) 2014, Jouni Malinen <[email protected]> # # This software may be distributed under the terms of the BSD license. # See README for more details. import logging logger = logging.getLogger() import time import hostapd from hostapd import HostapdGlobal import hwsim_utils from wpasupplicant import WpaSupplicant from rfkill import RFKill from utils import HwsimSkip def get_rfkill(dev): phy = dev.get_driver_status_field("phyname") try: for r, s, h in RFKill.list(): if r.name == phy: return r except Exception, e: raise HwsimSkip("No rfkill available: " + str(e)) raise HwsimSkip("No rfkill match found for the interface") def test_rfkill_open(dev, apdev): """rfkill block/unblock during open mode connection""" rfk = get_rfkill(dev[0]) hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" }) dev[0].connect("open", key_mgmt="NONE", scan_freq="2412") try: logger.info("rfkill block") rfk.block() dev[0].wait_disconnected(timeout=10, error="Missing disconnection event on rfkill block") if "FAIL" not in dev[0].request("REASSOCIATE"): raise Exception("REASSOCIATE accepted while disabled") if "FAIL" not in dev[0].request("REATTACH"): raise Exception("REATTACH accepted while disabled") if "FAIL" not in dev[0].request("RECONNECT"): raise Exception("RECONNECT accepted while disabled") if "FAIL" not in dev[0].request("FETCH_OSU"): raise Exception("FETCH_OSU accepted while disabled") logger.info("rfkill unblock") rfk.unblock() dev[0].wait_connected(timeout=10, error="Missing connection event on rfkill unblock") hwsim_utils.test_connectivity(dev[0], hapd) finally: rfk.unblock() def test_rfkill_wpa2_psk(dev, apdev): """rfkill block/unblock during WPA2-PSK connection""" rfk = get_rfkill(dev[0]) ssid = "test-wpa2-psk" passphrase = 'qwertyuiop' params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase) hapd = hostapd.add_ap(apdev[0]['ifname'], params) dev[0].connect(ssid, psk=passphrase, scan_freq="2412") try: logger.info("rfkill block") rfk.block() dev[0].wait_disconnected(timeout=10, error="Missing disconnection event on rfkill block") logger.info("rfkill unblock") rfk.unblock() dev[0].wait_connected(timeout=10, error="Missing connection event on rfkill unblock") hwsim_utils.test_connectivity(dev[0], hapd) finally: rfk.unblock() def test_rfkill_autogo(dev, apdev): """rfkill block/unblock for autonomous P2P GO""" rfk0 = get_rfkill(dev[0]) rfk1 = get_rfkill(dev[1]) dev[0].p2p_start_go() dev[1].request("SET p2p_no_group_iface 0") dev[1].p2p_start_go() try: logger.info("rfkill block 0") rfk0.block() ev = dev[0].wait_global_event(["P2P-GROUP-REMOVED"], timeout=10) if ev is None: raise Exception("Group removal not reported") if "reason=UNAVAILABLE" not in ev: raise Exception("Unexpected group removal reason: " + ev) if "FAIL" not in dev[0].request("P2P_LISTEN 1"): raise Exception("P2P_LISTEN accepted unexpectedly") if "FAIL" not in dev[0].request("P2P_LISTEN"): raise Exception("P2P_LISTEN accepted unexpectedly") logger.info("rfkill block 1") rfk1.block() ev = dev[1].wait_global_event(["P2P-GROUP-REMOVED"], timeout=10) if ev is None: raise Exception("Group removal not reported") if "reason=UNAVAILABLE" not in ev: raise Exception("Unexpected group removal reason: " + ev) logger.info("rfkill unblock 0") rfk0.unblock() logger.info("rfkill unblock 1") rfk1.unblock() time.sleep(1) finally: rfk0.unblock() rfk1.unblock() def test_rfkill_hostapd(dev, apdev): """rfkill block/unblock during and prior to hostapd operations"""<|fim▁hole|> hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" }) rfk = get_rfkill(hapd) try: rfk.block() ev = hapd.wait_event(["INTERFACE-DISABLED"], timeout=5) if ev is None: raise Exception("INTERFACE-DISABLED event not seen") rfk.unblock() ev = hapd.wait_event(["INTERFACE-ENABLED"], timeout=5) if ev is None: raise Exception("INTERFACE-ENABLED event not seen") # hostapd does not current re-enable beaconing automatically hapd.disable() hapd.enable() dev[0].connect("open", key_mgmt="NONE", scan_freq="2412") rfk.block() ev = hapd.wait_event(["INTERFACE-DISABLED"], timeout=5) if ev is None: raise Exception("INTERFACE-DISABLED event not seen") dev[0].wait_disconnected(timeout=10) dev[0].request("DISCONNECT") hapd.disable() hglobal = HostapdGlobal() hglobal.flush() hglobal.remove(apdev[0]['ifname']) hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open2" }, no_enable=True) if "FAIL" not in hapd.request("ENABLE"): raise Exception("ENABLE succeeded unexpectedly (rfkill)") finally: rfk.unblock() def test_rfkill_wpas(dev, apdev): """rfkill block prior to wpa_supplicant start""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") rfk = get_rfkill(wpas) wpas.interface_remove("wlan5") try: rfk.block() wpas.interface_add("wlan5") time.sleep(0.5) state = wpas.get_status_field("wpa_state") if state != "INTERFACE_DISABLED": raise Exception("Unexpected state with rfkill blocked: " + state) rfk.unblock() time.sleep(0.5) state = wpas.get_status_field("wpa_state") if state == "INTERFACE_DISABLED": raise Exception("Unexpected state with rfkill unblocked: " + state) finally: rfk.unblock()<|fim▁end|>
<|file_name|>censor.go<|end_file_name|><|fim▁begin|>/* Copyright 2021 The Kubernetes Authors. 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. */ package sidecar import ( "archive/tar" "compress/gzip" "context" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "strings" "sync" "github.com/mattn/go-zglob" "github.com/sirupsen/logrus" "golang.org/x/sync/semaphore" "gopkg.in/ini.v1" kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/test-infra/prow/secretutil" ) // defaultBufferSize is the default buffer size, 10MiB. const defaultBufferSize = 10 * 1024 * 1024 func (o Options) censor() error { var concurrency int64 if o.CensoringOptions.CensoringConcurrency == nil { concurrency = int64(10) } else { concurrency = *o.CensoringOptions.CensoringConcurrency } logrus.WithField("concurrency", concurrency).Debug("Censoring artifacts.") sem := semaphore.NewWeighted(concurrency) wg := &sync.WaitGroup{} errors := make(chan error) var errs []error errLock := &sync.Mutex{} go func() { errLock.Lock() for err := range errors { errs = append(errs, err) } errLock.Unlock() }() secrets, err := loadSecrets(o.CensoringOptions.SecretDirectories, o.CensoringOptions.IniFilenames) if err != nil { return fmt.Errorf("could not load secrets: %w", err) } logrus.WithField("secrets", len(secrets)).Debug("Loaded secrets to censor.") censorer := secretutil.NewCensorer() censorer.RefreshBytes(secrets...) bufferSize := defaultBufferSize if o.CensoringOptions.CensoringBufferSize != nil { bufferSize = *o.CensoringOptions.CensoringBufferSize } if largest := censorer.LargestSecret(); 2*largest > bufferSize { bufferSize = 2 * largest } logrus.WithField("buffer_size", bufferSize).Debug("Determined censoring buffer size.") censorFile := fileCensorer(sem, errors, censorer, bufferSize) censor := func(file string) { censorFile(wg, file) } for _, entry := range o.Entries { logPath := entry.ProcessLog censor(logPath) } for _, item := range o.GcsOptions.Items { if err := filepath.Walk(item, func(absPath string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() || info.Mode()&os.ModeSymlink == os.ModeSymlink { return nil } logger := logrus.WithField("path", absPath) relpath, shouldNotErr := filepath.Rel(item, absPath) if shouldNotErr != nil { logrus.WithError(shouldNotErr).Warnf("filepath.Rel returned an error, but we assumed there must be a relative path between %s and %s", item, absPath) } should, err := shouldCensor(*o.CensoringOptions, relpath) if err != nil { return fmt.Errorf("could not determine if we should censor path: %w", err) } if !should { return nil } contentType, err := determineContentType(absPath) if err != nil { return fmt.Errorf("could not determine content type of %s: %w", absPath, err) } switch contentType { case "application/x-gzip", "application/zip": logger.Debug("Censoring archive.") if err := handleArchive(absPath, censorFile); err != nil { return fmt.Errorf("could not censor archive %s: %w", absPath, err) } default: logger.Debug("Censoring file.") censor(absPath) } return nil }); err != nil { return fmt.Errorf("could not walk items to censor them: %w", err) } } wg.Wait() close(errors) errLock.Lock() return kerrors.NewAggregate(errs) } func shouldCensor(options CensoringOptions, path string) (bool, error) { for _, glob := range options.ExcludeDirectories { found, err := zglob.Match(glob, path) if err != nil { return false, err } if found { return false, nil // when explicitly excluded, do not censor } } for _, glob := range options.IncludeDirectories { found, err := zglob.Match(glob, path) if err != nil { return false, err } if found { return true, nil // when explicitly included, censor } } return len(options.IncludeDirectories) == 0, nil // censor if no explicit includes exist } // fileCensorer returns a closure over all of our synchronization for a clean handler signature func fileCensorer(sem *semaphore.Weighted, errors chan<- error, censorer secretutil.Censorer, bufferSize int) func(wg *sync.WaitGroup, file string) { return func(wg *sync.WaitGroup, file string) { wg.Add(1) go func() { if err := sem.Acquire(context.Background(), 1); err != nil { errors <- err return } defer sem.Release(1) defer wg.Done() errors <- handleFile(file, censorer, bufferSize) }() } } // determineContentType determines the content type of the file func determineContentType(path string) (string, error) { file, err := os.Open(path) if err != nil { return "", fmt.Errorf("could not open file to check content type: %w", err) } defer func() { if err := file.Close(); err != nil { logrus.WithError(err).Warn("Could not close input file while detecting content type.") } }() header := make([]byte, 512) if _, err := file.Read(header); err != nil && err != io.EOF { return "", fmt.Errorf("could not read file to check content type: %w", err) } return http.DetectContentType(header), nil } // handleArchive unravels the archive in order to censor data in the files that were added to it. // This is mostly stolen from build/internal/untar/untar.go func handleArchive(archivePath string, censor func(wg *sync.WaitGroup, file string)) error { outputDir, err := ioutil.TempDir("", "tmp-unpack") if err != nil { return fmt.Errorf("could not create temporary dir for unpacking: %w", err) } defer func() { if err := os.RemoveAll(outputDir); err != nil { logrus.WithError(err).Warn("Failed to clean up temporary directory for archive") } }() if err := unarchive(archivePath, outputDir); err != nil { return fmt.Errorf("could not unpack archive: %w", err) } children := &sync.WaitGroup{} if err := filepath.Walk(outputDir, func(absPath string, info os.FileInfo, err error) error { if info.IsDir() { return nil } censor(children, absPath) return nil }); err != nil { return fmt.Errorf("could not walk unpacked archive to censor them: %w", err) } children.Wait() if err := archive(outputDir, archivePath); err != nil { return fmt.Errorf("could not re-pack archive: %w", err) } return nil } // unarchive unpacks the archive into the destination func unarchive(archivePath, destPath string) error { input, err := os.Open(archivePath) if err != nil { return fmt.Errorf("could not open archive for unpacking: %w", err) } zipReader, err := gzip.NewReader(input) if err != nil { return fmt.Errorf("could not read archive: %w", err) } tarReader := tar.NewReader(zipReader) defer func() { if err := zipReader.Close(); err != nil { logrus.WithError(err).Warn("Could not close zip reader after unarchiving.") } if err := input.Close(); err != nil { logrus.WithError(err).Warn("Could not close input file after unarchiving.") } }() for { entry, err := tarReader.Next() if err == io.EOF { break } if err != nil { return fmt.Errorf("could not read archive: %w", err) } if !validRelPath(entry.Name) { return fmt.Errorf("tar contained invalid name error %q", entry.Name) } rel := filepath.FromSlash(entry.Name) abs := filepath.Join(destPath, rel) mode := entry.FileInfo().Mode() switch { case mode.IsDir(): if err := os.MkdirAll(abs, 0755); err != nil { return fmt.Errorf("could not create directory while unpacking archive: %w", err) } case mode.IsRegular(): file, err := os.OpenFile(abs, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode.Perm()) if err != nil { return err } n, err := io.Copy(file, tarReader) if closeErr := file.Close(); closeErr != nil && err == nil { return fmt.Errorf("error closing %s: %w", abs, closeErr) } if err != nil { return fmt.Errorf("error writing to %s: %w", abs, err) } if n != entry.Size { return fmt.Errorf("only wrote %d bytes to %s; expected %d", n, abs, entry.Size) } } } return nil } func validRelPath(p string) bool { if p == "" || strings.Contains(p, `\`) || strings.HasPrefix(p, "/") || strings.Contains(p, "../") { return false } return true } // archive re-packs the dir into the destination func archive(srcDir, destArchive string) error { // we want the temporary file we use for output to be in the same directory as the real destination, so // we can be certain that our final os.Rename() call will not have to operate across a device boundary output, err := ioutil.TempFile(filepath.Dir(destArchive), "tmp-archive") if err != nil { return fmt.Errorf("failed to create temporary file for archive: %w", err) } zipWriter := gzip.NewWriter(output) tarWriter := tar.NewWriter(zipWriter)<|fim▁hole|> logrus.WithError(err).Warn("Could not close tar writer after archiving.") } if err := zipWriter.Close(); err != nil { logrus.WithError(err).Warn("Could not close zip writer after archiving.") } if err := output.Close(); err != nil { logrus.WithError(err).Warn("Could not close output file after archiving.") } }() if err := filepath.Walk(srcDir, func(absPath string, info os.FileInfo, err error) error { if err != nil { return err } // Handle symlinks. See https://stackoverflow.com/a/40003617. var link string if info.Mode()&os.ModeSymlink == os.ModeSymlink { if link, err = os.Readlink(absPath); err != nil { return err } } // "link" is only used by FileInfoHeader if "info" here is a symlink. // See https://pkg.go.dev/archive/tar#FileInfoHeader. header, err := tar.FileInfoHeader(info, link) if err != nil { return fmt.Errorf("could not create tar header: %w", err) } // the header won't get nested paths right relpath, shouldNotErr := filepath.Rel(srcDir, absPath) if shouldNotErr != nil { logrus.WithError(shouldNotErr).Warnf("filepath.Rel returned an error, but we assumed there must be a relative path between %s and %s", srcDir, absPath) } header.Name = relpath if err := tarWriter.WriteHeader(header); err != nil { return fmt.Errorf("could not write tar header: %w", err) } if info.IsDir() { return nil } // Nothing more to do for non-regular files (symlinks). if !info.Mode().IsRegular() { return nil } file, err := os.Open(absPath) if err != nil { return fmt.Errorf("could not open source file: %w", err) } n, err := io.Copy(tarWriter, file) if err != nil { return fmt.Errorf("could not tar file: %w", err) } if n != info.Size() { return fmt.Errorf("only wrote %d bytes from %s; expected %d", n, absPath, info.Size()) } if err := file.Close(); err != nil { return fmt.Errorf("could not close source file: %w", err) } return nil }); err != nil { return fmt.Errorf("could not walk source files to archive them: %w", err) } if err := os.Rename(output.Name(), destArchive); err != nil { return fmt.Errorf("could not overwrite archive: %w", err) } return nil } // handleFile censors the content of a file by streaming it to a new location, then overwriting the previous // location, to make it seem like this happened in place on the filesystem func handleFile(path string, censorer secretutil.Censorer, bufferSize int) error { input, err := os.Open(path) if err != nil { return fmt.Errorf("could not open file for censoring: %w", err) } // we want the temporary file we use for output to be in the same directory as the real destination, so // we can be certain that our final os.Rename() call will not have to operate across a device boundary output, err := ioutil.TempFile(filepath.Dir(path), "tmp-censor") if err != nil { return fmt.Errorf("could not create temporary file for censoring: %w", err) } if err := censor(input, output, censorer, bufferSize); err != nil { return fmt.Errorf("could not censor file: %w", err) } if err := os.Rename(output.Name(), path); err != nil { return fmt.Errorf("could not overwrite file after censoring: %w", err) } return nil } // censor censors input data and streams it to the output. We have a memory footprint of bufferSize bytes. func censor(input io.ReadCloser, output io.WriteCloser, censorer secretutil.Censorer, bufferSize int) error { if bufferSize%2 != 0 { return fmt.Errorf("frame size must be even, not %d", bufferSize) } defer func() { if err := input.Close(); err != nil { logrus.WithError(err).Warn("Could not close input file after censoring.") } if err := output.Close(); err != nil { logrus.WithError(err).Warn("Could not close output file after censoring.") } }() buffer := make([]byte, bufferSize) frameSize := bufferSize / 2 // bootstrap the algorithm by reading in the first half-frame numInitialized, initializeErr := input.Read(buffer[:frameSize]) // handle read errors - if we read everything in this init step, the next read will return 0, EOF and // we can flush appropriately as part of the process loop if initializeErr != nil && initializeErr != io.EOF { return fmt.Errorf("could not read data from input file before censoring: %w", initializeErr) } frameSize = numInitialized // this will normally be bufferSize/2 but will be smaller at the end of the file for { // populate the second half of the buffer with new data numRead, readErr := input.Read(buffer[frameSize:]) if readErr != nil && readErr != io.EOF { return fmt.Errorf("could not read data from input file before censoring: %w", readErr) } // censor the full buffer and flush the first half to the output censorer.Censor(&buffer) numWritten, writeErr := output.Write(buffer[:frameSize]) if writeErr != nil { return fmt.Errorf("could not write data to output file after censoring: %w", writeErr) } if numWritten != frameSize { // TODO: we could retry here I guess? When would a filesystem write less than expected and not error? return fmt.Errorf("only wrote %d out of %d bytes after censoring", numWritten, frameSize) } // shift the buffer over and get ready to repopulate the rest with new data copy(buffer[:numRead], buffer[frameSize:frameSize+numRead]) frameSize = numRead if readErr == io.EOF { break } } return nil } // loadSecrets loads all files under the paths into memory func loadSecrets(paths, iniFilenames []string) ([][]byte, error) { var secrets [][]byte for _, path := range paths { if err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if strings.HasPrefix(info.Name(), "..") { // kubernetes volumes also include files we // should not look be looking into for keys if info.IsDir() { return filepath.SkipDir } return nil } if info.IsDir() { return nil } raw, err := ioutil.ReadFile(path) if err != nil { return err } secrets = append(secrets, raw) // In many cases, a secret file contains much more than just the sensitive data. For instance, // container registry credentials files are JSON formatted, so there are only a couple of fields // that are truly secret, the rest is formatting and whitespace. The implication here is that // a censoring approach that only looks at the full, uninterrupted secret value will not be able // to censor anything if that value is reformatted, truncated, etc. When the secrets we are asked // to censor are container registry credentials, we can know the format of these files and extract // the subsets of data that are sensitive, allowing us not only to censor the full file's contents // but also any individual fields that exist in the output, whether they're there due to a user // extracting the fields or output being truncated, etc. var parser = func(bytes []byte) ([]string, error) { return nil, nil } if info.Name() == ".dockercfg" { parser = loadDockercfgAuths } if info.Name() == ".dockerconfigjson" { parser = loadDockerconfigJsonAuths } for _, filename := range iniFilenames { if info.Name() == filename { parser = loadIniData break } } extra, parseErr := parser(raw) if parseErr != nil { return fmt.Errorf("could not read %s as a docker secret: %w", path, parseErr) } // It is important that these are added to the list of secrets *after* their parent data // as we will censor in order and this will give a reasonable guarantee that the parent // data (a superset of any of these fields) will be censored in its entirety, first. It // remains possible that the sliding window used to censor pulls in only part of the // superset and some small part of it is censored first, making the larger superset no // longer match the file being censored. for _, item := range extra { secrets = append(secrets, []byte(item)) } return nil }); err != nil { return nil, err } } return secrets, nil } // loadDockercfgAuths parses auth values from a kubernetes.io/dockercfg secret func loadDockercfgAuths(content []byte) ([]string, error) { var data map[string]authEntry if err := json.Unmarshal(content, &data); err != nil { return nil, err } var entries []authEntry for _, entry := range data { entries = append(entries, entry) } return collectSecretsFrom(entries), nil } // loadDockerconfigJsonAuths parses auth values from a kubernetes.io/dockercfgjson secret func loadDockerconfigJsonAuths(content []byte) ([]string, error) { var data = struct { Auths map[string]authEntry `json:"auths"` }{} if err := json.Unmarshal(content, &data); err != nil { return nil, err } var entries []authEntry for _, entry := range data.Auths { entries = append(entries, entry) } return collectSecretsFrom(entries), nil } // authEntry holds credentials for authentication to registries type authEntry struct { Password string `json:"password"` Auth string `json:"auth"` } func collectSecretsFrom(entries []authEntry) []string { var auths []string for _, entry := range entries { if entry.Auth != "" { auths = append(auths, entry.Auth) } if entry.Password != "" { auths = append(auths, entry.Password) } } return auths } func handleSection(section *ini.Section, extra []string) []string { for _, subsection := range section.ChildSections() { extra = handleSection(subsection, extra) } for _, key := range section.Keys() { extra = append(extra, key.Value()) } return extra } // loadIniData parses key-value data from an INI file func loadIniData(content []byte) ([]string, error) { cfg, err := ini.Load(content) if err != nil { return nil, err } var extra []string for _, section := range cfg.Sections() { extra = handleSection(section, extra) } return extra, nil }<|fim▁end|>
defer func() { if err := tarWriter.Close(); err != nil {
<|file_name|>upgrade-notification.js<|end_file_name|><|fim▁begin|>'use strict'; function getBetterUpgradeMessage(foundVersion) { let version = (foundVersion && foundVersion[1]) ? `(${foundVersion[1]}) ` : ''; return `A new version of Ghost Core ${version}is available! Hot Damn. \ <a href="http://support.ghost.org/how-to-upgrade/" target="_blank">Click here</a> \ to learn more on upgrading Ghost Core.`; } /** * Simple timeout + attempt based function that checks to see if Ghost Core has an update available, * and replaces the notification text with something a little more specific.'; */ function upgradeNotification(attempts = 100) { const elements = document.querySelectorAll('aside.gh-alerts .gh-alert-content'); elements.forEach((element) => { let foundVersion = /Ghost (\d\.\d\.\d) is available/g.exec(element.innerText); element.innerHTML = getBetterUpgradeMessage(foundVersion); }); <|fim▁hole|> } } /** * Init */ document.addEventListener('DOMContentLoaded', () => setTimeout(upgradeNotification, 50));<|fim▁end|>
if (elements.length === 0 && attempts > 0) { setTimeout(() => upgradeNotification(attempts - 1), 50);
<|file_name|>live.rs<|end_file_name|><|fim▁begin|>/// Disk scheme replacement when making live disk use alloc::sync::Arc; use alloc::collections::BTreeMap; use core::{slice, str}; use core::sync::atomic::{AtomicUsize, Ordering};<|fim▁hole|>use syscall::data::Stat; use syscall::error::*; use syscall::flag::{MODE_DIR, MODE_FILE}; use syscall::scheme::{calc_seek_offset_usize, Scheme}; use crate::memory::Frame; use crate::paging::{ActivePageTable, Page, PageFlags, PhysicalAddress, TableKind, VirtualAddress}; use crate::paging::mapper::PageFlushAll; static mut LIST: [u8; 2] = [b'0', b'\n']; struct Handle { path: &'static [u8], data: Arc<RwLock<&'static mut [u8]>>, mode: u16, seek: usize } pub struct DiskScheme { next_id: AtomicUsize, list: Arc<RwLock<&'static mut [u8]>>, data: Arc<RwLock<&'static mut [u8]>>, handles: RwLock<BTreeMap<usize, Handle>> } impl DiskScheme { pub fn new() -> Option<DiskScheme> { let mut phys = 0; let mut size = 0; for line in str::from_utf8(unsafe { crate::INIT_ENV }).unwrap_or("").lines() { let mut parts = line.splitn(2, '='); let name = parts.next().unwrap_or(""); let value = parts.next().unwrap_or(""); if name == "DISK_LIVE_ADDR" { phys = usize::from_str_radix(value, 16).unwrap_or(0); } if name == "DISK_LIVE_SIZE" { size = usize::from_str_radix(value, 16).unwrap_or(0); } } if phys > 0 && size > 0 { // Map live disk pages let virt = phys + crate::PHYS_OFFSET; unsafe { let mut active_table = ActivePageTable::new(TableKind::Kernel); let flush_all = PageFlushAll::new(); let start_page = Page::containing_address(VirtualAddress::new(virt)); let end_page = Page::containing_address(VirtualAddress::new(virt + size - 1)); for page in Page::range_inclusive(start_page, end_page) { let frame = Frame::containing_address(PhysicalAddress::new(page.start_address().data() - crate::PHYS_OFFSET)); let flags = PageFlags::new().write(true); let result = active_table.map_to(page, frame, flags); flush_all.consume(result); } flush_all.flush(); } Some(DiskScheme { next_id: AtomicUsize::new(0), list: Arc::new(RwLock::new(unsafe { &mut LIST })), data: Arc::new(RwLock::new(unsafe { slice::from_raw_parts_mut(virt as *mut u8, size) })), handles: RwLock::new(BTreeMap::new()) }) } else { None } } } impl Scheme for DiskScheme { fn open(&self, path: &str, _flags: usize, _uid: u32, _gid: u32) -> Result<usize> { let path_trimmed = path.trim_matches('/'); match path_trimmed { "" => { let id = self.next_id.fetch_add(1, Ordering::SeqCst); self.handles.write().insert(id, Handle { path: b"", data: self.list.clone(), mode: MODE_DIR | 0o755, seek: 0 }); Ok(id) }, "0" => { let id = self.next_id.fetch_add(1, Ordering::SeqCst); self.handles.write().insert(id, Handle { path: b"0", data: self.data.clone(), mode: MODE_FILE | 0o644, seek: 0 }); Ok(id) } _ => Err(Error::new(ENOENT)) } } fn read(&self, id: usize, buffer: &mut [u8]) -> Result<usize> { let mut handles = self.handles.write(); let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?; let data = handle.data.read(); let mut i = 0; while i < buffer.len() && handle.seek < data.len() { buffer[i] = data[handle.seek]; i += 1; handle.seek += 1; } Ok(i) } fn write(&self, id: usize, buffer: &[u8]) -> Result<usize> { let mut handles = self.handles.write(); let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?; let mut data = handle.data.write(); let mut i = 0; while i < buffer.len() && handle.seek < data.len() { data[handle.seek] = buffer[i]; i += 1; handle.seek += 1; } Ok(i) } fn seek(&self, id: usize, pos: isize, whence: usize) -> Result<isize> { let mut handles = self.handles.write(); let handle = handles.get_mut(&id).ok_or(Error::new(EBADF))?; let data = handle.data.read(); let new_offset = calc_seek_offset_usize(handle.seek, pos, whence, data.len())?; handle.seek = new_offset as usize; Ok(new_offset) } fn fcntl(&self, id: usize, _cmd: usize, _arg: usize) -> Result<usize> { let handles = self.handles.read(); let _handle = handles.get(&id).ok_or(Error::new(EBADF))?; Ok(0) } fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let handles = self.handles.read(); let handle = handles.get(&id).ok_or(Error::new(EBADF))?; //TODO: Copy scheme part in kernel let mut i = 0; let scheme_path = b"disk/live:"; while i < buf.len() && i < scheme_path.len() { buf[i] = scheme_path[i]; i += 1; } let mut j = 0; while i < buf.len() && j < handle.path.len() { buf[i] = handle.path[j]; i += 1; j += 1; } Ok(i) } fn fstat(&self, id: usize, stat: &mut Stat) -> Result<usize> { let handles = self.handles.read(); let handle = handles.get(&id).ok_or(Error::new(EBADF))?; let data = handle.data.read(); stat.st_mode = handle.mode; stat.st_uid = 0; stat.st_gid = 0; stat.st_size = data.len() as u64; Ok(0) } fn fsync(&self, id: usize) -> Result<usize> { let handles = self.handles.read(); let _handle = handles.get(&id).ok_or(Error::new(EBADF))?; Ok(0) } fn close(&self, id: usize) -> Result<usize> { self.handles.write().remove(&id).ok_or(Error::new(EBADF)).and(Ok(0)) } }<|fim▁end|>
use spin::RwLock;
<|file_name|>Export_Count_Station_Location.py<|end_file_name|><|fim▁begin|>''' Copyright 2015 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The TMG Toolbox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the TMG Toolbox. If not, see <http://www.gnu.org/licenses/>. ''' #---METADATA--------------------- ''' Export Count Station Link Correspondence File Authors: David King Latest revision by: [Description] ''' #---VERSION HISTORY ''' 0.0.1 Created 0.1.1 Created on 2015-03-13 by David King ''' import inro.modeller as _m import csv import traceback as _traceback from contextlib import contextmanager from contextlib import nested _mm = _m.Modeller() net =_mm.scenario.get_network() _util = _mm.module('tmg.common.utilities') _tmgTPB = _mm.module('tmg.common.TMG_tool_page_builder') class ExportCountStationLocation(_m.Tool()): version = '0.1.1' tool_run_msg = "" number_of_tasks = 1 Scenario = _m.Attribute(_m.InstanceType) CordonExportFile = _m.Attribute(str) def __init__(self): #---Init internal variables self.TRACKER = _util.ProgressTracker(self.number_of_tasks) #init the ProgressTracker #---Set the defaults of parameters used by Modeller self.Scenario = _mm.scenario #Default is primary scenario def page(self): pb = _tmgTPB.TmgToolPageBuilder(self, title="Export Count Station-Link Correspondence File v%s" %self.version, description="Exports a link and countpost correspondence file.\ Contained witin, is the link on which each countpost is found.\ Assumes that count stations are defined by '@stn1'.", branding_text="- TMG Toolbox") if self.tool_run_msg != "": # to display messages in the page pb.tool_run_status(self.tool_run_msg_status) pb.add_header("EXPORT CORDON DATA FILE") pb.add_select_file(tool_attribute_name='CordonExportFile', window_type='save_file', file_filter='*.csv', title="Cordon Count File", note="Select Export Location:\ <ul><li>countpost_id</li>\ <li>link id (inode-jnode)</li>\ </ul>") return pb.render() def __call__(self, Scen, TruthTable): self.tool_run_msg = "" self.TRACKER.reset() self.Scenario = Scen self.CordonTruthTable = TruthTable try: self._Execute() except Exception as e: self.tool_run_msg = _m.PageBuilder.format_exception( e, _traceback.format_exc()) raise self.tool_run_msg = _m.PageBuilder.format_info("Done.") def run(self): self.tool_run_msg = "" self.TRACKER.reset() try: self._Execute() except Exception as e: self.tool_run_msg = _m.PageBuilder.format_exception( e, _traceback.format_exc()) raise self.tool_run_msg = _m.PageBuilder.format_info("Done.") <|fim▁hole|> def _Execute(self): with _m.logbook_trace(name="{classname} v{version}".format(classname=(self.__class__.__name__), version=self.version), attributes=self._GetAtts()): lines =[] for link in net.links(): if int(link['@stn1']) > 0: lines.append((link['@stn1'],link.id)) with open(self.CordonExportFile, 'w') as writer: writer.write("Countpost ID ,Link (i-node j-node)") for line in lines: line = [str(c) for c in line] writer.write("\n" + ','.join(line)) #----SUB FUNCTIONS--------------------------------------------------------------------------------- def _GetAtts(self): atts = { "Scenario" : str(self.Scenario.id), "Version": self.version, "self": self.__MODELLER_NAMESPACE__} return atts @_m.method(return_type=_m.TupleType) def percent_completed(self): return self.TRACKER.getProgress() @_m.method(return_type=unicode) def tool_run_msg_status(self): return self.tool_run_msg<|fim▁end|>
<|file_name|>samples_compact_yaml.py<|end_file_name|><|fim▁begin|>SAMPLES_YAML = { 'a': """\ - a1-a: [pk] - [A1] - [A2] - [B1] - [C1] - [C2] - [D1] - [E1] - [P1] """, 'b': """\ - a1-a: [pk] - [B1] - [C1] - [C2] - [D1] - [E1] - a1-b: [pk] - [B1] - [C1] - [C2] - [D1] - [E1] """, 'c': """\ - a1-a: [pk] - [C1] - [C2] - [D1] - a1-b: [pk] - [C1] - [C2] - [D1] - a1-c: [pk] - [C1] - [C2] - [D1] """, 'd': """\ - a1-a: [pk] - [D1] - a1-b: [pk] - [D1] - a1-c: [pk] - [D1] - a1-d: [pk] - [D1] """, 'e': """\ - a1-a: [pk] - [E1] - a1-b: [pk] - [E1] - a1-e: [pk] - [E1] """, 'f': """\ - a1-a: [pk] - [A1] - [D1] - a1-f: [pk, a] - [F1, null] - [F2, A1] - [F3, A1] - [F4, D1] """, 'g': """\ - a1-a: [pk] - [D1] - a1-b: [pk] - [D1] - a1-c: [pk] - [D1] - a1-d: [pk] - [D1] - a1-g: [pk, d] - [G1, D1] """, 'p': """\ - a1-a: [pk] - [A1] - [A2] - [B1] - [C1] - [C2] - [D1] - [E1] - [P1] """, 'o': """\<|fim▁hole|> - [D1] - a1-b: [pk] - [C1] - [C2] - [D1] - a1-c: [pk] - [C1] - [C2] - [D1] - a1-o: [pk, c, s] - [O1, null, null] - [O2, C1, null] - [O3, C2, O1] - [O4, D1, O3] - [O5, null, O5] """, 'm': """\ - a1-m: [pk] - [M1] - [M2] - [M3] - [M4] - [M5] """, 'm_d': """\ - a1-a: [pk] - [D1] - a1-b: [pk] - [D1] - a1-c: [pk] - [D1] - a1-d: [pk] - [D1] - a1-m: [pk] - [M3] - [M4] - a1-m_d: [pk, d, m] - [1, D1, M3] - [2, D1, M4] """, 'm_s': """\ - a1-m: [pk] - [M1] - [M2] - [M3] - [M4] - [M5] - a1-m_s: [pk, from_m, to_m] - [1, M2, M1] - [2, M1, M2] - [3, M4, M3] - [4, M3, M4] - [5, M5, M3] - [6, M3, M5] - [7, M5, M4] - [8, M4, M5] - [9, M5, M5] """, 'a_some': """\ - a1-a: [pk] - [A2] - [D1] """, 'a_some_a_b': """\ - a1-a: [pk] - [A2] - [D1] - a1-b: [pk] - [D1] """, 'f_a_d': """\ - a1-a: [pk] - [A1] - [D1] - a1-f: [pk, a] - [F1, null] - [F2, A1] - [F3, A1] - [F4, D1] """, 'd_a_f': """\ - a1-a: [pk] - [D1] - a1-b: [pk] - [D1] - a1-c: [pk] - [D1] - a1-d: [pk] - [D1] - a1-f: [pk, a] - [F4, D1] """, 'o_one_o_s': """\ - a1-a: [pk] - [C2] - [D1] - a1-b: [pk] - [C2] - [D1] - a1-c: [pk] - [C2] - [D1] - a1-o: [pk, c, s] - [O1, null, null] - [O3, C2, O1] - [O4, D1, O3] """, 'm_one_m_s': """\ - a1-m: [pk] - [M3] - [M4] - [M5] - a1-m_s: [pk, from_m, to_m] - [3, M4, M3] - [4, M3, M4] - [5, M5, M3] - [6, M3, M5] - [7, M5, M4] - [8, M4, M5] - [9, M5, M5] """, 'd_d_m': """\ - a1-a: [pk] - [D1] - a1-b: [pk] - [D1] - a1-c: [pk] - [D1] - a1-d: [pk] - [D1] - a1-m: [pk] - [M3] - [M4] - a1-m_d: [pk, d, m] - [1, D1, M3] - [2, D1, M4] """, 'd_d_m_m_s': """\ - a1-a: [pk] - [D1] - a1-b: [pk] - [D1] - a1-c: [pk] - [D1] - a1-d: [pk] - [D1] - a1-m: [pk] - [M3] - [M4] - [M5] - a1-m_d: [pk, d, m] - [1, D1, M3] - [2, D1, M4] - a1-m_s: [pk, from_m, to_m] - [3, M4, M3] - [4, M3, M4] - [5, M5, M3] - [6, M3, M5] - [7, M5, M4] - [8, M4, M5] - [9, M5, M5] """, 'a2': """\ - a2-article: [pk, headline] - [1, The only Review for The explicit AutoField] - a2-book: [pk, title] - [1, The explicit AutoField] - a2-bookreview: [pk, article_ptr] - [1, 1] """, 'a3': """\ - a3-piece: [pk] - [1] - a3-article: [pk, headline] - [1, The only Review for The common ancestor] - a3-book: [pk, title] - [1, The common ancestor] - a3-bookreview: [pk, article_ptr] - [1, 1] """, 'q': """\ - a4-question: [pk, pub_date, question_text] - [Q1, !!timestamp '2014-01-01 00:00:00', 'what question 1?'] - [Q2, !!timestamp '2014-01-02 00:00:00', 'what question 2?'] - [Q3, !!timestamp '2014-01-03 00:00:00', 'what question 3?'] """, 'q_r': """\ - a4-question: [pk, pub_date, question_text] - [Q1, !!timestamp '2014-01-01 00:00:00', 'what question 1?'] - [Q2, !!timestamp '2014-01-02 00:00:00', 'what question 2?'] - [Q3, !!timestamp '2014-01-03 00:00:00', 'what question 3?'] - a4-response: [pk, question, response_text, votes] - [R1, Q1, 'NULL', 0] - [R2, Q1, None, 111] - [R3, Q2, foo, 222] - [R4, Q2, bar, 333] - [R5, Q3, foobar, 444] """, 's': """\ - a4-sample: [pk, bool, comma, date, dec, float, nullbool, slug, text, time] - [S1, true, '[1, 2, 3]', 2014-02-01, '12.34', 1.23, false, abc, foobar, '01:01:00'] - [S2, false, '[4, 5, 6]', 2014-02-02, '56.78', 3.45, true, def, "\\xC2", '01:02:00'] - [S3, true, '[]', 2014-02-03, '-9.12', 6.78, null, '', '', '01:03:00'] """, }<|fim▁end|>
- a1-a: [pk] - [C1] - [C2]