file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
spot_launcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import boto.ec2 from boto.ec2.blockdevicemapping import BlockDeviceType from boto.ec2.blockdevicemapping import BlockDeviceMapping import time import copy import argparse import sys import pprint import os import yaml BASE_PATH = os.path.dirname(os.path.abspath(__file__)) CONFIG_PATH = os.path.join(BASE_PATH, '../configs') def launch_from_config(conn, instance_config_name, config_file_name): spot_requests_config = get_config(config_file_name) config = spot_requests_config[instance_config_name] mapping = create_mapping(config) print 'Launching %s instances'%(instance_config_name) print 'Instance parameters:' pp = pprint.PrettyPrinter(indent=4) pp.pprint(config) spot_req = conn.request_spot_instances( config['price'], config['ami_id'], count=config['count'], type=config['type'], key_name=config['key_name'], instance_type=config['instance_type'], placement_group=config['placement_group'], security_group_ids=config['security_groups'], subnet_id=config['subnet_id'], instance_profile_name=config['instance_profile_name'], block_device_map=mapping ) request_ids = [req.id for req in spot_req] print 'Waiting for fulfillment' instance_ids = wait_for_fulfillment(conn, request_ids, copy.deepcopy(request_ids)) if 'tags' in config: tag_instances(conn, instance_ids, config['tags']) return instance_ids def get_config(config_file_name): config_file = open(os.path.join(CONFIG_PATH, config_file_name)) config_dict = yaml.load(config_file.read()) return config_dict def create_mapping(config): if 'mapping' not in config: return None mapping = BlockDeviceMapping() for ephemeral_name, device_path in config['mapping'].iteritems(): ephemeral = BlockDeviceType() ephemeral.ephemeral_name = ephemeral_name mapping[device_path] = ephemeral return mapping def wait_for_fulfillment(conn, request_ids, pending_request_ids): """Loop through all pending request ids waiting for them to be fulfilled. If a request is fulfilled, remove it from pending_request_ids. If there are still pending requests, sleep and check again in 10 seconds. Only return when all spot requests have been fulfilled.""" instance_ids = [] failed_ids = [] time.sleep(10) pending_statuses = set(['pending-evaluation', 'pending-fulfillment']) while len(pending_request_ids) > 0: results = conn.get_all_spot_instance_requests( request_ids=pending_request_ids) for result in results: if result.status.code == 'fulfilled': pending_request_ids.pop(pending_request_ids.index(result.id)) print '\nspot request %s fulfilled!'%result.id instance_ids.append(result.instance_id) elif result.status.code not in pending_statuses: pending_request_ids.pop(pending_request_ids.index(result.id)) print '\nspot request %s could not be fulfilled. ' \ 'Status code: %s'%(result.id, result.status.code) failed_ids.append(result.id) if len(pending_request_ids) > 0: sys.stdout.write('.') sys.stdout.flush() time.sleep(10) if len(failed_ids) > 0: print 'The following spot requests ' \ 'have failed: %s'%(', '.join(failed_ids)) else: print 'All spot requests fulfilled!' return instance_ids def tag_instances(conn, instance_ids, tags): instances = conn.get_only_instances(instance_ids=instance_ids) for instance in instances: for key, value in tags.iteritems(): instance.add_tag(key=key, value=value) def main(): parser = argparse.ArgumentParser() parser.add_argument('instance', type=str, help='Instance config name to launch') parser.add_argument('-r', '--region', type=str, default='us-east-1', help='EC2 region name') parser.add_argument('-c', '--config-file', type=str, default='spot_requests.yml', help='Spot requests config file name') args = parser.parse_args() conn = boto.ec2.connect_to_region(args.region) config_file_name = args.config_file
launch_from_config(conn, instance_config_name, config_file_name) if __name__ == '__main__': main()
instance_config_name = args.instance
random_line_split
spot_launcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import boto.ec2 from boto.ec2.blockdevicemapping import BlockDeviceType from boto.ec2.blockdevicemapping import BlockDeviceMapping import time import copy import argparse import sys import pprint import os import yaml BASE_PATH = os.path.dirname(os.path.abspath(__file__)) CONFIG_PATH = os.path.join(BASE_PATH, '../configs') def launch_from_config(conn, instance_config_name, config_file_name): spot_requests_config = get_config(config_file_name) config = spot_requests_config[instance_config_name] mapping = create_mapping(config) print 'Launching %s instances'%(instance_config_name) print 'Instance parameters:' pp = pprint.PrettyPrinter(indent=4) pp.pprint(config) spot_req = conn.request_spot_instances( config['price'], config['ami_id'], count=config['count'], type=config['type'], key_name=config['key_name'], instance_type=config['instance_type'], placement_group=config['placement_group'], security_group_ids=config['security_groups'], subnet_id=config['subnet_id'], instance_profile_name=config['instance_profile_name'], block_device_map=mapping ) request_ids = [req.id for req in spot_req] print 'Waiting for fulfillment' instance_ids = wait_for_fulfillment(conn, request_ids, copy.deepcopy(request_ids)) if 'tags' in config: tag_instances(conn, instance_ids, config['tags']) return instance_ids def get_config(config_file_name):
def create_mapping(config): if 'mapping' not in config: return None mapping = BlockDeviceMapping() for ephemeral_name, device_path in config['mapping'].iteritems(): ephemeral = BlockDeviceType() ephemeral.ephemeral_name = ephemeral_name mapping[device_path] = ephemeral return mapping def wait_for_fulfillment(conn, request_ids, pending_request_ids): """Loop through all pending request ids waiting for them to be fulfilled. If a request is fulfilled, remove it from pending_request_ids. If there are still pending requests, sleep and check again in 10 seconds. Only return when all spot requests have been fulfilled.""" instance_ids = [] failed_ids = [] time.sleep(10) pending_statuses = set(['pending-evaluation', 'pending-fulfillment']) while len(pending_request_ids) > 0: results = conn.get_all_spot_instance_requests( request_ids=pending_request_ids) for result in results: if result.status.code == 'fulfilled': pending_request_ids.pop(pending_request_ids.index(result.id)) print '\nspot request %s fulfilled!'%result.id instance_ids.append(result.instance_id) elif result.status.code not in pending_statuses: pending_request_ids.pop(pending_request_ids.index(result.id)) print '\nspot request %s could not be fulfilled. ' \ 'Status code: %s'%(result.id, result.status.code) failed_ids.append(result.id) if len(pending_request_ids) > 0: sys.stdout.write('.') sys.stdout.flush() time.sleep(10) if len(failed_ids) > 0: print 'The following spot requests ' \ 'have failed: %s'%(', '.join(failed_ids)) else: print 'All spot requests fulfilled!' return instance_ids def tag_instances(conn, instance_ids, tags): instances = conn.get_only_instances(instance_ids=instance_ids) for instance in instances: for key, value in tags.iteritems(): instance.add_tag(key=key, value=value) def main(): parser = argparse.ArgumentParser() parser.add_argument('instance', type=str, help='Instance config name to launch') parser.add_argument('-r', '--region', type=str, default='us-east-1', help='EC2 region name') parser.add_argument('-c', '--config-file', type=str, default='spot_requests.yml', help='Spot requests config file name') args = parser.parse_args() conn = boto.ec2.connect_to_region(args.region) config_file_name = args.config_file instance_config_name = args.instance launch_from_config(conn, instance_config_name, config_file_name) if __name__ == '__main__': main()
config_file = open(os.path.join(CONFIG_PATH, config_file_name)) config_dict = yaml.load(config_file.read()) return config_dict
identifier_body
spot_launcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import boto.ec2 from boto.ec2.blockdevicemapping import BlockDeviceType from boto.ec2.blockdevicemapping import BlockDeviceMapping import time import copy import argparse import sys import pprint import os import yaml BASE_PATH = os.path.dirname(os.path.abspath(__file__)) CONFIG_PATH = os.path.join(BASE_PATH, '../configs') def launch_from_config(conn, instance_config_name, config_file_name): spot_requests_config = get_config(config_file_name) config = spot_requests_config[instance_config_name] mapping = create_mapping(config) print 'Launching %s instances'%(instance_config_name) print 'Instance parameters:' pp = pprint.PrettyPrinter(indent=4) pp.pprint(config) spot_req = conn.request_spot_instances( config['price'], config['ami_id'], count=config['count'], type=config['type'], key_name=config['key_name'], instance_type=config['instance_type'], placement_group=config['placement_group'], security_group_ids=config['security_groups'], subnet_id=config['subnet_id'], instance_profile_name=config['instance_profile_name'], block_device_map=mapping ) request_ids = [req.id for req in spot_req] print 'Waiting for fulfillment' instance_ids = wait_for_fulfillment(conn, request_ids, copy.deepcopy(request_ids)) if 'tags' in config:
return instance_ids def get_config(config_file_name): config_file = open(os.path.join(CONFIG_PATH, config_file_name)) config_dict = yaml.load(config_file.read()) return config_dict def create_mapping(config): if 'mapping' not in config: return None mapping = BlockDeviceMapping() for ephemeral_name, device_path in config['mapping'].iteritems(): ephemeral = BlockDeviceType() ephemeral.ephemeral_name = ephemeral_name mapping[device_path] = ephemeral return mapping def wait_for_fulfillment(conn, request_ids, pending_request_ids): """Loop through all pending request ids waiting for them to be fulfilled. If a request is fulfilled, remove it from pending_request_ids. If there are still pending requests, sleep and check again in 10 seconds. Only return when all spot requests have been fulfilled.""" instance_ids = [] failed_ids = [] time.sleep(10) pending_statuses = set(['pending-evaluation', 'pending-fulfillment']) while len(pending_request_ids) > 0: results = conn.get_all_spot_instance_requests( request_ids=pending_request_ids) for result in results: if result.status.code == 'fulfilled': pending_request_ids.pop(pending_request_ids.index(result.id)) print '\nspot request %s fulfilled!'%result.id instance_ids.append(result.instance_id) elif result.status.code not in pending_statuses: pending_request_ids.pop(pending_request_ids.index(result.id)) print '\nspot request %s could not be fulfilled. ' \ 'Status code: %s'%(result.id, result.status.code) failed_ids.append(result.id) if len(pending_request_ids) > 0: sys.stdout.write('.') sys.stdout.flush() time.sleep(10) if len(failed_ids) > 0: print 'The following spot requests ' \ 'have failed: %s'%(', '.join(failed_ids)) else: print 'All spot requests fulfilled!' return instance_ids def tag_instances(conn, instance_ids, tags): instances = conn.get_only_instances(instance_ids=instance_ids) for instance in instances: for key, value in tags.iteritems(): instance.add_tag(key=key, value=value) def main(): parser = argparse.ArgumentParser() parser.add_argument('instance', type=str, help='Instance config name to launch') parser.add_argument('-r', '--region', type=str, default='us-east-1', help='EC2 region name') parser.add_argument('-c', '--config-file', type=str, default='spot_requests.yml', help='Spot requests config file name') args = parser.parse_args() conn = boto.ec2.connect_to_region(args.region) config_file_name = args.config_file instance_config_name = args.instance launch_from_config(conn, instance_config_name, config_file_name) if __name__ == '__main__': main()
tag_instances(conn, instance_ids, config['tags'])
conditional_block
publish_test.js
'use strict'; const assert = require('assert'); const Bluebird = require('bluebird'); const Crypto = require('crypto'); const getAWSConfig = require('../aws_config'); const Ironium = require('../..'); const ms = require('ms'); const setup = require('../helpers'); (getAWSConfig.isAvailable ? describe : describe.skip)('Publish - AWS', function() { // We test that publish works by consuming from this queue // (which must be subscribed to the topic). let snsSubscribedQueue; const processedJobs = []; const randomValue = Crypto.randomBytes(32).toString('hex'); function processJob(notification)
before(setup); before(function() { snsSubscribedQueue = Ironium.queue('sns-foo-notification'); }); before(function() { Ironium.configure(getAWSConfig()); process.env.NODE_ENV = 'production'; }); before(function() { snsSubscribedQueue.eachJob(processJob); }); before(function() { return Ironium.publish('foo-notification', { value: randomValue }); }); before(function() { Ironium.start(); }); before(function() { return Bluebird.delay(ms('3s')); }); it('should have published to SNS and processed the job in SQS', function() { const processedJob = processedJobs.find(job => job.value === randomValue); assert(processedJob); }); after(function() { process.env.NODE_ENV = 'test'; Ironium.stop(); Ironium.configure({}); }); });
{ const job = JSON.parse(notification.Message); processedJobs.push(job); return Promise.resolve(); }
identifier_body
publish_test.js
'use strict'; const assert = require('assert'); const Bluebird = require('bluebird'); const Crypto = require('crypto'); const getAWSConfig = require('../aws_config'); const Ironium = require('../..'); const ms = require('ms'); const setup = require('../helpers'); (getAWSConfig.isAvailable ? describe : describe.skip)('Publish - AWS', function() {
const randomValue = Crypto.randomBytes(32).toString('hex'); function processJob(notification) { const job = JSON.parse(notification.Message); processedJobs.push(job); return Promise.resolve(); } before(setup); before(function() { snsSubscribedQueue = Ironium.queue('sns-foo-notification'); }); before(function() { Ironium.configure(getAWSConfig()); process.env.NODE_ENV = 'production'; }); before(function() { snsSubscribedQueue.eachJob(processJob); }); before(function() { return Ironium.publish('foo-notification', { value: randomValue }); }); before(function() { Ironium.start(); }); before(function() { return Bluebird.delay(ms('3s')); }); it('should have published to SNS and processed the job in SQS', function() { const processedJob = processedJobs.find(job => job.value === randomValue); assert(processedJob); }); after(function() { process.env.NODE_ENV = 'test'; Ironium.stop(); Ironium.configure({}); }); });
// We test that publish works by consuming from this queue // (which must be subscribed to the topic). let snsSubscribedQueue; const processedJobs = [];
random_line_split
publish_test.js
'use strict'; const assert = require('assert'); const Bluebird = require('bluebird'); const Crypto = require('crypto'); const getAWSConfig = require('../aws_config'); const Ironium = require('../..'); const ms = require('ms'); const setup = require('../helpers'); (getAWSConfig.isAvailable ? describe : describe.skip)('Publish - AWS', function() { // We test that publish works by consuming from this queue // (which must be subscribed to the topic). let snsSubscribedQueue; const processedJobs = []; const randomValue = Crypto.randomBytes(32).toString('hex'); function
(notification) { const job = JSON.parse(notification.Message); processedJobs.push(job); return Promise.resolve(); } before(setup); before(function() { snsSubscribedQueue = Ironium.queue('sns-foo-notification'); }); before(function() { Ironium.configure(getAWSConfig()); process.env.NODE_ENV = 'production'; }); before(function() { snsSubscribedQueue.eachJob(processJob); }); before(function() { return Ironium.publish('foo-notification', { value: randomValue }); }); before(function() { Ironium.start(); }); before(function() { return Bluebird.delay(ms('3s')); }); it('should have published to SNS and processed the job in SQS', function() { const processedJob = processedJobs.find(job => job.value === randomValue); assert(processedJob); }); after(function() { process.env.NODE_ENV = 'test'; Ironium.stop(); Ironium.configure({}); }); });
processJob
identifier_name
submissions.js
app.controller('submissions', ['$scope', '$http', '$rootScope', 'globalHelpers', function ($scope, $http, $rootScope, globalHelpers) { $scope.stats = {}; $scope.getUrlLanguages = function(gitUrlId){ globalHelpers.getUrlLanguagesPromise(gitUrlId).then( function (response){ $scope.stats[gitUrlId] = response.data.languages; }); } $scope.addForReview = function () { $scope.showWarning = false; $scope.showGithubWarning = false; if (!$scope.newName || !$scope.newUrl) { $scope.showWarning = true; return; } var _new_name = $scope.newName.trim(); var _new = $scope.newUrl.trim(); if (!_new || !_new_name)
if (!_new || !_new_name) { $scope.showWarning = true; return; } var _newUrl = globalHelpers.getLocation(_new); var pathArray = _newUrl.pathname.split('/'); isCommit = pathArray.indexOf('commit') > -1; isPR = pathArray.indexOf('pull') > -1; if (_newUrl.hostname != "github.com" || (!isCommit && !isPR)){ $scope.showGithubWarning = true; return; } var obj = JSON.parse('{"github_user": "' + $scope.github_user + '", "name": "' + _new_name + '", "url": "' + _new + '"}'); for (var i=0; i < $scope.existing.length; i++){ if (Object.keys($scope.existing[i])[0] == _new){ return; } } $scope.existing.push(obj); $http({ method: "post", url: "/add_for_review", headers: {'Content-Type': "application/json"}, data: obj }).success(function () { // console.log("success!"); }); $scope.showUWarning = false; $scope.showGithubWarning = false; $scope._new = ''; $rootScope.$broadcast('urlEntryChange', 'args'); }; $scope.removeUrl = function (url) { if(confirm("Are you sure you want to delete entry \"" + url["name"] + "\"?")){ for (var i=0; i < $scope.existing.length; i++){ if ($scope.existing[i]["url"] == url['url']){ $scope.existing.splice(i, 1) $http({ method: "post", url: "/remove_from_list", headers: {'Content-Type': "application/json"}, data: url }).success(function () { console.log("success!"); }); $rootScope.$broadcast('urlEntryChange', 'args'); } } } }; }]);
{ $scope.showWarning = true; return; }
conditional_block
submissions.js
app.controller('submissions', ['$scope', '$http', '$rootScope', 'globalHelpers', function ($scope, $http, $rootScope, globalHelpers) { $scope.stats = {}; $scope.getUrlLanguages = function(gitUrlId){ globalHelpers.getUrlLanguagesPromise(gitUrlId).then( function (response){ $scope.stats[gitUrlId] = response.data.languages; }); } $scope.addForReview = function () { $scope.showWarning = false; $scope.showGithubWarning = false; if (!$scope.newName || !$scope.newUrl) { $scope.showWarning = true; return; } var _new_name = $scope.newName.trim(); var _new = $scope.newUrl.trim(); if (!_new || !_new_name) { $scope.showWarning = true; return; } if (!_new || !_new_name) { $scope.showWarning = true; return; } var _newUrl = globalHelpers.getLocation(_new); var pathArray = _newUrl.pathname.split('/'); isCommit = pathArray.indexOf('commit') > -1; isPR = pathArray.indexOf('pull') > -1;
var obj = JSON.parse('{"github_user": "' + $scope.github_user + '", "name": "' + _new_name + '", "url": "' + _new + '"}'); for (var i=0; i < $scope.existing.length; i++){ if (Object.keys($scope.existing[i])[0] == _new){ return; } } $scope.existing.push(obj); $http({ method: "post", url: "/add_for_review", headers: {'Content-Type': "application/json"}, data: obj }).success(function () { // console.log("success!"); }); $scope.showUWarning = false; $scope.showGithubWarning = false; $scope._new = ''; $rootScope.$broadcast('urlEntryChange', 'args'); }; $scope.removeUrl = function (url) { if(confirm("Are you sure you want to delete entry \"" + url["name"] + "\"?")){ for (var i=0; i < $scope.existing.length; i++){ if ($scope.existing[i]["url"] == url['url']){ $scope.existing.splice(i, 1) $http({ method: "post", url: "/remove_from_list", headers: {'Content-Type': "application/json"}, data: url }).success(function () { console.log("success!"); }); $rootScope.$broadcast('urlEntryChange', 'args'); } } } }; }]);
if (_newUrl.hostname != "github.com" || (!isCommit && !isPR)){ $scope.showGithubWarning = true; return; }
random_line_split
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # 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 the "update_gcp_settings" module.""" import unittest from unittest import mock from google.auth.transport import requests from . import update_gcp_settings class UpdateGCPSettingsTest(unittest.TestCase): def test_initialize_command_line_args_enable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--enable"]) self.assertIsNotNone(actual) def
(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--disable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_organization_id_too_big(self): invalid_organization_id = 2**64 actual = update_gcp_settings.initialize_command_line_args( [f"--organization_id={invalid_organization_id}"]) self.assertIsNone(actual) def test_initialize_command_line_args_negative_organization_id(self): actual = update_gcp_settings.initialize_command_line_args( ["--organization_id=-1"]) self.assertIsNone(actual) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_http_error(self, mock_response, mock_session): mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=400) mock_response.raise_for_status.side_effect = ( requests.requests.exceptions.HTTPError()) with self.assertRaises(requests.requests.exceptions.HTTPError): update_gcp_settings.update_gcp_settings(mock_session, 123, True) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_happy_path(self, mock_response, mock_session): mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=200) update_gcp_settings.update_gcp_settings(mock_session, 123, True) if __name__ == "__main__": unittest.main()
test_initialize_command_line_args_disable_ingestion
identifier_name
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # 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 the "update_gcp_settings" module.""" import unittest from unittest import mock from google.auth.transport import requests from . import update_gcp_settings class UpdateGCPSettingsTest(unittest.TestCase): def test_initialize_command_line_args_enable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--enable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_disable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--disable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_organization_id_too_big(self): invalid_organization_id = 2**64 actual = update_gcp_settings.initialize_command_line_args( [f"--organization_id={invalid_organization_id}"]) self.assertIsNone(actual) def test_initialize_command_line_args_negative_organization_id(self): actual = update_gcp_settings.initialize_command_line_args( ["--organization_id=-1"]) self.assertIsNone(actual) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_http_error(self, mock_response, mock_session): mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=400) mock_response.raise_for_status.side_effect = ( requests.requests.exceptions.HTTPError()) with self.assertRaises(requests.requests.exceptions.HTTPError): update_gcp_settings.update_gcp_settings(mock_session, 123, True) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_happy_path(self, mock_response, mock_session): mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=200) update_gcp_settings.update_gcp_settings(mock_session, 123, True) if __name__ == "__main__":
unittest.main()
conditional_block
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # 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 the "update_gcp_settings" module.""" import unittest from unittest import mock from google.auth.transport import requests from . import update_gcp_settings class UpdateGCPSettingsTest(unittest.TestCase): def test_initialize_command_line_args_enable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--enable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_disable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--disable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_organization_id_too_big(self): invalid_organization_id = 2**64 actual = update_gcp_settings.initialize_command_line_args( [f"--organization_id={invalid_organization_id}"]) self.assertIsNone(actual) def test_initialize_command_line_args_negative_organization_id(self): actual = update_gcp_settings.initialize_command_line_args( ["--organization_id=-1"]) self.assertIsNone(actual) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_http_error(self, mock_response, mock_session): mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=400) mock_response.raise_for_status.side_effect = ( requests.requests.exceptions.HTTPError()) with self.assertRaises(requests.requests.exceptions.HTTPError): update_gcp_settings.update_gcp_settings(mock_session, 123, True) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_happy_path(self, mock_response, mock_session):
if __name__ == "__main__": unittest.main()
mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=200) update_gcp_settings.update_gcp_settings(mock_session, 123, True)
identifier_body
update_gcp_settings_test.py
# Copyright 2021 Google LLC # # 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 the "update_gcp_settings" module.""" import unittest from unittest import mock
class UpdateGCPSettingsTest(unittest.TestCase): def test_initialize_command_line_args_enable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--enable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_disable_ingestion(self): actual = update_gcp_settings.initialize_command_line_args( ["--credentials_file=./foo.json", "--organization_id=123", "--disable"]) self.assertIsNotNone(actual) def test_initialize_command_line_args_organization_id_too_big(self): invalid_organization_id = 2**64 actual = update_gcp_settings.initialize_command_line_args( [f"--organization_id={invalid_organization_id}"]) self.assertIsNone(actual) def test_initialize_command_line_args_negative_organization_id(self): actual = update_gcp_settings.initialize_command_line_args( ["--organization_id=-1"]) self.assertIsNone(actual) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_http_error(self, mock_response, mock_session): mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=400) mock_response.raise_for_status.side_effect = ( requests.requests.exceptions.HTTPError()) with self.assertRaises(requests.requests.exceptions.HTTPError): update_gcp_settings.update_gcp_settings(mock_session, 123, True) @mock.patch.object(requests, "AuthorizedSession", autospec=True) @mock.patch.object(requests.requests, "Response", autospec=True) def test_happy_path(self, mock_response, mock_session): mock_session.request.return_value = mock_response type(mock_response).status_code = mock.PropertyMock(return_value=200) update_gcp_settings.update_gcp_settings(mock_session, 123, True) if __name__ == "__main__": unittest.main()
from google.auth.transport import requests from . import update_gcp_settings
random_line_split
sokoban.rs
#![crate_type = "bin"] #![allow(unused_must_use)] //extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod sokoboard; mod sokoannotatedboard; fn main()
{ let args = os::args(); let contents; if args.len() > 1 { contents = File::open(&Path::new(args[1].as_slice())).read_to_str(); println!("Reading from file."); } else { contents = stdin().read_to_str(); println!("Reading from stdin."); } let board: SokoBoard = FromStr::from_str( contents.unwrap() ) .expect("Invalid sokoban board"); let annotated = SokoAnnotatedBoard::fromSokoBoard(board); do_sylvan(&annotated); }
identifier_body
sokoban.rs
#![crate_type = "bin"]
//extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod sokoboard; mod sokoannotatedboard; fn main() { let args = os::args(); let contents; if args.len() > 1 { contents = File::open(&Path::new(args[1].as_slice())).read_to_str(); println!("Reading from file."); } else { contents = stdin().read_to_str(); println!("Reading from stdin."); } let board: SokoBoard = FromStr::from_str( contents.unwrap() ) .expect("Invalid sokoban board"); let annotated = SokoAnnotatedBoard::fromSokoBoard(board); do_sylvan(&annotated); }
#![allow(unused_must_use)]
random_line_split
sokoban.rs
#![crate_type = "bin"] #![allow(unused_must_use)] //extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod sokoboard; mod sokoannotatedboard; fn
() { let args = os::args(); let contents; if args.len() > 1 { contents = File::open(&Path::new(args[1].as_slice())).read_to_str(); println!("Reading from file."); } else { contents = stdin().read_to_str(); println!("Reading from stdin."); } let board: SokoBoard = FromStr::from_str( contents.unwrap() ) .expect("Invalid sokoban board"); let annotated = SokoAnnotatedBoard::fromSokoBoard(board); do_sylvan(&annotated); }
main
identifier_name
sokoban.rs
#![crate_type = "bin"] #![allow(unused_must_use)] //extern crate native; extern crate libc; use std::from_str::{FromStr}; use std::io::{File}; use std::io::stdio::{stdin}; use std::path::{Path}; use std::os; use sokoboard::{SokoBoard}; use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan}; mod raw; mod bdd; mod sokoboard; mod sokoannotatedboard; fn main() { let args = os::args(); let contents; if args.len() > 1 { contents = File::open(&Path::new(args[1].as_slice())).read_to_str(); println!("Reading from file."); } else
let board: SokoBoard = FromStr::from_str( contents.unwrap() ) .expect("Invalid sokoban board"); let annotated = SokoAnnotatedBoard::fromSokoBoard(board); do_sylvan(&annotated); }
{ contents = stdin().read_to_str(); println!("Reading from stdin."); }
conditional_block
ibm2.py
# -*- coding: utf-8 -*- # Natural Language Toolkit: IBM Model 2 # # Copyright (C) 2001-2013 NLTK Project # Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Lexical translation model that considers word order. IBM Model 2 improves on Model 1 by accounting for word order. An alignment probability is introduced, a(i | j,l,m), which predicts a source word position, given its aligned target word's position. The EM algorithm used in Model 2 is: E step - In the training data, collect counts, weighted by prior probabilities. (a) count how many times a source language word is translated into a target language word (b) count how many times a particular position in the source sentence is aligned to a particular position in the target sentence M step - Estimate new probabilities based on the counts from the E step
j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in the target sentence s: A word in the source language t: A word in the target language References: Philipp Koehn. 2010. Statistical Machine Translation. Cambridge University Press, New York. Peter E Brown, Stephen A. Della Pietra, Vincent J. Della Pietra, and Robert L. Mercer. 1993. The Mathematics of Statistical Machine Translation: Parameter Estimation. Computational Linguistics, 19 (2), 263-311. """ from __future__ import division from collections import defaultdict from nltk.translate import AlignedSent from nltk.translate import Alignment from nltk.translate import IBMModel from nltk.translate import IBMModel1 from nltk.translate.ibm_model import Counts import warnings class IBMModel2(IBMModel): """ Lexical translation model that considers word order >>> bitext = [] >>> bitext.append(AlignedSent(['klein', 'ist', 'das', 'haus'], ['the', 'house', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus', 'ist', 'ja', 'groß'], ['the', 'house', 'is', 'big'])) >>> bitext.append(AlignedSent(['das', 'buch', 'ist', 'ja', 'klein'], ['the', 'book', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus'], ['the', 'house'])) >>> bitext.append(AlignedSent(['das', 'buch'], ['the', 'book'])) >>> bitext.append(AlignedSent(['ein', 'buch'], ['a', 'book'])) >>> ibm2 = IBMModel2(bitext, 5) >>> print(round(ibm2.translation_table['buch']['book'], 3)) 1.0 >>> print(round(ibm2.translation_table['das']['book'], 3)) 0.0 >>> print(round(ibm2.translation_table['buch'][None], 3)) 0.0 >>> print(round(ibm2.translation_table['ja'][None], 3)) 0.0 >>> print(ibm2.alignment_table[1][1][2][2]) 0.938... >>> print(round(ibm2.alignment_table[1][2][2][2], 3)) 0.0 >>> print(round(ibm2.alignment_table[2][2][4][5], 3)) 1.0 >>> test_sentence = bitext[2] >>> test_sentence.words ['das', 'buch', 'ist', 'ja', 'klein'] >>> test_sentence.mots ['the', 'book', 'is', 'small'] >>> test_sentence.alignment Alignment([(0, 0), (1, 1), (2, 2), (3, 2), (4, 3)]) """ def __init__(self, sentence_aligned_corpus, iterations, probability_tables=None): """ Train on ``sentence_aligned_corpus`` and create a lexical translation model and an alignment model. Translation direction is from ``AlignedSent.mots`` to ``AlignedSent.words``. :param sentence_aligned_corpus: Sentence-aligned parallel corpus :type sentence_aligned_corpus: list(AlignedSent) :param iterations: Number of iterations to run training algorithm :type iterations: int :param probability_tables: Optional. Use this to pass in custom probability values. If not specified, probabilities will be set to a uniform distribution, or some other sensible value. If specified, all the following entries must be present: ``translation_table``, ``alignment_table``. See ``IBMModel`` for the type and purpose of these tables. :type probability_tables: dict[str]: object """ super(IBMModel2, self).__init__(sentence_aligned_corpus) if probability_tables is None: # Get translation probabilities from IBM Model 1 # Run more iterations of training for Model 1, since it is # faster than Model 2 ibm1 = IBMModel1(sentence_aligned_corpus, 2 * iterations) self.translation_table = ibm1.translation_table self.set_uniform_probabilities(sentence_aligned_corpus) else: # Set user-defined probabilities self.translation_table = probability_tables['translation_table'] self.alignment_table = probability_tables['alignment_table'] for n in range(0, iterations): self.train(sentence_aligned_corpus) self.__align_all(sentence_aligned_corpus) def set_uniform_probabilities(self, sentence_aligned_corpus): # a(i | j,l,m) = 1 / (l+1) for all i, j, l, m l_m_combinations = set() for aligned_sentence in sentence_aligned_corpus: l = len(aligned_sentence.mots) m = len(aligned_sentence.words) if (l, m) not in l_m_combinations: l_m_combinations.add((l, m)) initial_prob = 1 / (l + 1) if initial_prob < IBMModel.MIN_PROB: warnings.warn("A source sentence is too long (" + str(l) + " words). Results may be less accurate.") for i in range(0, l + 1): for j in range(1, m + 1): self.alignment_table[i][j][l][m] = initial_prob def train(self, parallel_corpus): counts = Model2Counts() for aligned_sentence in parallel_corpus: src_sentence = [None] + aligned_sentence.mots trg_sentence = ['UNUSED'] + aligned_sentence.words # 1-indexed l = len(aligned_sentence.mots) m = len(aligned_sentence.words) # E step (a): Compute normalization factors to weigh counts total_count = self.prob_all_alignments(src_sentence, trg_sentence) # E step (b): Collect counts for j in range(1, m + 1): t = trg_sentence[j] for i in range(0, l + 1): s = src_sentence[i] count = self.prob_alignment_point( i, j, src_sentence, trg_sentence) normalized_count = count / total_count[t] counts.update_lexical_translation(normalized_count, s, t) counts.update_alignment(normalized_count, i, j, l, m) # M step: Update probabilities with maximum likelihood estimates self.maximize_lexical_translation_probabilities(counts) self.maximize_alignment_probabilities(counts) def maximize_alignment_probabilities(self, counts): MIN_PROB = IBMModel.MIN_PROB for i, j_s in counts.alignment.items(): for j, src_sentence_lengths in j_s.items(): for l, trg_sentence_lengths in src_sentence_lengths.items(): for m in trg_sentence_lengths: estimate = (counts.alignment[i][j][l][m] / counts.alignment_for_any_i[j][l][m]) self.alignment_table[i][j][l][m] = max(estimate, MIN_PROB) def prob_all_alignments(self, src_sentence, trg_sentence): """ Computes the probability of all possible word alignments, expressed as a marginal distribution over target words t Each entry in the return value represents the contribution to the total alignment probability by the target word t. To obtain probability(alignment | src_sentence, trg_sentence), simply sum the entries in the return value. :return: Probability of t for all s in ``src_sentence`` :rtype: dict(str): float """ alignment_prob_for_t = defaultdict(lambda: 0.0) for j in range(1, len(trg_sentence)): t = trg_sentence[j] for i in range(0, len(src_sentence)): alignment_prob_for_t[t] += self.prob_alignment_point( i, j, src_sentence, trg_sentence) return alignment_prob_for_t def prob_alignment_point(self, i, j, src_sentence, trg_sentence): """ Probability that position j in ``trg_sentence`` is aligned to position i in the ``src_sentence`` """ l = len(src_sentence) - 1 m = len(trg_sentence) - 1 s = src_sentence[i] t = trg_sentence[j] return self.translation_table[t][s] * self.alignment_table[i][j][l][m] def prob_t_a_given_s(self, alignment_info): """ Probability of target sentence and an alignment given the source sentence """ prob = 1.0 l = len(alignment_info.src_sentence) - 1 m = len(alignment_info.trg_sentence) - 1 for j, i in enumerate(alignment_info.alignment): if j == 0: continue # skip the dummy zeroeth element trg_word = alignment_info.trg_sentence[j] src_word = alignment_info.src_sentence[i] prob *= (self.translation_table[trg_word][src_word] * self.alignment_table[i][j][l][m]) return max(prob, IBMModel.MIN_PROB) def __align_all(self, parallel_corpus): for sentence_pair in parallel_corpus: self.__align(sentence_pair) def __align(self, sentence_pair): """ Determines the best word alignment for one sentence pair from the corpus that the model was trained on. The best alignment will be set in ``sentence_pair`` when the method returns. In contrast with the internal implementation of IBM models, the word indices in the ``Alignment`` are zero- indexed, not one-indexed. :param sentence_pair: A sentence in the source language and its counterpart sentence in the target language :type sentence_pair: AlignedSent """ best_alignment = [] l = len(sentence_pair.mots) m = len(sentence_pair.words) for j, trg_word in enumerate(sentence_pair.words): # Initialize trg_word to align with the NULL token best_prob = (self.translation_table[trg_word][None] * self.alignment_table[0][j + 1][l][m]) best_prob = max(best_prob, IBMModel.MIN_PROB) best_alignment_point = None for i, src_word in enumerate(sentence_pair.mots): align_prob = (self.translation_table[trg_word][src_word] * self.alignment_table[i + 1][j + 1][l][m]) if align_prob >= best_prob: best_prob = align_prob best_alignment_point = i best_alignment.append((j, best_alignment_point)) sentence_pair.alignment = Alignment(best_alignment) class Model2Counts(Counts): """ Data object to store counts of various parameters during training. Includes counts for alignment. """ def __init__(self): super(Model2Counts, self).__init__() self.alignment = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: defaultdict( lambda: 0.0)))) self.alignment_for_any_i = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: 0.0))) def update_lexical_translation(self, count, s, t): self.t_given_s[t][s] += count self.any_t_given_s[s] += count def update_alignment(self, count, i, j, l, m): self.alignment[i][j][l][m] += count self.alignment_for_any_i[j][l][m] += count
Notations: i: Position in the source sentence Valid values are 0 (for NULL), 1, 2, ..., length of source sentence
random_line_split
ibm2.py
# -*- coding: utf-8 -*- # Natural Language Toolkit: IBM Model 2 # # Copyright (C) 2001-2013 NLTK Project # Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Lexical translation model that considers word order. IBM Model 2 improves on Model 1 by accounting for word order. An alignment probability is introduced, a(i | j,l,m), which predicts a source word position, given its aligned target word's position. The EM algorithm used in Model 2 is: E step - In the training data, collect counts, weighted by prior probabilities. (a) count how many times a source language word is translated into a target language word (b) count how many times a particular position in the source sentence is aligned to a particular position in the target sentence M step - Estimate new probabilities based on the counts from the E step Notations: i: Position in the source sentence Valid values are 0 (for NULL), 1, 2, ..., length of source sentence j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in the target sentence s: A word in the source language t: A word in the target language References: Philipp Koehn. 2010. Statistical Machine Translation. Cambridge University Press, New York. Peter E Brown, Stephen A. Della Pietra, Vincent J. Della Pietra, and Robert L. Mercer. 1993. The Mathematics of Statistical Machine Translation: Parameter Estimation. Computational Linguistics, 19 (2), 263-311. """ from __future__ import division from collections import defaultdict from nltk.translate import AlignedSent from nltk.translate import Alignment from nltk.translate import IBMModel from nltk.translate import IBMModel1 from nltk.translate.ibm_model import Counts import warnings class IBMModel2(IBMModel): """ Lexical translation model that considers word order >>> bitext = [] >>> bitext.append(AlignedSent(['klein', 'ist', 'das', 'haus'], ['the', 'house', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus', 'ist', 'ja', 'groß'], ['the', 'house', 'is', 'big'])) >>> bitext.append(AlignedSent(['das', 'buch', 'ist', 'ja', 'klein'], ['the', 'book', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus'], ['the', 'house'])) >>> bitext.append(AlignedSent(['das', 'buch'], ['the', 'book'])) >>> bitext.append(AlignedSent(['ein', 'buch'], ['a', 'book'])) >>> ibm2 = IBMModel2(bitext, 5) >>> print(round(ibm2.translation_table['buch']['book'], 3)) 1.0 >>> print(round(ibm2.translation_table['das']['book'], 3)) 0.0 >>> print(round(ibm2.translation_table['buch'][None], 3)) 0.0 >>> print(round(ibm2.translation_table['ja'][None], 3)) 0.0 >>> print(ibm2.alignment_table[1][1][2][2]) 0.938... >>> print(round(ibm2.alignment_table[1][2][2][2], 3)) 0.0 >>> print(round(ibm2.alignment_table[2][2][4][5], 3)) 1.0 >>> test_sentence = bitext[2] >>> test_sentence.words ['das', 'buch', 'ist', 'ja', 'klein'] >>> test_sentence.mots ['the', 'book', 'is', 'small'] >>> test_sentence.alignment Alignment([(0, 0), (1, 1), (2, 2), (3, 2), (4, 3)]) """ def __init__(self, sentence_aligned_corpus, iterations, probability_tables=None): """ Train on ``sentence_aligned_corpus`` and create a lexical translation model and an alignment model. Translation direction is from ``AlignedSent.mots`` to ``AlignedSent.words``. :param sentence_aligned_corpus: Sentence-aligned parallel corpus :type sentence_aligned_corpus: list(AlignedSent) :param iterations: Number of iterations to run training algorithm :type iterations: int :param probability_tables: Optional. Use this to pass in custom probability values. If not specified, probabilities will be set to a uniform distribution, or some other sensible value. If specified, all the following entries must be present: ``translation_table``, ``alignment_table``. See ``IBMModel`` for the type and purpose of these tables. :type probability_tables: dict[str]: object """ super(IBMModel2, self).__init__(sentence_aligned_corpus) if probability_tables is None: # Get translation probabilities from IBM Model 1 # Run more iterations of training for Model 1, since it is # faster than Model 2 ibm1 = IBMModel1(sentence_aligned_corpus, 2 * iterations) self.translation_table = ibm1.translation_table self.set_uniform_probabilities(sentence_aligned_corpus) else: # Set user-defined probabilities self.translation_table = probability_tables['translation_table'] self.alignment_table = probability_tables['alignment_table'] for n in range(0, iterations): self.train(sentence_aligned_corpus) self.__align_all(sentence_aligned_corpus) def set_uniform_probabilities(self, sentence_aligned_corpus): # a(i | j,l,m) = 1 / (l+1) for all i, j, l, m l_m_combinations = set() for aligned_sentence in sentence_aligned_corpus: l = len(aligned_sentence.mots) m = len(aligned_sentence.words) if (l, m) not in l_m_combinations: l_m_combinations.add((l, m)) initial_prob = 1 / (l + 1) if initial_prob < IBMModel.MIN_PROB: warnings.warn("A source sentence is too long (" + str(l) + " words). Results may be less accurate.") for i in range(0, l + 1): for j in range(1, m + 1): self.alignment_table[i][j][l][m] = initial_prob def train(self, parallel_corpus): counts = Model2Counts() for aligned_sentence in parallel_corpus: src_sentence = [None] + aligned_sentence.mots trg_sentence = ['UNUSED'] + aligned_sentence.words # 1-indexed l = len(aligned_sentence.mots) m = len(aligned_sentence.words) # E step (a): Compute normalization factors to weigh counts total_count = self.prob_all_alignments(src_sentence, trg_sentence) # E step (b): Collect counts for j in range(1, m + 1): t = trg_sentence[j] for i in range(0, l + 1): s = src_sentence[i] count = self.prob_alignment_point( i, j, src_sentence, trg_sentence) normalized_count = count / total_count[t] counts.update_lexical_translation(normalized_count, s, t) counts.update_alignment(normalized_count, i, j, l, m) # M step: Update probabilities with maximum likelihood estimates self.maximize_lexical_translation_probabilities(counts) self.maximize_alignment_probabilities(counts) def maximize_alignment_probabilities(self, counts): MIN_PROB = IBMModel.MIN_PROB for i, j_s in counts.alignment.items(): for j, src_sentence_lengths in j_s.items(): for l, trg_sentence_lengths in src_sentence_lengths.items(): for m in trg_sentence_lengths: estimate = (counts.alignment[i][j][l][m] / counts.alignment_for_any_i[j][l][m]) self.alignment_table[i][j][l][m] = max(estimate, MIN_PROB) def prob_all_alignments(self, src_sentence, trg_sentence): """ Computes the probability of all possible word alignments, expressed as a marginal distribution over target words t Each entry in the return value represents the contribution to the total alignment probability by the target word t. To obtain probability(alignment | src_sentence, trg_sentence), simply sum the entries in the return value. :return: Probability of t for all s in ``src_sentence`` :rtype: dict(str): float """ alignment_prob_for_t = defaultdict(lambda: 0.0) for j in range(1, len(trg_sentence)): t = trg_sentence[j] for i in range(0, len(src_sentence)): alignment_prob_for_t[t] += self.prob_alignment_point( i, j, src_sentence, trg_sentence) return alignment_prob_for_t def prob_alignment_point(self, i, j, src_sentence, trg_sentence): """ Probability that position j in ``trg_sentence`` is aligned to position i in the ``src_sentence`` """ l = len(src_sentence) - 1 m = len(trg_sentence) - 1 s = src_sentence[i] t = trg_sentence[j] return self.translation_table[t][s] * self.alignment_table[i][j][l][m] def prob_t_a_given_s(self, alignment_info): """ Probability of target sentence and an alignment given the source sentence """ prob = 1.0 l = len(alignment_info.src_sentence) - 1 m = len(alignment_info.trg_sentence) - 1 for j, i in enumerate(alignment_info.alignment): if j == 0: continue # skip the dummy zeroeth element trg_word = alignment_info.trg_sentence[j] src_word = alignment_info.src_sentence[i] prob *= (self.translation_table[trg_word][src_word] * self.alignment_table[i][j][l][m]) return max(prob, IBMModel.MIN_PROB) def _
self, parallel_corpus): for sentence_pair in parallel_corpus: self.__align(sentence_pair) def __align(self, sentence_pair): """ Determines the best word alignment for one sentence pair from the corpus that the model was trained on. The best alignment will be set in ``sentence_pair`` when the method returns. In contrast with the internal implementation of IBM models, the word indices in the ``Alignment`` are zero- indexed, not one-indexed. :param sentence_pair: A sentence in the source language and its counterpart sentence in the target language :type sentence_pair: AlignedSent """ best_alignment = [] l = len(sentence_pair.mots) m = len(sentence_pair.words) for j, trg_word in enumerate(sentence_pair.words): # Initialize trg_word to align with the NULL token best_prob = (self.translation_table[trg_word][None] * self.alignment_table[0][j + 1][l][m]) best_prob = max(best_prob, IBMModel.MIN_PROB) best_alignment_point = None for i, src_word in enumerate(sentence_pair.mots): align_prob = (self.translation_table[trg_word][src_word] * self.alignment_table[i + 1][j + 1][l][m]) if align_prob >= best_prob: best_prob = align_prob best_alignment_point = i best_alignment.append((j, best_alignment_point)) sentence_pair.alignment = Alignment(best_alignment) class Model2Counts(Counts): """ Data object to store counts of various parameters during training. Includes counts for alignment. """ def __init__(self): super(Model2Counts, self).__init__() self.alignment = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: defaultdict( lambda: 0.0)))) self.alignment_for_any_i = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: 0.0))) def update_lexical_translation(self, count, s, t): self.t_given_s[t][s] += count self.any_t_given_s[s] += count def update_alignment(self, count, i, j, l, m): self.alignment[i][j][l][m] += count self.alignment_for_any_i[j][l][m] += count
_align_all(
identifier_name
ibm2.py
# -*- coding: utf-8 -*- # Natural Language Toolkit: IBM Model 2 # # Copyright (C) 2001-2013 NLTK Project # Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Lexical translation model that considers word order. IBM Model 2 improves on Model 1 by accounting for word order. An alignment probability is introduced, a(i | j,l,m), which predicts a source word position, given its aligned target word's position. The EM algorithm used in Model 2 is: E step - In the training data, collect counts, weighted by prior probabilities. (a) count how many times a source language word is translated into a target language word (b) count how many times a particular position in the source sentence is aligned to a particular position in the target sentence M step - Estimate new probabilities based on the counts from the E step Notations: i: Position in the source sentence Valid values are 0 (for NULL), 1, 2, ..., length of source sentence j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in the target sentence s: A word in the source language t: A word in the target language References: Philipp Koehn. 2010. Statistical Machine Translation. Cambridge University Press, New York. Peter E Brown, Stephen A. Della Pietra, Vincent J. Della Pietra, and Robert L. Mercer. 1993. The Mathematics of Statistical Machine Translation: Parameter Estimation. Computational Linguistics, 19 (2), 263-311. """ from __future__ import division from collections import defaultdict from nltk.translate import AlignedSent from nltk.translate import Alignment from nltk.translate import IBMModel from nltk.translate import IBMModel1 from nltk.translate.ibm_model import Counts import warnings class IBMModel2(IBMModel):
class Model2Counts(Counts): """ Data object to store counts of various parameters during training. Includes counts for alignment. """ def __init__(self): super(Model2Counts, self).__init__() self.alignment = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: defaultdict( lambda: 0.0)))) self.alignment_for_any_i = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: 0.0))) def update_lexical_translation(self, count, s, t): self.t_given_s[t][s] += count self.any_t_given_s[s] += count def update_alignment(self, count, i, j, l, m): self.alignment[i][j][l][m] += count self.alignment_for_any_i[j][l][m] += count
""" Lexical translation model that considers word order >>> bitext = [] >>> bitext.append(AlignedSent(['klein', 'ist', 'das', 'haus'], ['the', 'house', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus', 'ist', 'ja', 'groß'], ['the', 'house', 'is', 'big'])) >>> bitext.append(AlignedSent(['das', 'buch', 'ist', 'ja', 'klein'], ['the', 'book', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus'], ['the', 'house'])) >>> bitext.append(AlignedSent(['das', 'buch'], ['the', 'book'])) >>> bitext.append(AlignedSent(['ein', 'buch'], ['a', 'book'])) >>> ibm2 = IBMModel2(bitext, 5) >>> print(round(ibm2.translation_table['buch']['book'], 3)) 1.0 >>> print(round(ibm2.translation_table['das']['book'], 3)) 0.0 >>> print(round(ibm2.translation_table['buch'][None], 3)) 0.0 >>> print(round(ibm2.translation_table['ja'][None], 3)) 0.0 >>> print(ibm2.alignment_table[1][1][2][2]) 0.938... >>> print(round(ibm2.alignment_table[1][2][2][2], 3)) 0.0 >>> print(round(ibm2.alignment_table[2][2][4][5], 3)) 1.0 >>> test_sentence = bitext[2] >>> test_sentence.words ['das', 'buch', 'ist', 'ja', 'klein'] >>> test_sentence.mots ['the', 'book', 'is', 'small'] >>> test_sentence.alignment Alignment([(0, 0), (1, 1), (2, 2), (3, 2), (4, 3)]) """ def __init__(self, sentence_aligned_corpus, iterations, probability_tables=None): """ Train on ``sentence_aligned_corpus`` and create a lexical translation model and an alignment model. Translation direction is from ``AlignedSent.mots`` to ``AlignedSent.words``. :param sentence_aligned_corpus: Sentence-aligned parallel corpus :type sentence_aligned_corpus: list(AlignedSent) :param iterations: Number of iterations to run training algorithm :type iterations: int :param probability_tables: Optional. Use this to pass in custom probability values. If not specified, probabilities will be set to a uniform distribution, or some other sensible value. If specified, all the following entries must be present: ``translation_table``, ``alignment_table``. See ``IBMModel`` for the type and purpose of these tables. :type probability_tables: dict[str]: object """ super(IBMModel2, self).__init__(sentence_aligned_corpus) if probability_tables is None: # Get translation probabilities from IBM Model 1 # Run more iterations of training for Model 1, since it is # faster than Model 2 ibm1 = IBMModel1(sentence_aligned_corpus, 2 * iterations) self.translation_table = ibm1.translation_table self.set_uniform_probabilities(sentence_aligned_corpus) else: # Set user-defined probabilities self.translation_table = probability_tables['translation_table'] self.alignment_table = probability_tables['alignment_table'] for n in range(0, iterations): self.train(sentence_aligned_corpus) self.__align_all(sentence_aligned_corpus) def set_uniform_probabilities(self, sentence_aligned_corpus): # a(i | j,l,m) = 1 / (l+1) for all i, j, l, m l_m_combinations = set() for aligned_sentence in sentence_aligned_corpus: l = len(aligned_sentence.mots) m = len(aligned_sentence.words) if (l, m) not in l_m_combinations: l_m_combinations.add((l, m)) initial_prob = 1 / (l + 1) if initial_prob < IBMModel.MIN_PROB: warnings.warn("A source sentence is too long (" + str(l) + " words). Results may be less accurate.") for i in range(0, l + 1): for j in range(1, m + 1): self.alignment_table[i][j][l][m] = initial_prob def train(self, parallel_corpus): counts = Model2Counts() for aligned_sentence in parallel_corpus: src_sentence = [None] + aligned_sentence.mots trg_sentence = ['UNUSED'] + aligned_sentence.words # 1-indexed l = len(aligned_sentence.mots) m = len(aligned_sentence.words) # E step (a): Compute normalization factors to weigh counts total_count = self.prob_all_alignments(src_sentence, trg_sentence) # E step (b): Collect counts for j in range(1, m + 1): t = trg_sentence[j] for i in range(0, l + 1): s = src_sentence[i] count = self.prob_alignment_point( i, j, src_sentence, trg_sentence) normalized_count = count / total_count[t] counts.update_lexical_translation(normalized_count, s, t) counts.update_alignment(normalized_count, i, j, l, m) # M step: Update probabilities with maximum likelihood estimates self.maximize_lexical_translation_probabilities(counts) self.maximize_alignment_probabilities(counts) def maximize_alignment_probabilities(self, counts): MIN_PROB = IBMModel.MIN_PROB for i, j_s in counts.alignment.items(): for j, src_sentence_lengths in j_s.items(): for l, trg_sentence_lengths in src_sentence_lengths.items(): for m in trg_sentence_lengths: estimate = (counts.alignment[i][j][l][m] / counts.alignment_for_any_i[j][l][m]) self.alignment_table[i][j][l][m] = max(estimate, MIN_PROB) def prob_all_alignments(self, src_sentence, trg_sentence): """ Computes the probability of all possible word alignments, expressed as a marginal distribution over target words t Each entry in the return value represents the contribution to the total alignment probability by the target word t. To obtain probability(alignment | src_sentence, trg_sentence), simply sum the entries in the return value. :return: Probability of t for all s in ``src_sentence`` :rtype: dict(str): float """ alignment_prob_for_t = defaultdict(lambda: 0.0) for j in range(1, len(trg_sentence)): t = trg_sentence[j] for i in range(0, len(src_sentence)): alignment_prob_for_t[t] += self.prob_alignment_point( i, j, src_sentence, trg_sentence) return alignment_prob_for_t def prob_alignment_point(self, i, j, src_sentence, trg_sentence): """ Probability that position j in ``trg_sentence`` is aligned to position i in the ``src_sentence`` """ l = len(src_sentence) - 1 m = len(trg_sentence) - 1 s = src_sentence[i] t = trg_sentence[j] return self.translation_table[t][s] * self.alignment_table[i][j][l][m] def prob_t_a_given_s(self, alignment_info): """ Probability of target sentence and an alignment given the source sentence """ prob = 1.0 l = len(alignment_info.src_sentence) - 1 m = len(alignment_info.trg_sentence) - 1 for j, i in enumerate(alignment_info.alignment): if j == 0: continue # skip the dummy zeroeth element trg_word = alignment_info.trg_sentence[j] src_word = alignment_info.src_sentence[i] prob *= (self.translation_table[trg_word][src_word] * self.alignment_table[i][j][l][m]) return max(prob, IBMModel.MIN_PROB) def __align_all(self, parallel_corpus): for sentence_pair in parallel_corpus: self.__align(sentence_pair) def __align(self, sentence_pair): """ Determines the best word alignment for one sentence pair from the corpus that the model was trained on. The best alignment will be set in ``sentence_pair`` when the method returns. In contrast with the internal implementation of IBM models, the word indices in the ``Alignment`` are zero- indexed, not one-indexed. :param sentence_pair: A sentence in the source language and its counterpart sentence in the target language :type sentence_pair: AlignedSent """ best_alignment = [] l = len(sentence_pair.mots) m = len(sentence_pair.words) for j, trg_word in enumerate(sentence_pair.words): # Initialize trg_word to align with the NULL token best_prob = (self.translation_table[trg_word][None] * self.alignment_table[0][j + 1][l][m]) best_prob = max(best_prob, IBMModel.MIN_PROB) best_alignment_point = None for i, src_word in enumerate(sentence_pair.mots): align_prob = (self.translation_table[trg_word][src_word] * self.alignment_table[i + 1][j + 1][l][m]) if align_prob >= best_prob: best_prob = align_prob best_alignment_point = i best_alignment.append((j, best_alignment_point)) sentence_pair.alignment = Alignment(best_alignment)
identifier_body
ibm2.py
# -*- coding: utf-8 -*- # Natural Language Toolkit: IBM Model 2 # # Copyright (C) 2001-2013 NLTK Project # Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Lexical translation model that considers word order. IBM Model 2 improves on Model 1 by accounting for word order. An alignment probability is introduced, a(i | j,l,m), which predicts a source word position, given its aligned target word's position. The EM algorithm used in Model 2 is: E step - In the training data, collect counts, weighted by prior probabilities. (a) count how many times a source language word is translated into a target language word (b) count how many times a particular position in the source sentence is aligned to a particular position in the target sentence M step - Estimate new probabilities based on the counts from the E step Notations: i: Position in the source sentence Valid values are 0 (for NULL), 1, 2, ..., length of source sentence j: Position in the target sentence Valid values are 1, 2, ..., length of target sentence l: Number of words in the source sentence, excluding NULL m: Number of words in the target sentence s: A word in the source language t: A word in the target language References: Philipp Koehn. 2010. Statistical Machine Translation. Cambridge University Press, New York. Peter E Brown, Stephen A. Della Pietra, Vincent J. Della Pietra, and Robert L. Mercer. 1993. The Mathematics of Statistical Machine Translation: Parameter Estimation. Computational Linguistics, 19 (2), 263-311. """ from __future__ import division from collections import defaultdict from nltk.translate import AlignedSent from nltk.translate import Alignment from nltk.translate import IBMModel from nltk.translate import IBMModel1 from nltk.translate.ibm_model import Counts import warnings class IBMModel2(IBMModel): """ Lexical translation model that considers word order >>> bitext = [] >>> bitext.append(AlignedSent(['klein', 'ist', 'das', 'haus'], ['the', 'house', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus', 'ist', 'ja', 'groß'], ['the', 'house', 'is', 'big'])) >>> bitext.append(AlignedSent(['das', 'buch', 'ist', 'ja', 'klein'], ['the', 'book', 'is', 'small'])) >>> bitext.append(AlignedSent(['das', 'haus'], ['the', 'house'])) >>> bitext.append(AlignedSent(['das', 'buch'], ['the', 'book'])) >>> bitext.append(AlignedSent(['ein', 'buch'], ['a', 'book'])) >>> ibm2 = IBMModel2(bitext, 5) >>> print(round(ibm2.translation_table['buch']['book'], 3)) 1.0 >>> print(round(ibm2.translation_table['das']['book'], 3)) 0.0 >>> print(round(ibm2.translation_table['buch'][None], 3)) 0.0 >>> print(round(ibm2.translation_table['ja'][None], 3)) 0.0 >>> print(ibm2.alignment_table[1][1][2][2]) 0.938... >>> print(round(ibm2.alignment_table[1][2][2][2], 3)) 0.0 >>> print(round(ibm2.alignment_table[2][2][4][5], 3)) 1.0 >>> test_sentence = bitext[2] >>> test_sentence.words ['das', 'buch', 'ist', 'ja', 'klein'] >>> test_sentence.mots ['the', 'book', 'is', 'small'] >>> test_sentence.alignment Alignment([(0, 0), (1, 1), (2, 2), (3, 2), (4, 3)]) """ def __init__(self, sentence_aligned_corpus, iterations, probability_tables=None): """ Train on ``sentence_aligned_corpus`` and create a lexical translation model and an alignment model. Translation direction is from ``AlignedSent.mots`` to ``AlignedSent.words``. :param sentence_aligned_corpus: Sentence-aligned parallel corpus :type sentence_aligned_corpus: list(AlignedSent) :param iterations: Number of iterations to run training algorithm :type iterations: int :param probability_tables: Optional. Use this to pass in custom probability values. If not specified, probabilities will be set to a uniform distribution, or some other sensible value. If specified, all the following entries must be present: ``translation_table``, ``alignment_table``. See ``IBMModel`` for the type and purpose of these tables. :type probability_tables: dict[str]: object """ super(IBMModel2, self).__init__(sentence_aligned_corpus) if probability_tables is None: # Get translation probabilities from IBM Model 1 # Run more iterations of training for Model 1, since it is # faster than Model 2 ibm1 = IBMModel1(sentence_aligned_corpus, 2 * iterations) self.translation_table = ibm1.translation_table self.set_uniform_probabilities(sentence_aligned_corpus) else: # Set user-defined probabilities self.translation_table = probability_tables['translation_table'] self.alignment_table = probability_tables['alignment_table'] for n in range(0, iterations): self.train(sentence_aligned_corpus) self.__align_all(sentence_aligned_corpus) def set_uniform_probabilities(self, sentence_aligned_corpus): # a(i | j,l,m) = 1 / (l+1) for all i, j, l, m l_m_combinations = set() for aligned_sentence in sentence_aligned_corpus: l = len(aligned_sentence.mots) m = len(aligned_sentence.words) if (l, m) not in l_m_combinations: l_m_combinations.add((l, m)) initial_prob = 1 / (l + 1) if initial_prob < IBMModel.MIN_PROB: warnings.warn("A source sentence is too long (" + str(l) + " words). Results may be less accurate.") for i in range(0, l + 1): for j in range(1, m + 1): self.alignment_table[i][j][l][m] = initial_prob def train(self, parallel_corpus): counts = Model2Counts() for aligned_sentence in parallel_corpus: src_sentence = [None] + aligned_sentence.mots trg_sentence = ['UNUSED'] + aligned_sentence.words # 1-indexed l = len(aligned_sentence.mots) m = len(aligned_sentence.words) # E step (a): Compute normalization factors to weigh counts total_count = self.prob_all_alignments(src_sentence, trg_sentence) # E step (b): Collect counts for j in range(1, m + 1): t = trg_sentence[j] for i in range(0, l + 1): s = src_sentence[i] count = self.prob_alignment_point( i, j, src_sentence, trg_sentence) normalized_count = count / total_count[t] counts.update_lexical_translation(normalized_count, s, t) counts.update_alignment(normalized_count, i, j, l, m) # M step: Update probabilities with maximum likelihood estimates self.maximize_lexical_translation_probabilities(counts) self.maximize_alignment_probabilities(counts) def maximize_alignment_probabilities(self, counts): MIN_PROB = IBMModel.MIN_PROB for i, j_s in counts.alignment.items(): for j, src_sentence_lengths in j_s.items(): for l, trg_sentence_lengths in src_sentence_lengths.items(): for m in trg_sentence_lengths: estimate = (counts.alignment[i][j][l][m] / counts.alignment_for_any_i[j][l][m]) self.alignment_table[i][j][l][m] = max(estimate, MIN_PROB) def prob_all_alignments(self, src_sentence, trg_sentence): """ Computes the probability of all possible word alignments, expressed as a marginal distribution over target words t Each entry in the return value represents the contribution to the total alignment probability by the target word t. To obtain probability(alignment | src_sentence, trg_sentence), simply sum the entries in the return value. :return: Probability of t for all s in ``src_sentence`` :rtype: dict(str): float """ alignment_prob_for_t = defaultdict(lambda: 0.0) for j in range(1, len(trg_sentence)): t = trg_sentence[j] for i in range(0, len(src_sentence)): a
return alignment_prob_for_t def prob_alignment_point(self, i, j, src_sentence, trg_sentence): """ Probability that position j in ``trg_sentence`` is aligned to position i in the ``src_sentence`` """ l = len(src_sentence) - 1 m = len(trg_sentence) - 1 s = src_sentence[i] t = trg_sentence[j] return self.translation_table[t][s] * self.alignment_table[i][j][l][m] def prob_t_a_given_s(self, alignment_info): """ Probability of target sentence and an alignment given the source sentence """ prob = 1.0 l = len(alignment_info.src_sentence) - 1 m = len(alignment_info.trg_sentence) - 1 for j, i in enumerate(alignment_info.alignment): if j == 0: continue # skip the dummy zeroeth element trg_word = alignment_info.trg_sentence[j] src_word = alignment_info.src_sentence[i] prob *= (self.translation_table[trg_word][src_word] * self.alignment_table[i][j][l][m]) return max(prob, IBMModel.MIN_PROB) def __align_all(self, parallel_corpus): for sentence_pair in parallel_corpus: self.__align(sentence_pair) def __align(self, sentence_pair): """ Determines the best word alignment for one sentence pair from the corpus that the model was trained on. The best alignment will be set in ``sentence_pair`` when the method returns. In contrast with the internal implementation of IBM models, the word indices in the ``Alignment`` are zero- indexed, not one-indexed. :param sentence_pair: A sentence in the source language and its counterpart sentence in the target language :type sentence_pair: AlignedSent """ best_alignment = [] l = len(sentence_pair.mots) m = len(sentence_pair.words) for j, trg_word in enumerate(sentence_pair.words): # Initialize trg_word to align with the NULL token best_prob = (self.translation_table[trg_word][None] * self.alignment_table[0][j + 1][l][m]) best_prob = max(best_prob, IBMModel.MIN_PROB) best_alignment_point = None for i, src_word in enumerate(sentence_pair.mots): align_prob = (self.translation_table[trg_word][src_word] * self.alignment_table[i + 1][j + 1][l][m]) if align_prob >= best_prob: best_prob = align_prob best_alignment_point = i best_alignment.append((j, best_alignment_point)) sentence_pair.alignment = Alignment(best_alignment) class Model2Counts(Counts): """ Data object to store counts of various parameters during training. Includes counts for alignment. """ def __init__(self): super(Model2Counts, self).__init__() self.alignment = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: defaultdict( lambda: 0.0)))) self.alignment_for_any_i = defaultdict( lambda: defaultdict(lambda: defaultdict(lambda: 0.0))) def update_lexical_translation(self, count, s, t): self.t_given_s[t][s] += count self.any_t_given_s[s] += count def update_alignment(self, count, i, j, l, m): self.alignment[i][j][l][m] += count self.alignment_for_any_i[j][l][m] += count
lignment_prob_for_t[t] += self.prob_alignment_point( i, j, src_sentence, trg_sentence)
conditional_block
config.rs
use errors::*; use modules::{centerdevice, pocket, slack}; use std::fs::File; use std::io::Read; use std::path::Path; use toml; #[derive(Debug, Deserialize)] #[serde(tag = "format")] #[derive(PartialOrd, PartialEq, Eq)] #[derive(Clone, Copy)] pub enum OutputFormat { JSON, HUMAN, } impl<'a> From<&'a str> for OutputFormat { fn
(format: &'a str) -> Self { let format_sane: &str = &format.to_string().to_uppercase(); match format_sane { "JSON" => OutputFormat::JSON, _ => OutputFormat::HUMAN } } } #[derive(Debug, Deserialize)] #[serde(tag = "verbosity")] #[derive(PartialOrd, PartialEq, Eq)] #[derive(Clone, Copy)] pub enum Verbosity { VERBOSE = 1, NORMAL = 2, QUIET = 3, } #[derive(Debug, Deserialize)] pub struct GeneralConfig { pub cache_dir: String, pub output_format: OutputFormat, pub verbosity: Verbosity, } #[derive(Debug, Deserialize)] pub struct Config { pub general: GeneralConfig, pub centerdevice: centerdevice::CenterDeviceConfig, pub pocket: pocket::PocketConfig, pub slack: slack::SlackConfig, } impl Config { pub fn from_file(file_path: &Path) -> Result<Config> { let mut config_file = File::open(file_path).chain_err(|| "Could not open config file.")?; let mut config_content = String::new(); config_file.read_to_string(&mut config_content).chain_err(|| "Could not read config file.")?; let config: Config = toml::from_str(&config_content).chain_err(|| "Could not parse config file.")?; Ok(config) } }
from
identifier_name
config.rs
use errors::*; use modules::{centerdevice, pocket, slack}; use std::fs::File; use std::io::Read; use std::path::Path;
#[derive(PartialOrd, PartialEq, Eq)] #[derive(Clone, Copy)] pub enum OutputFormat { JSON, HUMAN, } impl<'a> From<&'a str> for OutputFormat { fn from(format: &'a str) -> Self { let format_sane: &str = &format.to_string().to_uppercase(); match format_sane { "JSON" => OutputFormat::JSON, _ => OutputFormat::HUMAN } } } #[derive(Debug, Deserialize)] #[serde(tag = "verbosity")] #[derive(PartialOrd, PartialEq, Eq)] #[derive(Clone, Copy)] pub enum Verbosity { VERBOSE = 1, NORMAL = 2, QUIET = 3, } #[derive(Debug, Deserialize)] pub struct GeneralConfig { pub cache_dir: String, pub output_format: OutputFormat, pub verbosity: Verbosity, } #[derive(Debug, Deserialize)] pub struct Config { pub general: GeneralConfig, pub centerdevice: centerdevice::CenterDeviceConfig, pub pocket: pocket::PocketConfig, pub slack: slack::SlackConfig, } impl Config { pub fn from_file(file_path: &Path) -> Result<Config> { let mut config_file = File::open(file_path).chain_err(|| "Could not open config file.")?; let mut config_content = String::new(); config_file.read_to_string(&mut config_content).chain_err(|| "Could not read config file.")?; let config: Config = toml::from_str(&config_content).chain_err(|| "Could not parse config file.")?; Ok(config) } }
use toml; #[derive(Debug, Deserialize)] #[serde(tag = "format")]
random_line_split
label_image.py
import tensorflow as tf, sys image_path = sys.argv[1] # Read in the image_data image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile("/cellule/retrained_labels.txt")] # Unpersists graph from file with tf.gfile.FastGFile("/cellule/retrained_graph.pb", 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') with tf.Session() as sess: # Feed the image_data as input to the graph and get first prediction softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') predictions = sess.run(softmax_tensor, \ {'DecodeJpeg/contents:0': image_data}) # Sort to show labels of first prediction in order of confidence top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] for node_id in top_k:
# To run the program - docker run -it -v ~/Desktop/cellule/:/cellule/ gcr.io/tensorflow/tensorflow:latest-devel # Enter the above line of code in the docker command prompt # Then enter - python /cellule/label_image.py <image_location> next to the # in the docker command prompt
human_string = label_lines[node_id] score = predictions[0][node_id] print('%s (score = %.5f)' % (human_string, score))
conditional_block
label_image.py
import tensorflow as tf, sys image_path = sys.argv[1] # Read in the image_data image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile("/cellule/retrained_labels.txt")] # Unpersists graph from file with tf.gfile.FastGFile("/cellule/retrained_graph.pb", 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') with tf.Session() as sess: # Feed the image_data as input to the graph and get first prediction softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') predictions = sess.run(softmax_tensor, \ {'DecodeJpeg/contents:0': image_data}) # Sort to show labels of first prediction in order of confidence top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] for node_id in top_k: human_string = label_lines[node_id] score = predictions[0][node_id] print('%s (score = %.5f)' % (human_string, score))
# To run the program - docker run -it -v ~/Desktop/cellule/:/cellule/ gcr.io/tensorflow/tensorflow:latest-devel # Enter the above line of code in the docker command prompt # Then enter - python /cellule/label_image.py <image_location> next to the # in the docker command prompt
random_line_split
pt-br.js
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.lang['pt-br'] = { "editor": "Editor de Texto", "editorPanel": "Rich Text Editor panel", "common": { "editorHelp": "Pressione ALT+0 para ajuda", "browseServer": "Localizar no Servidor", "url": "URL", "protocol": "Protocolo", "upload": "Enviar ao Servidor", "uploadSubmit": "Enviar para o Servidor", "image": "Imagem", "flash": "Flash", "form": "Formulário", "checkbox": "Caixa de Seleção", "radio": "Botão de Opção", "textField": "Caixa de Texto", "textarea": "Área de Texto", "hiddenField": "Campo Oculto", "button": "Botão", "select": "Caixa de Listagem", "imageButton": "Botão de Imagem", "notSet": "<não ajustado>", "id": "Id", "name": "Nome", "langDir": "Direção do idioma", "langDirLtr": "Esquerda para Direita (LTR)", "langDirRtl": "Direita para Esquerda (RTL)", "langCode": "Idioma", "longDescr": "Descrição da URL", "cssClass": "Classe de CSS", "advisoryTitle": "Título", "cssStyle": "Estilos", "ok": "OK", "cancel": "Cancelar", "close": "Fechar", "preview": "Visualizar", "resize": "Arraste para redimensionar", "generalTab": "Geral", "advancedTab": "Avançado", "validateNumberFailed": "Este valor não é um número.", "confirmNewPage": "Todas as mudanças não salvas serão perdidas. Tem certeza de que quer abrir uma nova página?", "confirmCancel": "Algumas opções foram alteradas. Tem certeza de que quer fechar a caixa de diálogo?", "options": "Opções", "target": "Destino", "targetNew": "Nova Janela (_blank)", "targetTop": "Janela de Cima (_top)", "targetSelf": "Mesma Janela (_self)", "targetParent": "Janela Pai (_parent)", "langDirLTR": "Esquerda para Direita (LTR)", "langDirRTL": "Direita para Esquerda (RTL)", "styles": "Estilo", "cssClasses": "Classes", "width": "Largura", "height": "Altura", "align": "Alinhamento", "alignLeft": "Esquerda", "alignRight": "Direita", "alignCenter": "Centralizado", "alignTop": "Superior", "alignMiddle": "Centralizado", "alignBottom": "Inferior", "invalidValue": "Valor inválido.", "invalidHeight": "A altura tem que ser um número", "invalidWidth": "A largura tem que ser um número.", "invalidCssLength": "O valor do campo \"%1\" deve ser um número positivo opcionalmente seguido por uma válida unidade de medida de CSS (px, %, in, cm, mm, em, ex, pt ou pc).", "invalidHtmlLength": "O valor do campo \"%1\" deve ser um número positivo opcionalmente seguido por uma válida unidade de medida de HTML (px ou %).", "invalidInlineStyle": "O valor válido para estilo deve conter uma ou mais tuplas no formato \"nome : valor\", separados por ponto e vírgula.", "cssLengthTooltip": "Insira um número para valor em pixels ou um número seguido de uma válida unidade de medida de CSS (px, %, in, cm, mm, em, ex, pt ou pc).", "unavailable": "%1<span class=\"cke_accessibility\">, indisponível</span>" }, "about": { "copy": "Copyright &copy; $1. Todos os direitos reservados.", "dlgTitle": "Sobre o CKEditor", "help": "Verifique o $1 para obter ajuda.", "moreInfo": "Para informações sobre a licença por favor visite o nosso site:", "title": "Sobre o CKEditor", "userGuide": "Guia do Usuário do CKEditor" }, "basicstyles": { "bold": "Negrito", "italic": "Itálico", "strike": "Tachado", "subscript": "Subscrito", "superscript": "Sobrescrito", "underline": "Sublinhado" }, "bidi": { "ltr": "Direção do texto da esquerda para a direita", "rtl": "Direção do texto da direita para a esquerda" }, "blockquote": {"toolbar": "Citação"}, "clipboard": { "copy": "Copiar", "copyError": "As configurações de segurança do seu navegador não permitem que o editor execute operações de copiar automaticamente. Por favor, utilize o teclado para copiar (Ctrl/Cmd+C).", "cut": "Recortar", "cutError": "As configurações de segurança do seu navegador não permitem que o editor execute operações de recortar automaticamente. Por favor, utilize o teclado para recortar (Ctrl/Cmd+X).", "paste": "Colar", "pasteArea": "Área para Colar", "pasteMsg": "Transfira o link usado na caixa usando o teclado com (<STRONG>Ctrl/Cmd+V</STRONG>) e <STRONG>OK</STRONG>.", "securityMsg": "As configurações de segurança do seu navegador não permitem que o editor acesse os dados da área de transferência diretamente. Por favor cole o conteúdo manualmente nesta janela.", "title": "Colar" }, "colorbutton": { "auto": "Automático", "bgColorTitle": "Cor do Plano de Fundo", "colors": { "000": "Preto", "800000": "Foquete", "8B4513": "Marrom 1", "2F4F4F": "Cinza 1", "008080": "Cerceta", "000080": "Azul Marinho", "4B0082": "Índigo", "696969": "Cinza 2", "B22222": "Tijolo de Fogo", "A52A2A": "Marrom 2", "DAA520": "Vara Dourada", "006400": "Verde Escuro", "40E0D0": "Turquesa", "0000CD": "Azul Médio", "800080": "Roxo", "808080": "Cinza 3", "F00": "Vermelho", "FF8C00": "Laranja Escuro", "FFD700": "Dourado", "008000": "Verde", "0FF": "Ciano", "00F": "Azul", "EE82EE": "Violeta", "A9A9A9": "Cinza Escuro", "FFA07A": "Salmão Claro", "FFA500": "Laranja", "FFFF00": "Amarelo", "00FF00": "Lima", "AFEEEE": "Turquesa Pálido", "ADD8E6": "Azul Claro", "DDA0DD": "Ameixa", "D3D3D3": "Cinza Claro", "FFF0F5": "Lavanda 1", "FAEBD7": "Branco Antiguidade", "FFFFE0": "Amarelo Claro", "F0FFF0": "Orvalho", "F0FFFF": "Azure", "F0F8FF": "Azul Alice", "E6E6FA": "Lavanda 2", "FFF": "Branco" }, "more": "Mais Cores...", "panelTitle": "Cores", "textColorTitle": "Cor do Texto" }, "colordialog": { "clear": "Limpar", "highlight": "Grifar", "options": "Opções de Cor", "selected": "Cor Selecionada", "title": "Selecione uma Cor" }, "templates": { "button": "Modelos de layout", "emptyListMsg": "(Não foram definidos modelos de layout)", "insertOption": "Substituir o conteúdo atual", "options": "Opções de Template", "selectPromptMsg": "Selecione um modelo de layout para ser aberto no editor<br>(o conteúdo atual será perdido):", "title": "Modelo de layout de conteúdo" }, "contextmenu": {"options": "Opções Menu de Contexto"}, "div": { "IdInputLabel": "Id", "advisoryTitleInputLabel": "Título Consulta", "cssClassInputLabel": "Classes de CSS", "edit": "Editar Div", "inlineStyleInputLabel": "Estilo Inline", "langDirLTRLabel": "Esquerda para Direita (LTR)", "langDirLabel": "Direção da Escrita", "langDirRTLLabel": "Direita para Esquerda (RTL)", "languageCodeInputLabel": "Código de Idioma", "remove": "Remover Div", "styleSelectLabel": "Estilo", "title": "Criar Container de DIV", "toolbar": "Criar Container de DIV" }, "toolbar": { "toolbarCollapse": "Diminuir Barra de Ferramentas", "toolbarExpand": "Aumentar Barra de Ferramentas", "toolbarGroups": { "document": "Documento", "clipboard": "Clipboard/Desfazer", "editing": "Edição", "forms": "Formulários", "basicstyles": "Estilos Básicos", "paragraph": "Paragrafo", "links": "Links", "insert": "Inserir", "styles": "Estilos", "colors": "Cores", "tools": "Ferramentas" }, "toolbars": "Barra de Ferramentas do Editor" }, "elementspath": {"eleLabel": "Caminho dos Elementos", "eleTitle": "Elemento %1"}, "find": { "find": "Localizar", "findOptions": "Opções", "findWhat": "Procurar por:", "matchCase": "Coincidir Maiúsculas/Minúsculas", "matchCyclic": "Coincidir cíclico", "matchWord": "Coincidir a palavra inteira", "notFoundMsg": "O texto especificado não foi encontrado.", "replace": "Substituir", "replaceAll": "Substituir Tudo", "replaceSuccessMsg": "%1 ocorrência(s) substituída(s).", "replaceWith": "Substituir por:", "title": "Localizar e Substituir" }, "fakeobjects": { "anchor": "Âncora", "flash": "Animação em Flash", "hiddenfield": "Campo Oculto", "iframe": "IFrame", "unknown": "Objeto desconhecido" }, "flash": { "access": "Acesso ao script", "accessAlways": "Sempre", "accessNever": "Nunca", "accessSameDomain": "Acessar Mesmo Domínio", "alignAbsBottom": "Inferior Absoluto", "alignAbsMiddle": "Centralizado Absoluto", "alignBaseline": "Baseline", "alignTextTop": "Superior Absoluto", "bgcolor": "Cor do Plano de Fundo", "chkFull": "Permitir tela cheia", "chkLoop": "Tocar Infinitamente", "chkMenu": "Habilita Menu Flash", "chkPlay": "Tocar Automaticamente", "flashvars": "Variáveis do Flash", "hSpace": "HSpace", "properties": "Propriedades do Flash", "propertiesTab": "Propriedades", "quality": "Qualidade", "qualityAutoHigh": "Qualidade Alta Automática", "qualityAutoLow": "Qualidade Baixa Automática", "qualityBest": "Qualidade Melhor", "qualityHigh": "Qualidade Alta", "qualityLow": "Qualidade Baixa", "qualityMedium": "Qualidade Média", "scale": "Escala", "scaleAll": "Mostrar tudo", "scaleFit": "Escala Exata", "scaleNoBorder": "Sem Borda", "title": "Propriedades do Flash", "vSpace": "VSpace", "validateHSpace": "O HSpace tem que ser um número", "validateSrc": "Por favor, digite o endereço do link", "validateVSpace": "O VSpace tem que ser um número.", "windowMode": "Modo da janela", "windowModeOpaque": "Opaca", "windowModeTransparent": "Transparente", "windowModeWindow": "Janela" }, "font": { "fontSize": {"label": "Tamanho", "voiceLabel": "Tamanho da fonte", "panelTitle": "Tamanho"}, "label": "Fonte", "panelTitle": "Fonte", "voiceLabel": "Fonte" }, "forms": { "button": { "title": "Formatar Botão", "text": "Texto (Valor)", "type": "Tipo", "typeBtn": "Botão", "typeSbm": "Enviar", "typeRst": "Limpar" }, "checkboxAndRadio": { "checkboxTitle": "Formatar Caixa de Seleção", "radioTitle": "Formatar Botão de Opção", "value": "Valor", "selected": "Selecionado" }, "form": { "title": "Formatar Formulário", "menu": "Formatar Formulário", "action": "Ação", "method": "Método", "encoding": "Codificação" }, "hidden": {"title": "Formatar Campo Oculto", "name": "Nome", "value": "Valor"}, "select": { "title": "Formatar Caixa de Listagem", "selectInfo": "Informações", "opAvail": "Opções disponíveis", "value": "Valor", "size": "Tamanho", "lines": "linhas", "chkMulti": "Permitir múltiplas seleções", "opText": "Texto", "opValue": "Valor", "btnAdd": "Adicionar", "btnModify": "Modificar", "btnUp": "Para cima", "btnDown": "Para baixo", "btnSetValue": "Definir como selecionado", "btnDelete": "Remover" }, "textarea": {"title": "Formatar Área de Texto", "cols": "Colunas", "rows": "Linhas"}, "textfield": { "title": "Formatar Caixa de Texto", "name": "Nome", "value": "Valor", "charWidth": "Comprimento (em caracteres)", "maxChars": "Número Máximo de Caracteres", "type": "Tipo", "typeText": "Texto", "typePass": "Senha", "typeEmail": "Email", "typeSearch": "Busca", "typeTel": "Número de Telefone", "typeUrl": "URL" } }, "format": { "label": "Formatação", "panelTitle": "Formatação", "tag_address": "Endereço", "tag_div": "Normal (DIV)", "tag_h1": "Título 1", "tag_h2": "Título 2", "tag_h3": "Título 3", "tag_h4": "Título 4", "tag_h5": "Título 5", "tag_h6": "Título 6", "tag_p": "Normal", "tag_pre": "Formatado" }, "horizontalrule": {"toolbar": "Inserir Linha Horizontal"}, "iframe": { "border": "Mostra borda do iframe", "noUrl": "Insira a URL do iframe", "scrolling": "Abilita scrollbars", "title": "Propriedade do IFrame", "toolbar": "IFrame" }, "image": { "alertUrl": "Por favor, digite a URL da imagem.", "alt": "Texto Alternativo", "border": "Borda", "btnUpload": "Enviar para o Servidor", "button2Img": "Deseja transformar o botão de imagem em uma imagem comum?", "hSpace": "HSpace", "img2Button": "Deseja transformar a imagem em um botão de imagem?", "infoTab": "Informações da Imagem", "linkTab": "Link", "lockRatio": "Travar Proporções", "menu": "Formatar Imagem", "resetSize": "Redefinir para o Tamanho Original", "title": "Formatar Imagem", "titleButton": "Formatar Botão de Imagem", "upload": "Enviar", "urlMissing": "URL da imagem está faltando.", "vSpace": "VSpace", "validateBorder": "A borda deve ser um número inteiro.", "validateHSpace": "O HSpace deve ser um número inteiro.", "validateVSpace": "O VSpace deve ser um número inteiro." }, "indent": {"indent": "Aumentar Recuo", "outdent": "Diminuir Recuo"}, "smiley": {"options": "Opções de Emoticons", "title": "Inserir Emoticon", "toolbar": "Emoticon"}, "justify": { "block": "Justificado", "center": "Centralizar", "left": "Alinhar Esquerda", "right": "Alinhar Direita" }, "link": { "acccessKey": "Chave de Acesso", "advanced": "Avançado", "advisoryContentType": "Tipo de Conteúdo", "advisoryTitle": "Título", "anchor": { "toolbar": "Inserir/Editar Âncora", "menu": "Formatar Âncora", "title": "Formatar Âncora", "name": "Nome da Âncora", "errorName": "Por favor, digite o nome da âncora", "remove": "Remover Âncora" }, "anchorId": "Id da âncora", "anchorName": "Nome da âncora", "charset": "Charset do Link", "cssClasses": "Classe de CSS", "emailAddress": "Endereço E-Mail", "emailBody": "Corpo da Mensagem", "emailSubject": "Assunto da Mensagem", "id": "Id", "info": "Informações", "langCode": "Direção do idioma", "langDir": "Direção do idioma", "langDirLTR": "Esquerda para Direita (LTR)", "langDirRTL": "Direita para Esquerda (RTL)", "menu": "Editar Link", "name": "Nome", "noAnchors": "(Não há âncoras no documento)", "noEmail": "Por favor, digite o endereço de e-mail", "noUrl": "Por favor, digite o endereço do Link", "other": "<outro>", "popupDependent": "Dependente (Netscape)", "popupFeatures": "Propriedades da Janela Pop-up", "popupFullScreen": "Modo Tela Cheia (IE)", "popupLeft": "Esquerda", "popupLocationBar": "Barra de Endereços", "popupMenuBar": "Barra de Menus", "popupResizable": "Redimensionável", "popupScrollBars": "Barras de Rolagem", "popupStatusBar": "Barra de Status", "popupToolbar": "Barra de Ferramentas", "popupTop": "Topo", "rel": "Tipo de Relação", "selectAnchor": "Selecione uma âncora", "styles": "Estilos", "tabIndex": "Índice de Tabulação", "target": "Destino", "targetFrame": "<frame>", "targetFrameName": "Nome do Frame de Destino", "targetPopup": "<janela popup>", "targetPopupName": "Nome da Janela Pop-up", "title": "Editar Link", "toAnchor": "Âncora nesta página", "toEmail": "E-Mail", "toUrl": "URL", "toolbar": "Inserir/Editar Link", "type": "Tipo de hiperlink", "unlink": "Remover Link", "upload": "Enviar ao Servidor" }, "list": {"bulletedlist": "Lista sem números", "numberedlist": "Lista numerada"}, "liststyle": { "armenian": "Numeração Armêna", "bulletedTitle": "Propriedades da Lista sem Numeros", "circle": "Círculo", "decimal": "Numeração Decimal (1, 2, 3, etc.)", "decimalLeadingZero": "Numeração Decimal com zeros (01, 02, 03, etc.)", "disc": "Disco", "georgian": "Numeração da Geórgia (an, ban, gan, etc.)", "lowerAlpha": "Numeração Alfabética minúscula (a, b, c, d, e, etc.)", "lowerGreek": "Numeração Grega minúscula (alpha, beta, gamma, etc.)", "lowerRoman": "Numeração Romana minúscula (i, ii, iii, iv, v, etc.)", "none": "Nenhum", "notset": "<não definido>", "numberedTitle": "Propriedades da Lista Numerada", "square": "Quadrado", "start": "Início", "type": "Tipo", "upperAlpha": "Numeração Alfabética Maiúscula (A, B, C, D, E, etc.)", "upperRoman": "Numeração Romana maiúscula (I, II, III, IV, V, etc.)", "validateStartNumber": "O número inicial da lista deve ser um número inteiro." }, "magicline": {"title": "Insera um parágrafo aqui"}, "maximize": {"maximize": "Maximizar", "minimize": "Minimize"}, "newpage": {"toolbar": "Novo"}, "pagebreak": {"alt": "Quebra de Página", "toolbar": "Inserir Quebra de Página"}, "pastetext": {"button": "Colar como Texto sem Formatação", "title": "Colar como Texto sem Formatação"}, "pastefromword": { "confirmCleanup": "O texto que você deseja colar parece ter sido copiado do Word. Você gostaria de remover a formatação antes de colar?", "error": "Não foi possível limpar os dados colados devido a um erro interno", "title": "Colar do Word", "toolbar": "Colar do Word" },
"print": {"toolbar": "Imprimir"}, "removeformat": {"toolbar": "Remover Formatação"}, "save": {"toolbar": "Salvar"}, "selectall": {"toolbar": "Selecionar Tudo"}, "showblocks": {"toolbar": "Mostrar blocos de código"}, "sourcearea": {"toolbar": "Código-Fonte"}, "specialchar": { "options": "Opções de Caractere Especial", "title": "Selecione um Caractere Especial", "toolbar": "Inserir Caractere Especial" }, "scayt": { "about": "Sobre a correção ortográfica durante a digitação", "aboutTab": "Sobre", "addWord": "Adicionar palavra", "allCaps": "Ignorar palavras maiúsculas", "dic_create": "Criar", "dic_delete": "Excluir", "dic_field_name": "Nome do Dicionário", "dic_info": "Inicialmente, o dicionário do usuário fica armazenado em um Cookie. Porém, Cookies tem tamanho limitado, portanto quand o dicionário do usuário atingir o tamanho limite poderá ser armazenado no nosso servidor. Para armazenar seu dicionário pessoal no nosso servidor deverá especificar um nome para ele. Se já tiver um dicionário armazenado por favor especifique o seu nome e clique em Restaurar.", "dic_rename": "Renomear", "dic_restore": "Restaurar", "dictionariesTab": "Dicionários", "disable": "Desabilitar correção ortográfica durante a digitação", "emptyDic": "O nome do dicionário não deveria estar vazio.", "enable": "Habilitar correção ortográfica durante a digitação", "ignore": "Ignorar", "ignoreAll": "Ignorar todas", "ignoreDomainNames": "Ignorar nomes de domínio", "langs": "Idiomas", "languagesTab": "Idiomas", "mixedCase": "Ignorar palavras com maiúsculas e minúsculas misturadas", "mixedWithDigits": "Ignorar palavras com números", "moreSuggestions": "Mais sugestões", "opera_title": "Não suportado no Opera", "options": "Opções", "optionsTab": "Opções", "title": "Correção ortográfica durante a digitação", "toggle": "Ativar/desativar correção ortográfica durante a digitação", "noSuggestions": "No suggestion" }, "stylescombo": { "label": "Estilo", "panelTitle": "Estilos de Formatação", "panelTitle1": "Estilos de bloco", "panelTitle2": "Estilos de texto corrido", "panelTitle3": "Estilos de objeto" }, "table": { "border": "Borda", "caption": "Legenda", "cell": { "menu": "Célula", "insertBefore": "Inserir célula a esquerda", "insertAfter": "Inserir célula a direita", "deleteCell": "Remover Células", "merge": "Mesclar Células", "mergeRight": "Mesclar com célula a direita", "mergeDown": "Mesclar com célula abaixo", "splitHorizontal": "Dividir célula horizontalmente", "splitVertical": "Dividir célula verticalmente", "title": "Propriedades da célula", "cellType": "Tipo de célula", "rowSpan": "Linhas cobertas", "colSpan": "Colunas cobertas", "wordWrap": "Quebra de palavra", "hAlign": "Alinhamento horizontal", "vAlign": "Alinhamento vertical", "alignBaseline": "Patamar de alinhamento", "bgColor": "Cor de fundo", "borderColor": "Cor das bordas", "data": "Dados", "header": "Cabeçalho", "yes": "Sim", "no": "Não", "invalidWidth": "A largura da célula tem que ser um número.", "invalidHeight": "A altura da célula tem que ser um número.", "invalidRowSpan": "Linhas cobertas tem que ser um número inteiro.", "invalidColSpan": "Colunas cobertas tem que ser um número inteiro.", "chooseColor": "Escolher" }, "cellPad": "Margem interna", "cellSpace": "Espaçamento", "column": { "menu": "Coluna", "insertBefore": "Inserir coluna a esquerda", "insertAfter": "Inserir coluna a direita", "deleteColumn": "Remover Colunas" }, "columns": "Colunas", "deleteTable": "Apagar Tabela", "headers": "Cabeçalho", "headersBoth": "Ambos", "headersColumn": "Primeira coluna", "headersNone": "Nenhum", "headersRow": "Primeira linha", "invalidBorder": "O tamanho da borda tem que ser um número.", "invalidCellPadding": "A margem interna das células tem que ser um número.", "invalidCellSpacing": "O espaçamento das células tem que ser um número.", "invalidCols": "O número de colunas tem que ser um número maior que 0.", "invalidHeight": "A altura da tabela tem que ser um número.", "invalidRows": "O número de linhas tem que ser um número maior que 0.", "invalidWidth": "A largura da tabela tem que ser um número.", "menu": "Formatar Tabela", "row": { "menu": "Linha", "insertBefore": "Inserir linha acima", "insertAfter": "Inserir linha abaixo", "deleteRow": "Remover Linhas" }, "rows": "Linhas", "summary": "Resumo", "title": "Formatar Tabela", "toolbar": "Tabela", "widthPc": "%", "widthPx": "pixels", "widthUnit": "unidade largura" }, "undo": {"redo": "Refazer", "undo": "Desfazer"}, "wsc": { "btnIgnore": "Ignorar uma vez", "btnIgnoreAll": "Ignorar Todas", "btnReplace": "Alterar", "btnReplaceAll": "Alterar Todas", "btnUndo": "Desfazer", "changeTo": "Alterar para", "errorLoading": "Erro carregando servidor de aplicação: %s.", "ieSpellDownload": "A verificação ortográfica não foi instalada. Você gostaria de realizar o download agora?", "manyChanges": "Verificação ortográfica encerrada: %1 palavras foram alteradas", "noChanges": "Verificação ortográfica encerrada: Não houve alterações", "noMispell": "Verificação encerrada: Não foram encontrados erros de ortografia", "noSuggestions": "-sem sugestões de ortografia-", "notAvailable": "Desculpe, o serviço não está disponível no momento.", "notInDic": "Não encontrada", "oneChange": "Verificação ortográfica encerrada: Uma palavra foi alterada", "progress": "Verificação ortográfica em andamento...", "title": "Corretor Ortográfico", "toolbar": "Verificar Ortografia" } };
"preview": {"preview": "Visualizar"},
random_line_split
method-two-trait-defer-resolution-2.rs
// 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. // Test that we pick which version of `Foo` to run based on whether // the type we (ultimately) inferred for `x` is copyable or not. // // In this case, the two versions are both impls of same trait, and // hence we we can resolve method even without knowing yet which // version will run (note that the `push` occurs after the call to // `foo()`). trait Foo { fn foo(&self) -> int; } impl<T:Copy> Foo for Vec<T> { fn foo(&self) -> int {1} } impl<T> Foo for Vec<Box<T>> { fn foo(&self) -> int {2} } fn call_foo_copy() -> int { let mut x = Vec::new(); let y = x.foo(); x.push(0u); y } fn call_foo_other() -> int
fn main() { assert_eq!(call_foo_copy(), 1); assert_eq!(call_foo_other(), 2); }
{ let mut x = Vec::new(); let y = x.foo(); x.push(box 0i); y }
identifier_body
method-two-trait-defer-resolution-2.rs
// 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. // Test that we pick which version of `Foo` to run based on whether // the type we (ultimately) inferred for `x` is copyable or not. // // In this case, the two versions are both impls of same trait, and // hence we we can resolve method even without knowing yet which // version will run (note that the `push` occurs after the call to // `foo()`). trait Foo { fn foo(&self) -> int; } impl<T:Copy> Foo for Vec<T> { fn foo(&self) -> int {1} } impl<T> Foo for Vec<Box<T>> { fn
(&self) -> int {2} } fn call_foo_copy() -> int { let mut x = Vec::new(); let y = x.foo(); x.push(0u); y } fn call_foo_other() -> int { let mut x = Vec::new(); let y = x.foo(); x.push(box 0i); y } fn main() { assert_eq!(call_foo_copy(), 1); assert_eq!(call_foo_other(), 2); }
foo
identifier_name
cli.js
#!/usr/bin/env node // Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE 'use strict'; const sysPath = require('path'); const fs = require('fs'); const yargs = require('yargs'); const PWMetrics = require('../lib/index'); const { getConfigFromFile } = require('../lib/utils/fs'); const { getMessageWithPrefix, getMessage } = require('../lib/utils/messages'); const cliFlags = yargs .help('help') .version(() => require('../package').version) .showHelpOnFail(false, 'Specify --help for available options') .wrap(yargs.terminalWidth()) .usage('Usage: $0 <url>') .command('url', 'URL to test') .option('json', { 'describe': 'Output as json', 'type': 'boolean', 'default': 'false', 'group': 'Output:' }) .option('output-path', { 'describe': 'The file path to output the results', 'type': 'string', 'default': 'stdout', 'group': 'Output:' }) .option('runs', { 'describe': 'Does n runs (eg. 3, 5), and reports the median run\'s numbers.', 'type': 'number', 'default': 1, }) .option('expectations', { 'describe': 'Expectations from metrics results. Useful for CI. Config required.', 'type': 'boolean', 'default': false }) .option('submit', { 'describe': 'Submit metric results into google sheets. Config required.', 'type': 'boolean', 'default': false }) .option('config', {
}) .option('disable-cpu-throttling', { 'describe': 'Disable CPU throttling', 'type': 'boolean', 'default': false }) .epilogue('For more Lighthouse CLI options see https://github.com/GoogleChrome/lighthouse/#lighthouse-cli-options') .argv; const config = getConfigFromFile(cliFlags.config); //Merge options from all sources. Order indicates precedence (last one wins) let options = Object.assign({}, {flags: cliFlags}, config); //Get url first from cmd line then from config file. options.url = cliFlags._[0] || options.url; if (!options.url || !options.url.length) throw new Error(getMessage('NO_URL')); const writeToDisk = function (fileName, data) { return new Promise((resolve, reject) => { const path = sysPath.join(process.cwd(), fileName); fs.writeFile(path, data, err => { if (err) reject(err); console.log(getMessageWithPrefix('SUCCESS', 'SAVED_TO_JSON', path)); resolve(); }); }); }; const pwMetrics = new PWMetrics(options.url, options); pwMetrics.start() .then(data => { if (options.flags.json) { // serialize accordingly data = JSON.stringify(data, null, 2) + '\n'; // output to file. if (options.flags.outputPath != 'stdout') return writeToDisk(options.flags.outputPath, data); // output to stdout else if (data) process.stdout.write(data); } }).then(() => { process.exit(0); }).catch(err => { console.error(err); process.exit(1); });
'describe': 'Path to config file', 'type': 'string',
random_line_split
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: return None def who(self): return self.__class__.__name__ def parsebasic(self, xml): global cx if 'id' in xml.attrib: self.id = xml.attrib['id'] else: if self.who() in cx: cx[self.who()] += 1 else: cx[self.who()] = 1 self.id = self.who()+str(cx[self.who()]) if 'depends' in xml.attrib: self.depends = xml.attrib['depends'] else: self.depends = '' if 'blocks' in xml.attrib: self.blocks = xml.attrib['blocks'] else: self.blocks = '' self.data = {} self.ids = {} class SrcSimpleModel (TopModel): def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = ss.text if 'id' in ss.attrib: self.ids[s] = ss.attrib['id'] class SrcProdModel (TopModel): def getNTs(self,id): nts = [] for p in self.getProds(id): if p.nt not in nts: nts.append(p.nt) return nts def getProds(self,id): if id in self.data.keys(): return self.data[id][0] else: return [] def getScope(self,id): if id in self.data.keys(): return self.data[id][1] else: return [] def getData(self, id): if id in self.data.keys(): return '; '.join(map(str,self.data[id][0])).replace(':\n ',' ← ').replace('\n ',' | ') else: return '∅' def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = [[],[]] for p in ss.findall(slpsns.bgf_('production')): xp = BGF3.Production() xp.parse(p) self.data[s][0].append(xp) self.data[s][1] = ss.findall('in/*') # # <sources> # <src name="dcg">snapshot/dcg.bgf</src> # <src name="sdf">snapshot/sdf.bgf</src> # <src name="rsc">snapshot/rascal.bgf</src> # </sources> class Sources (SrcSimpleModel): def __init__(self, xml): self.parsebasic(xml) for s in xml.findall('src'): self.data[s.attrib['name']] = s.text # <naming-convention> # <default>l!</default> # <src name="dcg">l!</src> # <src name="sdf,rsc">C!</src> # </naming-convention> class NamingConvention (SrcSimpleModel): def __init__(self, xml): self.default = xml.findtext('default') self.parse(xml) def getSpecifics(self): return self.default # <name-bind> # <name>function</name> # <src name="dcg">function</src> # <src name="sdf,rsc">Function</src> # </name-bind> class NameBind (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return self.nt # <width> # <bgf:expression> # <nonterminal>newline</nonterminal> # </bgf:expression> # <src name="dcg,sdf">+</src> # <src name="rsc">!</src> # <in> # <nonterminal>function</nonterminal> # </in> # </width> class Width (SrcSimpleModel): def __init__(self, xml): self.expr = BGF3.Expression([]) self.expr.parse(xml.findall(slpsns.bgf_('expression'))[0]) # apply namemap!!! self.parse(xml) self.scope = xml.findall('in') def getSpecifics(self): return str(self.expr) # <unification> # <name>expr</name> # <src name="dcg" labels="apply,binary"> # <bgf:production> # ... # </bgf:production> # </src> # </unification> class Unification (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <iteration> # <label>binary</label> # <name>expr</name> # <separator>ops</separator> # <src name="dcg">iterate</src> # <src name="sdf,rsc">lassoc</src> # </iteration> class Iteration (SrcSimpleModel): def __init__(self, xml): self.label = xml.findtext('label') if not self.label: self.label = '' self.nt = xml.findtext('name') self.sep = xml.findtext('separator') self.parse(xml) def getSpecifics(self): s = '' if self.label: s += '['+self.label+'], ' s += 'n('+self.nt+')' if self.sep: s += ', n('+self.sep+')' return s # <selectables> # <src name="..."> # <bgf:production> # ... # <marked> # ... # </marked> # ... # </bgf:production> # </src> # </selectables> class Selectables (SrcProdModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <production-label> # <src name="..."> # <bgf:production> # <label>...</label> # ... # </bgf:production> # </src> # </production-label> class ProdLabel (SrcProdModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <top-choice> # <name>ops</name> # <src name="ant">horizontal</src> # <src name="dcg,sdf,rsc">vertical</src> # </top-choice> class TopChoice (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name')
self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <folding> # <name>apply</name> # <src name="ant"> # <bgf:production> # ... # </bgf:production> # </src> # </folding> class Folding (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('state/'+slpsns.bgf_('production')+'/nonterminal') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')'
random_line_split
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: return None def who(self): return self.__class__.__name__ def parsebasic(self, xml): global cx if 'id' in xml.attrib: self.id = xml.attrib['id'] else: if self.who() in cx: cx[self.who()] += 1 else: cx[self.who()] = 1 self.id = self.who()+str(cx[self.who()]) if 'depends' in xml.attrib: self.depends = xml.attrib['depends'] else: self.depends = '' if 'blocks' in xml.attrib: self.blocks = xml.attrib['blocks'] else: self.blocks = '' self.data = {} self.ids = {} class SrcSimpleModel (TopModel): def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = ss.text if 'id' in ss.attrib: self.ids[s] = ss.attrib['id'] class SrcProdModel (TopModel): def getNTs(self,id): nts = [] for p in self.getProds(id): if p.nt not in nts: nts.append(p.nt) return nts def getProds(self,id): if id in self.data.keys(): return self.data[id][0] else: return [] def getScope(self,id): if id in self.data.keys(): return self.data[id][1] else: return [] def getData(self, id): if id in self.data.keys(): return '; '.join(map(str,self.data[id][0])).replace(':\n ',' ← ').replace('\n ',' | ') else: return '∅' def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = [[],[]] for p in ss.findall(slpsns.bgf_('production')): xp = BGF3.Production() xp.parse(p) self.data[s][0].append(xp) self.data[s][1] = ss.findall('in/*') # # <sources> # <src name="dcg">snapshot/dcg.bgf</src> # <src name="sdf">snapshot/sdf.bgf</src> # <src name="rsc">snapshot/rascal.bgf</src> # </sources> class Sources (SrcSimpleModel): def __init__(self, xml): self.parsebasic(xml) for s in xml.findall('src'): self.data[s.attrib['name']] = s.text # <naming-convention> # <default>l!</default> # <src name="dcg">l!</src> # <src name="sdf,rsc">C!</src> # </naming-convention> class NamingConvention (SrcSimpleModel): def __init__(self, xml): self.default = xml.findtext('default') self.parse(xml) def getSpecifics(self): return self.default # <name-bind> # <name>function</name> # <src name="dcg">function</src> # <src name="sdf,rsc">Function</src> # </name-bind> class NameBind (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return self.nt # <width> # <bgf:expression> # <nonterminal>newline</nonterminal> # </bgf:expression> # <src name="dcg,sdf">+</src> # <src name="rsc">!</src> # <in> # <nonterminal>function</nonterminal> # </in> # </width> class Width (SrcSimpleModel): def __init__(self, xml): self.expr = BGF3.Expression([]) self.expr.parse(xml.findall(slpsns.bgf_('expression'))[0]) # apply namemap!!! self.parse(xml) self.scope = xml.findall('in') def getSpecifics(self): return str(self.expr) # <unification> # <name>expr</name> # <src name="dcg" labels="apply,binary"> # <bgf:production> # ... # </bgf:production> # </src> # </unification> class Unification (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <iteration> # <label>binary</label> # <name>expr</name> # <separator>ops</separator> # <src name="dcg">iterate</src> # <src name="sdf,rsc">lassoc</src> # </iteration> class Iteration (SrcSimpleModel): def __init__(self, xml): self.label = xml.findtext('label') if not self.label: self.label = '' self.nt = xml.findtext('name') self.sep = xml.findtext('separator') self.parse(xml) def getSpecifics(self): s = '' if self.label: s +=
+= 'n('+self.nt+')' if self.sep: s += ', n('+self.sep+')' return s # <selectables> # <src name="..."> # <bgf:production> # ... # <marked> # ... # </marked> # ... # </bgf:production> # </src> # </selectables> class Selectables (SrcProdModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <production-label> # <src name="..."> # <bgf:production> # <label>...</label> # ... # </bgf:production> # </src> # </production-label> class ProdLabel (SrcProdModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <top-choice> # <name>ops</name> # <src name="ant">horizontal</src> # <src name="dcg,sdf,rsc">vertical</src> # </top-choice> class TopChoice (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <folding> # <name>apply</name> # <src name="ant"> # <bgf:production> # ... # </bgf:production> # </src> # </folding> class Folding (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('state/'+slpsns.bgf_('production')+'/nonterminal') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')'
'['+self.label+'], ' s
conditional_block
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: return None def who(self):
def parsebasic(self, xml): global cx if 'id' in xml.attrib: self.id = xml.attrib['id'] else: if self.who() in cx: cx[self.who()] += 1 else: cx[self.who()] = 1 self.id = self.who()+str(cx[self.who()]) if 'depends' in xml.attrib: self.depends = xml.attrib['depends'] else: self.depends = '' if 'blocks' in xml.attrib: self.blocks = xml.attrib['blocks'] else: self.blocks = '' self.data = {} self.ids = {} class SrcSimpleModel (TopModel): def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = ss.text if 'id' in ss.attrib: self.ids[s] = ss.attrib['id'] class SrcProdModel (TopModel): def getNTs(self,id): nts = [] for p in self.getProds(id): if p.nt not in nts: nts.append(p.nt) return nts def getProds(self,id): if id in self.data.keys(): return self.data[id][0] else: return [] def getScope(self,id): if id in self.data.keys(): return self.data[id][1] else: return [] def getData(self, id): if id in self.data.keys(): return '; '.join(map(str,self.data[id][0])).replace(':\n ',' ← ').replace('\n ',' | ') else: return '∅' def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = [[],[]] for p in ss.findall(slpsns.bgf_('production')): xp = BGF3.Production() xp.parse(p) self.data[s][0].append(xp) self.data[s][1] = ss.findall('in/*') # # <sources> # <src name="dcg">snapshot/dcg.bgf</src> # <src name="sdf">snapshot/sdf.bgf</src> # <src name="rsc">snapshot/rascal.bgf</src> # </sources> class Sources (SrcSimpleModel): def __init__(self, xml): self.parsebasic(xml) for s in xml.findall('src'): self.data[s.attrib['name']] = s.text # <naming-convention> # <default>l!</default> # <src name="dcg">l!</src> # <src name="sdf,rsc">C!</src> # </naming-convention> class NamingConvention (SrcSimpleModel): def __init__(self, xml): self.default = xml.findtext('default') self.parse(xml) def getSpecifics(self): return self.default # <name-bind> # <name>function</name> # <src name="dcg">function</src> # <src name="sdf,rsc">Function</src> # </name-bind> class NameBind (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return self.nt # <width> # <bgf:expression> # <nonterminal>newline</nonterminal> # </bgf:expression> # <src name="dcg,sdf">+</src> # <src name="rsc">!</src> # <in> # <nonterminal>function</nonterminal> # </in> # </width> class Width (SrcSimpleModel): def __init__(self, xml): self.expr = BGF3.Expression([]) self.expr.parse(xml.findall(slpsns.bgf_('expression'))[0]) # apply namemap!!! self.parse(xml) self.scope = xml.findall('in') def getSpecifics(self): return str(self.expr) # <unification> # <name>expr</name> # <src name="dcg" labels="apply,binary"> # <bgf:production> # ... # </bgf:production> # </src> # </unification> class Unification (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <iteration> # <label>binary</label> # <name>expr</name> # <separator>ops</separator> # <src name="dcg">iterate</src> # <src name="sdf,rsc">lassoc</src> # </iteration> class Iteration (SrcSimpleModel): def __init__(self, xml): self.label = xml.findtext('label') if not self.label: self.label = '' self.nt = xml.findtext('name') self.sep = xml.findtext('separator') self.parse(xml) def getSpecifics(self): s = '' if self.label: s += '['+self.label+'], ' s += 'n('+self.nt+')' if self.sep: s += ', n('+self.sep+')' return s # <selectables> # <src name="..."> # <bgf:production> # ... # <marked> # ... # </marked> # ... # </bgf:production> # </src> # </selectables> class Selectables (SrcProdModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <production-label> # <src name="..."> # <bgf:production> # <label>...</label> # ... # </bgf:production> # </src> # </production-label> class ProdLabel (SrcProdModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <top-choice> # <name>ops</name> # <src name="ant">horizontal</src> # <src name="dcg,sdf,rsc">vertical</src> # </top-choice> class TopChoice (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <folding> # <name>apply</name> # <src name="ant"> # <bgf:production> # ... # </bgf:production> # </src> # </folding> class Folding (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('state/'+slpsns.bgf_('production')+'/nonterminal') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')'
return self.__class__.__name__
identifier_body
MBGF.py
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: return None def who(self): return self.__class__.__name__ def parsebasic(self, xml): global cx if 'id' in xml.attrib: self.id = xml.attrib['id'] else: if self.who() in cx: cx[self.who()] += 1 else: cx[self.who()] = 1 self.id = self.who()+str(cx[self.who()]) if 'depends' in xml.attrib: self.depends = xml.attrib['depends'] else: self.depends = '' if 'blocks' in xml.attrib: self.blocks = xml.attrib['blocks'] else: self.blocks = '' self.data = {} self.ids = {} class SrcSimpleModel (TopModel): def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = ss.text if 'id' in ss.attrib: self.ids[s] = ss.attrib['id'] class SrcProdModel (TopModel): def getNTs(self,id): nts = [] for p in self.getProds(id): if p.nt not in nts: nts.append(p.nt) return nts def getProds(self,id): if id in self.data.keys(): return self.data[id][0] else: return [] def getScope(self,id): if id in self.data.keys(): return self.data[id][1] else: return [] def getData(self, id): if id in self.data.keys(): return '; '.join(map(str,self.data[id][0])).replace(':\n ',' ← ').replace('\n ',' | ') else: return '∅' def parse(self, xml): self.parsebasic(xml) for ss in xml.findall('state'): for s in ss.attrib['src'].split(','): self.data[s] = [[],[]] for p in ss.findall(slpsns.bgf_('production')): xp = BGF3.Production() xp.parse(p) self.data[s][0].append(xp) self.data[s][1] = ss.findall('in/*') # # <sources> # <src name="dcg">snapshot/dcg.bgf</src> # <src name="sdf">snapshot/sdf.bgf</src> # <src name="rsc">snapshot/rascal.bgf</src> # </sources> class Sources (SrcSimpleModel): def __init__(self, xml): self.parsebasic(xml) for s in xml.findall('src'): self.data[s.attrib['name']] = s.text # <naming-convention> # <default>l!</default> # <src name="dcg">l!</src> # <src name="sdf,rsc">C!</src> # </naming-convention> class NamingConvention (SrcSimpleModel): def __init__(self, xml): self.default = xml.findtext('default') self.parse(xml) def getSpecifics(self): return self.default # <name-bind> # <name>function</name> # <src name="dcg">function</src> # <src name="sdf,rsc">Function</src> # </name-bind> class NameBind (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return self.nt # <width> # <bgf:expression> # <nonterminal>newline</nonterminal> # </bgf:expression> # <src name="dcg,sdf">+</src> # <src name="rsc">!</src> # <in> # <nonterminal>function</nonterminal> # </in> # </width> class Width (SrcSimpleModel): def __init__(self, xml): self.expr = BGF3.Expression([]) self.expr.parse(xml.findall(slpsns.bgf_('expression'))[0]) # apply namemap!!! self.parse(xml) self.scope = xml.findall('in') def getSpecifics(self): return str(self.expr) # <unification> # <name>expr</name> # <src name="dcg" labels="apply,binary"> # <bgf:production> # ... # </bgf:production> # </src> # </unification> class Unification (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <iteration> # <label>binary</label> # <name>expr</name> # <separator>ops</separator> # <src name="dcg">iterate</src> # <src name="sdf,rsc">lassoc</src> # </iteration> class Iteration (SrcSimpleModel): def __init__(self, xml): self.label = xml.findtext('label') if not self.label: self.label = '' self.nt = xml.findtext('name') self.sep = xml.findtext('separator') self.parse(xml) def getSpecifics(self): s = '' if self.label: s += '['+self.label+'], ' s += 'n('+self.nt+')' if self.sep: s += ', n('+self.sep+')' return s # <selectables> # <src name="..."> # <bgf:production> # ... # <marked> # ... # </marked> # ... # </bgf:production> # </src> # </selectables> class Selectables (SrcProdModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <production-label> # <src name="..."> # <bgf:production> # <label>...</label> # ... # </bgf:production> # </src> # </production-label> class ProdLa
rodModel): def __init__(self, xml): self.parse(xml) def getSpecifics(self): return '—' # <top-choice> # <name>ops</name> # <src name="ant">horizontal</src> # <src name="dcg,sdf,rsc">vertical</src> # </top-choice> class TopChoice (SrcSimpleModel): def __init__(self, xml): self.nt = xml.findtext('name') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')' # <folding> # <name>apply</name> # <src name="ant"> # <bgf:production> # ... # </bgf:production> # </src> # </folding> class Folding (SrcProdModel): def __init__(self, xml): self.nt = xml.findtext('state/'+slpsns.bgf_('production')+'/nonterminal') self.parse(xml) def getSpecifics(self): return 'n('+self.nt+')'
bel (SrcP
identifier_name
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word_dict def read_embedding(word_dict, embedding_file_path): embedding_size = 64 embedding_file = open(embedding_file_path, 'rb') embedding_matrix = np.zeros((len(word_dict) + 1, embedding_size)) for line in embedding_file: terms = line.rstrip().split(' ') if not len(terms) == embedding_size + 1: continue if terms[0] in word_dict:
return embedding_matrix #transfer each word to word id def transfer_data(word_vec, word_dict): vec = [] for word in word_vec: if not word in word_dict: word_dict[word] = len(word_dict) vec.append(word_dict[word]) return vec def sim_max(sentence, labelId, embedding_matrix): max_sim = 0.0 for ids in sentence: embedding = embedding_matrix[ids] simlarity = 1.0 - cosine(embedding, embedding_matrix[labelId]) if max_sim < simlarity: max_sim = simlarity return max_sim def avg_embedding(sentences, embedding_matrix): word_embeddings = [] for sentence in sentences: for ids in sentence: embedding = embedding_matrix[ids] word_embeddings.append(embedding) return np.mean(word_embeddings, axis = 0) #select sentences def filter_dataset_seq(labelId, sentences, embedding_matrix): x = [] max_score = 0 max_sentence = [] for sentence in sentences: cur_score = sim_max(sentence, labelId, embedding_matrix) if cur_score > max_score: max_score = cur_score max_sentence = sentence [max_sentence] = sequence.pad_sequences([max_sentence], maxlen=40) return avg_embedding(sentences, embedding_matrix), max_sentence, embedding_matrix[labelId] if __name__ == "__main__": ################################################################### # Read tag file ################################################################### TAG_FILE_PATH = "./tag.list" tag_map = {} tag_file = open(TAG_FILE_PATH, 'rb') for line in tag_file: tag = line.rstrip() add = True for item in tag_map.keys(): if item == tag: #replacy by similarity() function later add = False break if add: tag_map[tag] = 0 tag_file.close() sample_map = {} sentence_map = {} word_dict = {"&&":0} for i in range(6): ################################################################### # Read label file # Positive Sample if Tag in # Nagetive Sample if Tag not in (Randomly picked up for balancing) ################################################################### LABEL_FILE_PATH = "../../data/" + str(i) + ".part.tokens.label" Label_file = open(LABEL_FILE_PATH, 'rb') for line in Label_file: terms = line.split('\t') if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] local_map = {} #positive for term in terms[2:]: words = term.split(' ') if words[0] == 'not' or words[0] == 'no': continue if words[len(words) - 1] in tag_map: local_map[words[len(words) - 1]] = 1 if len(local_map) == 0: continue #negative positive_count = len(local_map) for count in range(positive_count): pos = random.randrange(0, len(tag_map)) while tag_map.keys()[pos] in local_map: pos = random.randrange(0, len(tag_map)) local_map[tag_map.keys()[pos]] = 0 #record sample_map[key] = [] for tag in local_map.keys(): sample_map[key].append([tag, local_map[tag]]) Label_file.close() ################################################################### # Read Sentences ################################################################### SENENCE_FILE_PATH = "../../data/" + str(i) + ".part.tokens.sentence" sentence_file = open(SENENCE_FILE_PATH, 'rb') for line in sentence_file: terms = line.rstrip().split("\t") if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] if not key in sample_map: continue sentences = [] sentence = [] for term in terms[2:]: if term == '&&': if len(sentence) > 5 and len(sentence) < 40: sentences.append(transfer_data(sentence, word_dict)) sentence = [] else: sentence.append(term) if len(sentences) > 0: sentence_map[key] = sentences sentence_file.close() print "word_dict " + str(len(word_dict)) print "characters " + str(len(sentence_map)) print "data read finished" ################################################################### # Read embedding ################################################################### EMBEDDING_FILE_PATH = "../../data/full_story_vec.txt" embedding_matrix = read_embedding(word_dict, EMBEDDING_FILE_PATH) print "embedding read finished" ################################################################### # Construct features ################################################################### X = [[], [], []] y = [] for key in sentence_map.keys(): for sample in sample_map[key]: if not sample[0] in word_dict: continue context,sentence,label_embedding = \ filter_dataset_seq(word_dict[sample[0]], sentence_map[key], embedding_matrix) X[0].append(context) X[1].append(sentence) X[2].append(label_embedding) y.append(sample[1]) X[0] = np.asmatrix(X[0]) X[1] = np.asmatrix(X[1]) X[2] = np.asmatrix(X[2]) y = np.asarray(y) scores = [] ################################################################### #model ################################################################### embedding_size = 64 max_features = len(word_dict) + 1 batch_size = 32 nb_epoch = 5 embedding_trainable = True early_stop = False maxlen = 40 from sklearn.model_selection import KFold import copy from sklearn.metrics import (precision_score, recall_score,f1_score, accuracy_score) kf = KFold(n_splits=5, shuffle=True, random_state = 7) for train, test in kf.split(y): X_train = [] X_test = [] for i in range(3): X_train.append(X[i][train]) X_test.append(X[i][test]) y_train, y_test = y[train], y[test] weights = copy.deepcopy(embedding_matrix) context_input = Input(shape=(embedding_size, )) word_input = Input(shape=(embedding_size, )) sentence_input = Input(shape=(40,), dtype='int32') x = Embedding(output_dim=embedding_size, input_dim=max_features, input_length=40, weights=[weights])(sentence_input) sentence_out = LSTM(output_dim=64)(x) x = keras.layers.concatenate([word_input, sentence_out, context_input], axis=-1) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) main_output = Dense(1, activation='sigmoid', name='main_output')(x) model = Model(inputs=[word_input, sentence_input, context_input], outputs=main_output) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, validation_split=0.1) y_pred = model.predict(X_test) y_pred = [int(np.round(x)) for x in y_pred] accuracy = accuracy_score(y_test, y_pred) recall = recall_score(y_test, y_pred) precision = precision_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print('Result\t{:.4f}\t{:.4f}\t{:.4f}\t{:.4f}'.format(precision, recall, f1, accuracy)) scores.append([precision, recall, f1, accuracy]) print "REC\t" + str(np.average(scores, axis = 0))
ids = word_dict[terms[0]] embedding_vec = np.asarray(terms[1:], dtype='float32') embedding_matrix[ids] = embedding_vec
conditional_block
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word_dict def read_embedding(word_dict, embedding_file_path): embedding_size = 64 embedding_file = open(embedding_file_path, 'rb') embedding_matrix = np.zeros((len(word_dict) + 1, embedding_size)) for line in embedding_file: terms = line.rstrip().split(' ') if not len(terms) == embedding_size + 1: continue if terms[0] in word_dict: ids = word_dict[terms[0]] embedding_vec = np.asarray(terms[1:], dtype='float32') embedding_matrix[ids] = embedding_vec return embedding_matrix #transfer each word to word id def transfer_data(word_vec, word_dict): vec = [] for word in word_vec: if not word in word_dict: word_dict[word] = len(word_dict) vec.append(word_dict[word]) return vec def
(sentence, labelId, embedding_matrix): max_sim = 0.0 for ids in sentence: embedding = embedding_matrix[ids] simlarity = 1.0 - cosine(embedding, embedding_matrix[labelId]) if max_sim < simlarity: max_sim = simlarity return max_sim def avg_embedding(sentences, embedding_matrix): word_embeddings = [] for sentence in sentences: for ids in sentence: embedding = embedding_matrix[ids] word_embeddings.append(embedding) return np.mean(word_embeddings, axis = 0) #select sentences def filter_dataset_seq(labelId, sentences, embedding_matrix): x = [] max_score = 0 max_sentence = [] for sentence in sentences: cur_score = sim_max(sentence, labelId, embedding_matrix) if cur_score > max_score: max_score = cur_score max_sentence = sentence [max_sentence] = sequence.pad_sequences([max_sentence], maxlen=40) return avg_embedding(sentences, embedding_matrix), max_sentence, embedding_matrix[labelId] if __name__ == "__main__": ################################################################### # Read tag file ################################################################### TAG_FILE_PATH = "./tag.list" tag_map = {} tag_file = open(TAG_FILE_PATH, 'rb') for line in tag_file: tag = line.rstrip() add = True for item in tag_map.keys(): if item == tag: #replacy by similarity() function later add = False break if add: tag_map[tag] = 0 tag_file.close() sample_map = {} sentence_map = {} word_dict = {"&&":0} for i in range(6): ################################################################### # Read label file # Positive Sample if Tag in # Nagetive Sample if Tag not in (Randomly picked up for balancing) ################################################################### LABEL_FILE_PATH = "../../data/" + str(i) + ".part.tokens.label" Label_file = open(LABEL_FILE_PATH, 'rb') for line in Label_file: terms = line.split('\t') if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] local_map = {} #positive for term in terms[2:]: words = term.split(' ') if words[0] == 'not' or words[0] == 'no': continue if words[len(words) - 1] in tag_map: local_map[words[len(words) - 1]] = 1 if len(local_map) == 0: continue #negative positive_count = len(local_map) for count in range(positive_count): pos = random.randrange(0, len(tag_map)) while tag_map.keys()[pos] in local_map: pos = random.randrange(0, len(tag_map)) local_map[tag_map.keys()[pos]] = 0 #record sample_map[key] = [] for tag in local_map.keys(): sample_map[key].append([tag, local_map[tag]]) Label_file.close() ################################################################### # Read Sentences ################################################################### SENENCE_FILE_PATH = "../../data/" + str(i) + ".part.tokens.sentence" sentence_file = open(SENENCE_FILE_PATH, 'rb') for line in sentence_file: terms = line.rstrip().split("\t") if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] if not key in sample_map: continue sentences = [] sentence = [] for term in terms[2:]: if term == '&&': if len(sentence) > 5 and len(sentence) < 40: sentences.append(transfer_data(sentence, word_dict)) sentence = [] else: sentence.append(term) if len(sentences) > 0: sentence_map[key] = sentences sentence_file.close() print "word_dict " + str(len(word_dict)) print "characters " + str(len(sentence_map)) print "data read finished" ################################################################### # Read embedding ################################################################### EMBEDDING_FILE_PATH = "../../data/full_story_vec.txt" embedding_matrix = read_embedding(word_dict, EMBEDDING_FILE_PATH) print "embedding read finished" ################################################################### # Construct features ################################################################### X = [[], [], []] y = [] for key in sentence_map.keys(): for sample in sample_map[key]: if not sample[0] in word_dict: continue context,sentence,label_embedding = \ filter_dataset_seq(word_dict[sample[0]], sentence_map[key], embedding_matrix) X[0].append(context) X[1].append(sentence) X[2].append(label_embedding) y.append(sample[1]) X[0] = np.asmatrix(X[0]) X[1] = np.asmatrix(X[1]) X[2] = np.asmatrix(X[2]) y = np.asarray(y) scores = [] ################################################################### #model ################################################################### embedding_size = 64 max_features = len(word_dict) + 1 batch_size = 32 nb_epoch = 5 embedding_trainable = True early_stop = False maxlen = 40 from sklearn.model_selection import KFold import copy from sklearn.metrics import (precision_score, recall_score,f1_score, accuracy_score) kf = KFold(n_splits=5, shuffle=True, random_state = 7) for train, test in kf.split(y): X_train = [] X_test = [] for i in range(3): X_train.append(X[i][train]) X_test.append(X[i][test]) y_train, y_test = y[train], y[test] weights = copy.deepcopy(embedding_matrix) context_input = Input(shape=(embedding_size, )) word_input = Input(shape=(embedding_size, )) sentence_input = Input(shape=(40,), dtype='int32') x = Embedding(output_dim=embedding_size, input_dim=max_features, input_length=40, weights=[weights])(sentence_input) sentence_out = LSTM(output_dim=64)(x) x = keras.layers.concatenate([word_input, sentence_out, context_input], axis=-1) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) main_output = Dense(1, activation='sigmoid', name='main_output')(x) model = Model(inputs=[word_input, sentence_input, context_input], outputs=main_output) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, validation_split=0.1) y_pred = model.predict(X_test) y_pred = [int(np.round(x)) for x in y_pred] accuracy = accuracy_score(y_test, y_pred) recall = recall_score(y_test, y_pred) precision = precision_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print('Result\t{:.4f}\t{:.4f}\t{:.4f}\t{:.4f}'.format(precision, recall, f1, accuracy)) scores.append([precision, recall, f1, accuracy]) print "REC\t" + str(np.average(scores, axis = 0))
sim_max
identifier_name
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word_dict def read_embedding(word_dict, embedding_file_path): embedding_size = 64 embedding_file = open(embedding_file_path, 'rb') embedding_matrix = np.zeros((len(word_dict) + 1, embedding_size)) for line in embedding_file: terms = line.rstrip().split(' ') if not len(terms) == embedding_size + 1: continue if terms[0] in word_dict: ids = word_dict[terms[0]] embedding_vec = np.asarray(terms[1:], dtype='float32') embedding_matrix[ids] = embedding_vec return embedding_matrix #transfer each word to word id def transfer_data(word_vec, word_dict): vec = [] for word in word_vec: if not word in word_dict: word_dict[word] = len(word_dict) vec.append(word_dict[word]) return vec def sim_max(sentence, labelId, embedding_matrix): max_sim = 0.0 for ids in sentence: embedding = embedding_matrix[ids] simlarity = 1.0 - cosine(embedding, embedding_matrix[labelId]) if max_sim < simlarity: max_sim = simlarity return max_sim def avg_embedding(sentences, embedding_matrix): word_embeddings = [] for sentence in sentences: for ids in sentence: embedding = embedding_matrix[ids] word_embeddings.append(embedding) return np.mean(word_embeddings, axis = 0) #select sentences def filter_dataset_seq(labelId, sentences, embedding_matrix): x = [] max_score = 0 max_sentence = [] for sentence in sentences: cur_score = sim_max(sentence, labelId, embedding_matrix) if cur_score > max_score: max_score = cur_score max_sentence = sentence [max_sentence] = sequence.pad_sequences([max_sentence], maxlen=40) return avg_embedding(sentences, embedding_matrix), max_sentence, embedding_matrix[labelId] if __name__ == "__main__": ###################################################################
tag_map = {} tag_file = open(TAG_FILE_PATH, 'rb') for line in tag_file: tag = line.rstrip() add = True for item in tag_map.keys(): if item == tag: #replacy by similarity() function later add = False break if add: tag_map[tag] = 0 tag_file.close() sample_map = {} sentence_map = {} word_dict = {"&&":0} for i in range(6): ################################################################### # Read label file # Positive Sample if Tag in # Nagetive Sample if Tag not in (Randomly picked up for balancing) ################################################################### LABEL_FILE_PATH = "../../data/" + str(i) + ".part.tokens.label" Label_file = open(LABEL_FILE_PATH, 'rb') for line in Label_file: terms = line.split('\t') if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] local_map = {} #positive for term in terms[2:]: words = term.split(' ') if words[0] == 'not' or words[0] == 'no': continue if words[len(words) - 1] in tag_map: local_map[words[len(words) - 1]] = 1 if len(local_map) == 0: continue #negative positive_count = len(local_map) for count in range(positive_count): pos = random.randrange(0, len(tag_map)) while tag_map.keys()[pos] in local_map: pos = random.randrange(0, len(tag_map)) local_map[tag_map.keys()[pos]] = 0 #record sample_map[key] = [] for tag in local_map.keys(): sample_map[key].append([tag, local_map[tag]]) Label_file.close() ################################################################### # Read Sentences ################################################################### SENENCE_FILE_PATH = "../../data/" + str(i) + ".part.tokens.sentence" sentence_file = open(SENENCE_FILE_PATH, 'rb') for line in sentence_file: terms = line.rstrip().split("\t") if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] if not key in sample_map: continue sentences = [] sentence = [] for term in terms[2:]: if term == '&&': if len(sentence) > 5 and len(sentence) < 40: sentences.append(transfer_data(sentence, word_dict)) sentence = [] else: sentence.append(term) if len(sentences) > 0: sentence_map[key] = sentences sentence_file.close() print "word_dict " + str(len(word_dict)) print "characters " + str(len(sentence_map)) print "data read finished" ################################################################### # Read embedding ################################################################### EMBEDDING_FILE_PATH = "../../data/full_story_vec.txt" embedding_matrix = read_embedding(word_dict, EMBEDDING_FILE_PATH) print "embedding read finished" ################################################################### # Construct features ################################################################### X = [[], [], []] y = [] for key in sentence_map.keys(): for sample in sample_map[key]: if not sample[0] in word_dict: continue context,sentence,label_embedding = \ filter_dataset_seq(word_dict[sample[0]], sentence_map[key], embedding_matrix) X[0].append(context) X[1].append(sentence) X[2].append(label_embedding) y.append(sample[1]) X[0] = np.asmatrix(X[0]) X[1] = np.asmatrix(X[1]) X[2] = np.asmatrix(X[2]) y = np.asarray(y) scores = [] ################################################################### #model ################################################################### embedding_size = 64 max_features = len(word_dict) + 1 batch_size = 32 nb_epoch = 5 embedding_trainable = True early_stop = False maxlen = 40 from sklearn.model_selection import KFold import copy from sklearn.metrics import (precision_score, recall_score,f1_score, accuracy_score) kf = KFold(n_splits=5, shuffle=True, random_state = 7) for train, test in kf.split(y): X_train = [] X_test = [] for i in range(3): X_train.append(X[i][train]) X_test.append(X[i][test]) y_train, y_test = y[train], y[test] weights = copy.deepcopy(embedding_matrix) context_input = Input(shape=(embedding_size, )) word_input = Input(shape=(embedding_size, )) sentence_input = Input(shape=(40,), dtype='int32') x = Embedding(output_dim=embedding_size, input_dim=max_features, input_length=40, weights=[weights])(sentence_input) sentence_out = LSTM(output_dim=64)(x) x = keras.layers.concatenate([word_input, sentence_out, context_input], axis=-1) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) main_output = Dense(1, activation='sigmoid', name='main_output')(x) model = Model(inputs=[word_input, sentence_input, context_input], outputs=main_output) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, validation_split=0.1) y_pred = model.predict(X_test) y_pred = [int(np.round(x)) for x in y_pred] accuracy = accuracy_score(y_test, y_pred) recall = recall_score(y_test, y_pred) precision = precision_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print('Result\t{:.4f}\t{:.4f}\t{:.4f}\t{:.4f}'.format(precision, recall, f1, accuracy)) scores.append([precision, recall, f1, accuracy]) print "REC\t" + str(np.average(scores, axis = 0))
# Read tag file ################################################################### TAG_FILE_PATH = "./tag.list"
random_line_split
cf_data.py
import random, keras import numpy as np from keras.preprocessing import sequence from scipy.spatial.distance import cosine from keras.models import Model, Sequential from keras.layers import Input, Dense, Dropout, Activation, Flatten, Merge, Embedding from keras.layers import LSTM #read Embedding if the word is in word_dict def read_embedding(word_dict, embedding_file_path): embedding_size = 64 embedding_file = open(embedding_file_path, 'rb') embedding_matrix = np.zeros((len(word_dict) + 1, embedding_size)) for line in embedding_file: terms = line.rstrip().split(' ') if not len(terms) == embedding_size + 1: continue if terms[0] in word_dict: ids = word_dict[terms[0]] embedding_vec = np.asarray(terms[1:], dtype='float32') embedding_matrix[ids] = embedding_vec return embedding_matrix #transfer each word to word id def transfer_data(word_vec, word_dict): vec = [] for word in word_vec: if not word in word_dict: word_dict[word] = len(word_dict) vec.append(word_dict[word]) return vec def sim_max(sentence, labelId, embedding_matrix):
def avg_embedding(sentences, embedding_matrix): word_embeddings = [] for sentence in sentences: for ids in sentence: embedding = embedding_matrix[ids] word_embeddings.append(embedding) return np.mean(word_embeddings, axis = 0) #select sentences def filter_dataset_seq(labelId, sentences, embedding_matrix): x = [] max_score = 0 max_sentence = [] for sentence in sentences: cur_score = sim_max(sentence, labelId, embedding_matrix) if cur_score > max_score: max_score = cur_score max_sentence = sentence [max_sentence] = sequence.pad_sequences([max_sentence], maxlen=40) return avg_embedding(sentences, embedding_matrix), max_sentence, embedding_matrix[labelId] if __name__ == "__main__": ################################################################### # Read tag file ################################################################### TAG_FILE_PATH = "./tag.list" tag_map = {} tag_file = open(TAG_FILE_PATH, 'rb') for line in tag_file: tag = line.rstrip() add = True for item in tag_map.keys(): if item == tag: #replacy by similarity() function later add = False break if add: tag_map[tag] = 0 tag_file.close() sample_map = {} sentence_map = {} word_dict = {"&&":0} for i in range(6): ################################################################### # Read label file # Positive Sample if Tag in # Nagetive Sample if Tag not in (Randomly picked up for balancing) ################################################################### LABEL_FILE_PATH = "../../data/" + str(i) + ".part.tokens.label" Label_file = open(LABEL_FILE_PATH, 'rb') for line in Label_file: terms = line.split('\t') if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] local_map = {} #positive for term in terms[2:]: words = term.split(' ') if words[0] == 'not' or words[0] == 'no': continue if words[len(words) - 1] in tag_map: local_map[words[len(words) - 1]] = 1 if len(local_map) == 0: continue #negative positive_count = len(local_map) for count in range(positive_count): pos = random.randrange(0, len(tag_map)) while tag_map.keys()[pos] in local_map: pos = random.randrange(0, len(tag_map)) local_map[tag_map.keys()[pos]] = 0 #record sample_map[key] = [] for tag in local_map.keys(): sample_map[key].append([tag, local_map[tag]]) Label_file.close() ################################################################### # Read Sentences ################################################################### SENENCE_FILE_PATH = "../../data/" + str(i) + ".part.tokens.sentence" sentence_file = open(SENENCE_FILE_PATH, 'rb') for line in sentence_file: terms = line.rstrip().split("\t") if len(terms) <= 2: continue key = terms[0] + ' ' + terms[1] if not key in sample_map: continue sentences = [] sentence = [] for term in terms[2:]: if term == '&&': if len(sentence) > 5 and len(sentence) < 40: sentences.append(transfer_data(sentence, word_dict)) sentence = [] else: sentence.append(term) if len(sentences) > 0: sentence_map[key] = sentences sentence_file.close() print "word_dict " + str(len(word_dict)) print "characters " + str(len(sentence_map)) print "data read finished" ################################################################### # Read embedding ################################################################### EMBEDDING_FILE_PATH = "../../data/full_story_vec.txt" embedding_matrix = read_embedding(word_dict, EMBEDDING_FILE_PATH) print "embedding read finished" ################################################################### # Construct features ################################################################### X = [[], [], []] y = [] for key in sentence_map.keys(): for sample in sample_map[key]: if not sample[0] in word_dict: continue context,sentence,label_embedding = \ filter_dataset_seq(word_dict[sample[0]], sentence_map[key], embedding_matrix) X[0].append(context) X[1].append(sentence) X[2].append(label_embedding) y.append(sample[1]) X[0] = np.asmatrix(X[0]) X[1] = np.asmatrix(X[1]) X[2] = np.asmatrix(X[2]) y = np.asarray(y) scores = [] ################################################################### #model ################################################################### embedding_size = 64 max_features = len(word_dict) + 1 batch_size = 32 nb_epoch = 5 embedding_trainable = True early_stop = False maxlen = 40 from sklearn.model_selection import KFold import copy from sklearn.metrics import (precision_score, recall_score,f1_score, accuracy_score) kf = KFold(n_splits=5, shuffle=True, random_state = 7) for train, test in kf.split(y): X_train = [] X_test = [] for i in range(3): X_train.append(X[i][train]) X_test.append(X[i][test]) y_train, y_test = y[train], y[test] weights = copy.deepcopy(embedding_matrix) context_input = Input(shape=(embedding_size, )) word_input = Input(shape=(embedding_size, )) sentence_input = Input(shape=(40,), dtype='int32') x = Embedding(output_dim=embedding_size, input_dim=max_features, input_length=40, weights=[weights])(sentence_input) sentence_out = LSTM(output_dim=64)(x) x = keras.layers.concatenate([word_input, sentence_out, context_input], axis=-1) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) main_output = Dense(1, activation='sigmoid', name='main_output')(x) model = Model(inputs=[word_input, sentence_input, context_input], outputs=main_output) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, validation_split=0.1) y_pred = model.predict(X_test) y_pred = [int(np.round(x)) for x in y_pred] accuracy = accuracy_score(y_test, y_pred) recall = recall_score(y_test, y_pred) precision = precision_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) print('Result\t{:.4f}\t{:.4f}\t{:.4f}\t{:.4f}'.format(precision, recall, f1, accuracy)) scores.append([precision, recall, f1, accuracy]) print "REC\t" + str(np.average(scores, axis = 0))
max_sim = 0.0 for ids in sentence: embedding = embedding_matrix[ids] simlarity = 1.0 - cosine(embedding, embedding_matrix[labelId]) if max_sim < simlarity: max_sim = simlarity return max_sim
identifier_body
instr_pminsb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn pminsb_1() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 223], OperandSize::Dword) } #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 144, 209, 9, 14, 106], OperandSize::Dword) } #[test] fn pminsb_3() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 201], OperandSize::Qword) } #[test] fn pminsb_4() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Eight, 1699663306, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 188, 223, 202, 205, 78, 101], OperandSize::Qword) }
pminsb_2
identifier_name
instr_pminsb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*;
use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn pminsb_1() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 223], OperandSize::Dword) } #[test] fn pminsb_2() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 144, 209, 9, 14, 106], OperandSize::Dword) } #[test] fn pminsb_3() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 201], OperandSize::Qword) } #[test] fn pminsb_4() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Eight, 1699663306, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 188, 223, 202, 205, 78, 101], OperandSize::Qword) }
random_line_split
instr_pminsb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn pminsb_1()
#[test] fn pminsb_2() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 144, 209, 9, 14, 106], OperandSize::Dword) } #[test] fn pminsb_3() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 201], OperandSize::Qword) } #[test] fn pminsb_4() { run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Eight, 1699663306, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 188, 223, 202, 205, 78, 101], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 223], OperandSize::Dword) }
identifier_body
day_4.rs
use std::str::Chars; use self::DisplayResult::{Output, NotANumber}; use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum
{ Output(Vec<Number>), NotANumber } impl From<Chars<'static>> for DisplayResult { fn from(chars: Chars) -> DisplayResult { let len = chars.as_str().len(); let mut vec = Vec::with_capacity(len); for c in chars { if c < '0' || c > '9' { return NotANumber; } let n = Number::from(c); vec.push(n); } Output(vec) } } #[derive(PartialEq, Debug)] pub enum Number { One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero } impl From<char> for Number { fn from(c: char) -> Number { match c { '1' => One, '2' => Two, '3' => Three, '4' => Four, '5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine, '0' => Zero, _ => unreachable!("Impossible!"), } } } #[derive(Default)] pub struct Display { input: Option<&'static str> } impl Display { pub fn new() -> Display { Display { input: None } } pub fn output(&self) -> DisplayResult { match self.input { Some(data) => DisplayResult::from(data.chars()), None => Output(vec![]), } } pub fn input(&mut self, data: &'static str) { self.input = Some(data); } }
DisplayResult
identifier_name
day_4.rs
use std::str::Chars; use self::DisplayResult::{Output, NotANumber}; use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum DisplayResult { Output(Vec<Number>), NotANumber } impl From<Chars<'static>> for DisplayResult { fn from(chars: Chars) -> DisplayResult { let len = chars.as_str().len(); let mut vec = Vec::with_capacity(len); for c in chars { if c < '0' || c > '9' { return NotANumber; } let n = Number::from(c); vec.push(n); } Output(vec) } } #[derive(PartialEq, Debug)] pub enum Number { One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero } impl From<char> for Number { fn from(c: char) -> Number { match c { '1' => One, '2' => Two, '3' => Three, '4' => Four, '5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine, '0' => Zero, _ => unreachable!("Impossible!"), } } } #[derive(Default)] pub struct Display { input: Option<&'static str> } impl Display {
input: None } } pub fn output(&self) -> DisplayResult { match self.input { Some(data) => DisplayResult::from(data.chars()), None => Output(vec![]), } } pub fn input(&mut self, data: &'static str) { self.input = Some(data); } }
pub fn new() -> Display { Display {
random_line_split
day_4.rs
use std::str::Chars; use self::DisplayResult::{Output, NotANumber}; use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero}; #[derive(PartialEq, Debug)] pub enum DisplayResult { Output(Vec<Number>), NotANumber } impl From<Chars<'static>> for DisplayResult { fn from(chars: Chars) -> DisplayResult { let len = chars.as_str().len(); let mut vec = Vec::with_capacity(len); for c in chars { if c < '0' || c > '9' { return NotANumber; } let n = Number::from(c); vec.push(n); } Output(vec) } } #[derive(PartialEq, Debug)] pub enum Number { One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero } impl From<char> for Number { fn from(c: char) -> Number { match c { '1' => One, '2' => Two, '3' => Three, '4' => Four, '5' => Five, '6' => Six, '7' => Seven, '8' => Eight, '9' => Nine, '0' => Zero, _ => unreachable!("Impossible!"), } } } #[derive(Default)] pub struct Display { input: Option<&'static str> } impl Display { pub fn new() -> Display { Display { input: None } } pub fn output(&self) -> DisplayResult { match self.input { Some(data) => DisplayResult::from(data.chars()), None => Output(vec![]), } } pub fn input(&mut self, data: &'static str)
}
{ self.input = Some(data); }
identifier_body
init.rs
use std::fs::{canonicalize, create_dir}; use std::path::Path; use std::path::PathBuf; use errors::{bail, Result}; use utils::fs::create_file; use crate::console; use crate::prompt::{ask_bool, ask_url}; const CONFIG: &str = r#" # The URL the site will be built for base_url = "%BASE_URL%" # Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola highlight_code = %HIGHLIGHT% [extra] # Put all your custom variables here "#; // canonicalize(path) function on windows system returns a path with UNC. // Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project // More details on Universal Naming Convention (UNC): // https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention // So the following const will be used to remove the network part of the UNC to display users a more common // path on windows systems. // This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed. const LOCAL_UNC: &str = "\\\\?\\"; // Given a path, return true if it is a directory and it doesn't have any // non-hidden files, otherwise return false (path is assumed to exist) pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> { if path.is_dir() { let mut entries = match path.read_dir() { Ok(entries) => entries, Err(e) => { bail!( "Could not read `{}` because of error: {}", path.to_string_lossy().to_string(), e ); } }; // If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error if entries.any(|x| match x { Ok(file) => !file .file_name() .to_str() .expect("Could not convert filename to &str") .starts_with('.'), Err(_) => true, }) { return Ok(false); } return Ok(true); } Ok(false) } // Remove the unc part of a windows path fn strip_unc(path: &PathBuf) -> String { let path_to_refine = path.to_str().unwrap(); path_to_refine.trim_start_matches(LOCAL_UNC).to_string() } pub fn create_new_project(name: &str, force: bool) -> Result<()> { let path = Path::new(name); // Better error message than the rust default if path.exists() && !is_directory_quasi_empty(&path)? && !force { if name == "." { bail!("The current directory is not an empty folder (hidden files are ignored)."); } else { bail!( "`{}` is not an empty folder (hidden files are ignored).", path.to_string_lossy().to_string() ) } } console::info("Welcome to Zola!"); console::info("Please answer a few questions to get started quickly."); console::info("Any choices made can be changed by modifying the `config.toml` file later."); let base_url = ask_url("> What is the URL of your site?", "https://example.com")?; let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?; let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?; let search = ask_bool("> Do you want to build a search index of the content?", false)?; let config = CONFIG .trim_start() .replace("%BASE_URL%", &base_url) .replace("%COMPILE_SASS%", &format!("{}", compile_sass)) .replace("%SEARCH%", &format!("{}", search)) .replace("%HIGHLIGHT%", &format!("{}", highlight)); populate(&path, compile_sass, &config)?; println!(); console::success(&format!( "Done! Your site was created in {}", strip_unc(&canonicalize(path).unwrap()) )); println!(); console::info( "Get started by moving into the directory and using the built-in server: `zola serve`", ); println!("Visit https://www.getzola.org for the full documentation."); Ok(()) } fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> { if !path.exists() { create_dir(path)?; } create_file(&path.join("config.toml"), &config)?; create_dir(path.join("content"))?; create_dir(path.join("templates"))?; create_dir(path.join("static"))?; create_dir(path.join("themes"))?; if compile_sass { create_dir(path.join("sass"))?; } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; use std::fs::{create_dir, remove_dir, remove_dir_all}; use std::path::Path; #[test] fn init_empty_directory() { let mut dir = temp_dir(); dir.push("test_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn init_non_empty_directory() { let mut dir = temp_dir(); dir.push("test_non_empty_dir"); if dir.exists()
create_dir(&dir).expect("Could not create test directory"); let mut content = dir.clone(); content.push("content"); create_dir(&content).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&content).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(false, allowed); } #[test] fn init_quasi_empty_directory() { let mut dir = temp_dir(); dir.push("test_quasi_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut git = dir.clone(); git.push(".git"); create_dir(&git).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&git).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn populate_existing_directory() { let mut dir = temp_dir(); dir.push("test_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_non_existing_directory() { let mut dir = temp_dir(); dir.push("test_non_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.exists()); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_without_sass() { let mut dir = temp_dir(); dir.push("test_wihout_sass_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, false, "").expect("Could not populate zola directories"); assert_eq!(false, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn strip_unc_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); if cfg!(target_os = "windows") { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), "C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ) } else { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string() ); } remove_dir_all(&dir).unwrap(); } // If the following test fails it means that the canonicalize function is fixed and strip_unc // function/workaround is not anymore required. // See issue https://github.com/rust-lang/rust/issues/42869 as a reference. #[test] #[cfg(target_os = "windows")] fn strip_unc_required_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); assert_eq!( canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(), "\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ); remove_dir_all(&dir).unwrap(); } }
{ remove_dir_all(&dir).expect("Could not free test directory"); }
conditional_block
init.rs
use std::fs::{canonicalize, create_dir}; use std::path::Path; use std::path::PathBuf; use errors::{bail, Result}; use utils::fs::create_file; use crate::console; use crate::prompt::{ask_bool, ask_url}; const CONFIG: &str = r#" # The URL the site will be built for base_url = "%BASE_URL%" # Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola highlight_code = %HIGHLIGHT% [extra] # Put all your custom variables here "#; // canonicalize(path) function on windows system returns a path with UNC. // Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project // More details on Universal Naming Convention (UNC): // https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention // So the following const will be used to remove the network part of the UNC to display users a more common // path on windows systems. // This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed. const LOCAL_UNC: &str = "\\\\?\\"; // Given a path, return true if it is a directory and it doesn't have any // non-hidden files, otherwise return false (path is assumed to exist) pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> { if path.is_dir() { let mut entries = match path.read_dir() { Ok(entries) => entries, Err(e) => { bail!( "Could not read `{}` because of error: {}", path.to_string_lossy().to_string(), e ); } }; // If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error if entries.any(|x| match x { Ok(file) => !file .file_name() .to_str() .expect("Could not convert filename to &str") .starts_with('.'), Err(_) => true, }) { return Ok(false); } return Ok(true); } Ok(false) } // Remove the unc part of a windows path fn strip_unc(path: &PathBuf) -> String { let path_to_refine = path.to_str().unwrap(); path_to_refine.trim_start_matches(LOCAL_UNC).to_string() } pub fn create_new_project(name: &str, force: bool) -> Result<()> { let path = Path::new(name); // Better error message than the rust default if path.exists() && !is_directory_quasi_empty(&path)? && !force { if name == "." { bail!("The current directory is not an empty folder (hidden files are ignored)."); } else { bail!( "`{}` is not an empty folder (hidden files are ignored).", path.to_string_lossy().to_string() ) } } console::info("Welcome to Zola!"); console::info("Please answer a few questions to get started quickly."); console::info("Any choices made can be changed by modifying the `config.toml` file later."); let base_url = ask_url("> What is the URL of your site?", "https://example.com")?; let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?; let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?; let search = ask_bool("> Do you want to build a search index of the content?", false)?; let config = CONFIG .trim_start() .replace("%BASE_URL%", &base_url) .replace("%COMPILE_SASS%", &format!("{}", compile_sass)) .replace("%SEARCH%", &format!("{}", search)) .replace("%HIGHLIGHT%", &format!("{}", highlight)); populate(&path, compile_sass, &config)?; println!(); console::success(&format!( "Done! Your site was created in {}", strip_unc(&canonicalize(path).unwrap()) )); println!(); console::info( "Get started by moving into the directory and using the built-in server: `zola serve`", ); println!("Visit https://www.getzola.org for the full documentation."); Ok(()) } fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> { if !path.exists() { create_dir(path)?; } create_file(&path.join("config.toml"), &config)?; create_dir(path.join("content"))?; create_dir(path.join("templates"))?; create_dir(path.join("static"))?; create_dir(path.join("themes"))?; if compile_sass { create_dir(path.join("sass"))?; } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; use std::fs::{create_dir, remove_dir, remove_dir_all}; use std::path::Path; #[test] fn init_empty_directory() { let mut dir = temp_dir(); dir.push("test_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn init_non_empty_directory()
#[test] fn init_quasi_empty_directory() { let mut dir = temp_dir(); dir.push("test_quasi_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut git = dir.clone(); git.push(".git"); create_dir(&git).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&git).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn populate_existing_directory() { let mut dir = temp_dir(); dir.push("test_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_non_existing_directory() { let mut dir = temp_dir(); dir.push("test_non_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.exists()); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_without_sass() { let mut dir = temp_dir(); dir.push("test_wihout_sass_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, false, "").expect("Could not populate zola directories"); assert_eq!(false, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn strip_unc_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); if cfg!(target_os = "windows") { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), "C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ) } else { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string() ); } remove_dir_all(&dir).unwrap(); } // If the following test fails it means that the canonicalize function is fixed and strip_unc // function/workaround is not anymore required. // See issue https://github.com/rust-lang/rust/issues/42869 as a reference. #[test] #[cfg(target_os = "windows")] fn strip_unc_required_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); assert_eq!( canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(), "\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ); remove_dir_all(&dir).unwrap(); } }
{ let mut dir = temp_dir(); dir.push("test_non_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut content = dir.clone(); content.push("content"); create_dir(&content).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&content).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(false, allowed); }
identifier_body
init.rs
use std::fs::{canonicalize, create_dir}; use std::path::Path; use std::path::PathBuf; use errors::{bail, Result}; use utils::fs::create_file; use crate::console; use crate::prompt::{ask_bool, ask_url}; const CONFIG: &str = r#" # The URL the site will be built for base_url = "%BASE_URL%" # Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola highlight_code = %HIGHLIGHT% [extra] # Put all your custom variables here "#; // canonicalize(path) function on windows system returns a path with UNC. // Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project // More details on Universal Naming Convention (UNC): // https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention // So the following const will be used to remove the network part of the UNC to display users a more common // path on windows systems. // This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed. const LOCAL_UNC: &str = "\\\\?\\"; // Given a path, return true if it is a directory and it doesn't have any // non-hidden files, otherwise return false (path is assumed to exist) pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> { if path.is_dir() { let mut entries = match path.read_dir() { Ok(entries) => entries, Err(e) => { bail!( "Could not read `{}` because of error: {}", path.to_string_lossy().to_string(), e ); } }; // If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error if entries.any(|x| match x { Ok(file) => !file .file_name() .to_str() .expect("Could not convert filename to &str") .starts_with('.'), Err(_) => true, }) { return Ok(false); } return Ok(true); } Ok(false) } // Remove the unc part of a windows path fn strip_unc(path: &PathBuf) -> String { let path_to_refine = path.to_str().unwrap(); path_to_refine.trim_start_matches(LOCAL_UNC).to_string() } pub fn create_new_project(name: &str, force: bool) -> Result<()> { let path = Path::new(name); // Better error message than the rust default if path.exists() && !is_directory_quasi_empty(&path)? && !force { if name == "." { bail!("The current directory is not an empty folder (hidden files are ignored)."); } else { bail!( "`{}` is not an empty folder (hidden files are ignored).", path.to_string_lossy().to_string() ) } } console::info("Welcome to Zola!"); console::info("Please answer a few questions to get started quickly."); console::info("Any choices made can be changed by modifying the `config.toml` file later."); let base_url = ask_url("> What is the URL of your site?", "https://example.com")?; let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?; let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?; let search = ask_bool("> Do you want to build a search index of the content?", false)?; let config = CONFIG .trim_start() .replace("%BASE_URL%", &base_url) .replace("%COMPILE_SASS%", &format!("{}", compile_sass)) .replace("%SEARCH%", &format!("{}", search)) .replace("%HIGHLIGHT%", &format!("{}", highlight)); populate(&path, compile_sass, &config)?; println!(); console::success(&format!( "Done! Your site was created in {}", strip_unc(&canonicalize(path).unwrap()) )); println!(); console::info( "Get started by moving into the directory and using the built-in server: `zola serve`", ); println!("Visit https://www.getzola.org for the full documentation."); Ok(()) } fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> { if !path.exists() { create_dir(path)?; } create_file(&path.join("config.toml"), &config)?; create_dir(path.join("content"))?; create_dir(path.join("templates"))?; create_dir(path.join("static"))?; create_dir(path.join("themes"))?; if compile_sass { create_dir(path.join("sass"))?; } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; use std::fs::{create_dir, remove_dir, remove_dir_all}; use std::path::Path; #[test] fn init_empty_directory() { let mut dir = temp_dir(); dir.push("test_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn
() { let mut dir = temp_dir(); dir.push("test_non_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut content = dir.clone(); content.push("content"); create_dir(&content).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&content).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(false, allowed); } #[test] fn init_quasi_empty_directory() { let mut dir = temp_dir(); dir.push("test_quasi_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut git = dir.clone(); git.push(".git"); create_dir(&git).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&git).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn populate_existing_directory() { let mut dir = temp_dir(); dir.push("test_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_non_existing_directory() { let mut dir = temp_dir(); dir.push("test_non_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.exists()); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_without_sass() { let mut dir = temp_dir(); dir.push("test_wihout_sass_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, false, "").expect("Could not populate zola directories"); assert_eq!(false, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn strip_unc_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); if cfg!(target_os = "windows") { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), "C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ) } else { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string() ); } remove_dir_all(&dir).unwrap(); } // If the following test fails it means that the canonicalize function is fixed and strip_unc // function/workaround is not anymore required. // See issue https://github.com/rust-lang/rust/issues/42869 as a reference. #[test] #[cfg(target_os = "windows")] fn strip_unc_required_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); assert_eq!( canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(), "\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ); remove_dir_all(&dir).unwrap(); } }
init_non_empty_directory
identifier_name
init.rs
use std::fs::{canonicalize, create_dir}; use std::path::Path; use std::path::PathBuf; use errors::{bail, Result}; use utils::fs::create_file; use crate::console; use crate::prompt::{ask_bool, ask_url}; const CONFIG: &str = r#" # The URL the site will be built for base_url = "%BASE_URL%" # Whether to automatically compile all Sass files in the sass directory compile_sass = %COMPILE_SASS% # Whether to build a search index to be used later on by a JavaScript library build_search_index = %SEARCH% [markdown] # Whether to do syntax highlighting # Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola highlight_code = %HIGHLIGHT% [extra] # Put all your custom variables here "#; // canonicalize(path) function on windows system returns a path with UNC. // Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project // More details on Universal Naming Convention (UNC): // https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention // So the following const will be used to remove the network part of the UNC to display users a more common // path on windows systems. // This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed. const LOCAL_UNC: &str = "\\\\?\\"; // Given a path, return true if it is a directory and it doesn't have any // non-hidden files, otherwise return false (path is assumed to exist) pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> { if path.is_dir() { let mut entries = match path.read_dir() { Ok(entries) => entries,
); } }; // If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error if entries.any(|x| match x { Ok(file) => !file .file_name() .to_str() .expect("Could not convert filename to &str") .starts_with('.'), Err(_) => true, }) { return Ok(false); } return Ok(true); } Ok(false) } // Remove the unc part of a windows path fn strip_unc(path: &PathBuf) -> String { let path_to_refine = path.to_str().unwrap(); path_to_refine.trim_start_matches(LOCAL_UNC).to_string() } pub fn create_new_project(name: &str, force: bool) -> Result<()> { let path = Path::new(name); // Better error message than the rust default if path.exists() && !is_directory_quasi_empty(&path)? && !force { if name == "." { bail!("The current directory is not an empty folder (hidden files are ignored)."); } else { bail!( "`{}` is not an empty folder (hidden files are ignored).", path.to_string_lossy().to_string() ) } } console::info("Welcome to Zola!"); console::info("Please answer a few questions to get started quickly."); console::info("Any choices made can be changed by modifying the `config.toml` file later."); let base_url = ask_url("> What is the URL of your site?", "https://example.com")?; let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?; let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?; let search = ask_bool("> Do you want to build a search index of the content?", false)?; let config = CONFIG .trim_start() .replace("%BASE_URL%", &base_url) .replace("%COMPILE_SASS%", &format!("{}", compile_sass)) .replace("%SEARCH%", &format!("{}", search)) .replace("%HIGHLIGHT%", &format!("{}", highlight)); populate(&path, compile_sass, &config)?; println!(); console::success(&format!( "Done! Your site was created in {}", strip_unc(&canonicalize(path).unwrap()) )); println!(); console::info( "Get started by moving into the directory and using the built-in server: `zola serve`", ); println!("Visit https://www.getzola.org for the full documentation."); Ok(()) } fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> { if !path.exists() { create_dir(path)?; } create_file(&path.join("config.toml"), &config)?; create_dir(path.join("content"))?; create_dir(path.join("templates"))?; create_dir(path.join("static"))?; create_dir(path.join("themes"))?; if compile_sass { create_dir(path.join("sass"))?; } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; use std::fs::{create_dir, remove_dir, remove_dir_all}; use std::path::Path; #[test] fn init_empty_directory() { let mut dir = temp_dir(); dir.push("test_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn init_non_empty_directory() { let mut dir = temp_dir(); dir.push("test_non_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut content = dir.clone(); content.push("content"); create_dir(&content).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&content).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(false, allowed); } #[test] fn init_quasi_empty_directory() { let mut dir = temp_dir(); dir.push("test_quasi_empty_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); let mut git = dir.clone(); git.push(".git"); create_dir(&git).unwrap(); let allowed = is_directory_quasi_empty(&dir) .expect("An error happened reading the directory's contents"); remove_dir(&git).unwrap(); remove_dir(&dir).unwrap(); assert_eq!(true, allowed); } #[test] fn populate_existing_directory() { let mut dir = temp_dir(); dir.push("test_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_non_existing_directory() { let mut dir = temp_dir(); dir.push("test_non_existing_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } populate(&dir, true, "").expect("Could not populate zola directories"); assert_eq!(true, dir.exists()); assert_eq!(true, dir.join("config.toml").exists()); assert_eq!(true, dir.join("content").exists()); assert_eq!(true, dir.join("templates").exists()); assert_eq!(true, dir.join("static").exists()); assert_eq!(true, dir.join("themes").exists()); assert_eq!(true, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn populate_without_sass() { let mut dir = temp_dir(); dir.push("test_wihout_sass_dir"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); populate(&dir, false, "").expect("Could not populate zola directories"); assert_eq!(false, dir.join("sass").exists()); remove_dir_all(&dir).unwrap(); } #[test] fn strip_unc_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); if cfg!(target_os = "windows") { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), "C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ) } else { assert_eq!( strip_unc(&canonicalize(Path::new(&dir)).unwrap()), canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string() ); } remove_dir_all(&dir).unwrap(); } // If the following test fails it means that the canonicalize function is fixed and strip_unc // function/workaround is not anymore required. // See issue https://github.com/rust-lang/rust/issues/42869 as a reference. #[test] #[cfg(target_os = "windows")] fn strip_unc_required_test() { let mut dir = temp_dir(); dir.push("new_project"); if dir.exists() { remove_dir_all(&dir).expect("Could not free test directory"); } create_dir(&dir).expect("Could not create test directory"); assert_eq!( canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(), "\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project" ); remove_dir_all(&dir).unwrap(); } }
Err(e) => { bail!( "Could not read `{}` because of error: {}", path.to_string_lossy().to_string(), e
random_line_split
assignment_tracker.rs
use common::*; use disassembler::*; use instruction_graph::*; pub struct AssignmentTracker; impl AssignmentTracker { // NOTE: expects reversed graph pub fn find( graph: &InstructionGraph, address: u64, register: Reg, try_match: &mut FnMut(&Insn, Reg) -> bool, ) -> Option<u64> { let mut skipped_initial_instruction = false; let mut stack = vec![address]; while !stack.is_empty() { let address = stack.pop().unwrap(); for pair in graph.get_adjacent(&address).into_iter().rev() { if let Ok((addr, link)) = pair { match link.type_ { LinkType::Next | LinkType::Branch | LinkType::SwitchCaseJump => { stack.push(*addr); } _ => (), } } } if !skipped_initial_instruction { skipped_initial_instruction = true; } let insn = graph.get_vertex(&address); if try_match(insn, register) { match insn.operands[1] { Operand::Register(_, r) => { return AssignmentTracker::find(graph, insn.address, r, &mut |i, reg| { if let Operand::Register(_, r) = i.operands[0] { if r == reg && i.code == Mnemonic::Imov { return true; } } return false; }); } Operand::ImmediateSigned(_, v) => return Some(v as u64), Operand::ImmediateUnsigned(_, v) => return Some(v), _ => { // TODO: logger.Warn("Cannot track assignments from 0x{0:x8} operand type {1}", instr.Offset, instr.Operands.[1].Type) return None; } } } if graph.get_in_value(insn.address) > 1 { // TODO: logger.Warn("Cannot track assignments from 0x{0:x8}, the number of incoming links > 1", instr.Offset) return None; } if let Mnemonic::Imov = insn.code { match (insn.operands[0], insn.operands[1]) { (Operand::Register(_, r0), Operand::Register(_, r1)) if r0 == register => { return AssignmentTracker::find(graph, insn.address, r1, try_match); } _ => {}
} None } }
} }
random_line_split
assignment_tracker.rs
use common::*; use disassembler::*; use instruction_graph::*; pub struct
; impl AssignmentTracker { // NOTE: expects reversed graph pub fn find( graph: &InstructionGraph, address: u64, register: Reg, try_match: &mut FnMut(&Insn, Reg) -> bool, ) -> Option<u64> { let mut skipped_initial_instruction = false; let mut stack = vec![address]; while !stack.is_empty() { let address = stack.pop().unwrap(); for pair in graph.get_adjacent(&address).into_iter().rev() { if let Ok((addr, link)) = pair { match link.type_ { LinkType::Next | LinkType::Branch | LinkType::SwitchCaseJump => { stack.push(*addr); } _ => (), } } } if !skipped_initial_instruction { skipped_initial_instruction = true; } let insn = graph.get_vertex(&address); if try_match(insn, register) { match insn.operands[1] { Operand::Register(_, r) => { return AssignmentTracker::find(graph, insn.address, r, &mut |i, reg| { if let Operand::Register(_, r) = i.operands[0] { if r == reg && i.code == Mnemonic::Imov { return true; } } return false; }); } Operand::ImmediateSigned(_, v) => return Some(v as u64), Operand::ImmediateUnsigned(_, v) => return Some(v), _ => { // TODO: logger.Warn("Cannot track assignments from 0x{0:x8} operand type {1}", instr.Offset, instr.Operands.[1].Type) return None; } } } if graph.get_in_value(insn.address) > 1 { // TODO: logger.Warn("Cannot track assignments from 0x{0:x8}, the number of incoming links > 1", instr.Offset) return None; } if let Mnemonic::Imov = insn.code { match (insn.operands[0], insn.operands[1]) { (Operand::Register(_, r0), Operand::Register(_, r1)) if r0 == register => { return AssignmentTracker::find(graph, insn.address, r1, try_match); } _ => {} } } } None } }
AssignmentTracker
identifier_name
assignment_tracker.rs
use common::*; use disassembler::*; use instruction_graph::*; pub struct AssignmentTracker; impl AssignmentTracker { // NOTE: expects reversed graph pub fn find( graph: &InstructionGraph, address: u64, register: Reg, try_match: &mut FnMut(&Insn, Reg) -> bool, ) -> Option<u64>
}
{ let mut skipped_initial_instruction = false; let mut stack = vec![address]; while !stack.is_empty() { let address = stack.pop().unwrap(); for pair in graph.get_adjacent(&address).into_iter().rev() { if let Ok((addr, link)) = pair { match link.type_ { LinkType::Next | LinkType::Branch | LinkType::SwitchCaseJump => { stack.push(*addr); } _ => (), } } } if !skipped_initial_instruction { skipped_initial_instruction = true; } let insn = graph.get_vertex(&address); if try_match(insn, register) { match insn.operands[1] { Operand::Register(_, r) => { return AssignmentTracker::find(graph, insn.address, r, &mut |i, reg| { if let Operand::Register(_, r) = i.operands[0] { if r == reg && i.code == Mnemonic::Imov { return true; } } return false; }); } Operand::ImmediateSigned(_, v) => return Some(v as u64), Operand::ImmediateUnsigned(_, v) => return Some(v), _ => { // TODO: logger.Warn("Cannot track assignments from 0x{0:x8} operand type {1}", instr.Offset, instr.Operands.[1].Type) return None; } } } if graph.get_in_value(insn.address) > 1 { // TODO: logger.Warn("Cannot track assignments from 0x{0:x8}, the number of incoming links > 1", instr.Offset) return None; } if let Mnemonic::Imov = insn.code { match (insn.operands[0], insn.operands[1]) { (Operand::Register(_, r0), Operand::Register(_, r1)) if r0 == register => { return AssignmentTracker::find(graph, insn.address, r1, try_match); } _ => {} } } } None }
identifier_body
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 0 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 0 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"], // standard ls format [ "-rw-r--r-- 1 500 500 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 500 500 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 500 500 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 500 500 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"] ] function checkData(request, data, ctx) { do_check_eq(tests[0][1], data); tests.shift(); next_test(); } function storeData(status, entry)
function next_test() { if (tests.length == 0) do_test_finished(); else { asyncOpenCacheEntry(URL, "FTP", Components.interfaces.nsICache.STORE_ANYWHERE, Components.interfaces.nsICache.ACCESS_READ_WRITE, storeData); } } function run_test() { do_execute_soon(next_test); do_test_pending(); }
{ do_check_eq(status, Components.results.NS_OK); entry.setMetaDataElement("servertype", "0"); var os = entry.openOutputStream(0); var written = os.write(tests[0][0], tests[0][0].length); if (written != tests[0][0].length) { do_throw("os.write has not written all data!\n" + " Expected: " + written + "\n" + " Actual: " + tests[0][0].length + "\n"); } os.close(); entry.close(); var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); var channel = ios.newChannel(URL, "", null); channel.asyncOpen(new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null); }
identifier_body
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 0 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 0 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"], // standard ls format [ "-rw-r--r-- 1 500 500 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 500 500 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 500 500 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 500 500 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"] ] function checkData(request, data, ctx) { do_check_eq(tests[0][1], data); tests.shift(); next_test(); } function storeData(status, entry) { do_check_eq(status, Components.results.NS_OK); entry.setMetaDataElement("servertype", "0"); var os = entry.openOutputStream(0); var written = os.write(tests[0][0], tests[0][0].length); if (written != tests[0][0].length)
os.close(); entry.close(); var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); var channel = ios.newChannel(URL, "", null); channel.asyncOpen(new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null); } function next_test() { if (tests.length == 0) do_test_finished(); else { asyncOpenCacheEntry(URL, "FTP", Components.interfaces.nsICache.STORE_ANYWHERE, Components.interfaces.nsICache.ACCESS_READ_WRITE, storeData); } } function run_test() { do_execute_soon(next_test); do_test_pending(); }
{ do_throw("os.write has not written all data!\n" + " Expected: " + written + "\n" + " Actual: " + tests[0][0].length + "\n"); }
conditional_block
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 0 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 0 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"], // standard ls format [ "-rw-r--r-- 1 500 500 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 500 500 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 500 500 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 500 500 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"] ] function checkData(request, data, ctx) { do_check_eq(tests[0][1], data); tests.shift();
do_check_eq(status, Components.results.NS_OK); entry.setMetaDataElement("servertype", "0"); var os = entry.openOutputStream(0); var written = os.write(tests[0][0], tests[0][0].length); if (written != tests[0][0].length) { do_throw("os.write has not written all data!\n" + " Expected: " + written + "\n" + " Actual: " + tests[0][0].length + "\n"); } os.close(); entry.close(); var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); var channel = ios.newChannel(URL, "", null); channel.asyncOpen(new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null); } function next_test() { if (tests.length == 0) do_test_finished(); else { asyncOpenCacheEntry(URL, "FTP", Components.interfaces.nsICache.STORE_ANYWHERE, Components.interfaces.nsICache.ACCESS_READ_WRITE, storeData); } } function run_test() { do_execute_soon(next_test); do_test_pending(); }
next_test(); } function storeData(status, entry) {
random_line_split
test_bug543805.js
const URL = "ftp://localhost/bug543805/"; var year = new Date().getFullYear().toString(); const tests = [ // AIX ls format ["-rw-r--r-- 1 0 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 0 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 0 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 0 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 0 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"], // standard ls format [ "-rw-r--r-- 1 500 500 11 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 22 Jan 1 20:19 test.blankfile\r\n" + "-rw-r--r-- 1 500 500 33 Apr 1 2008 test2.blankfile\r\n" + "-rw-r--r-- 1 500 500 44 Jan 1 20:19 nodup.file\r\n" + "-rw-r--r-- 1 500 500 55 Jan 1 20:19 test.file\r\n" + "-rw-r--r-- 1 500 500 66 Apr 1 2008 test2.file\r\n", "300: " + URL + "\n" + "200: filename content-length last-modified file-type\n" + "201: \"%20nodup.file\" 11 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test.blankfile\" 22 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"%20test2.blankfile\" 33 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n" + "201: \"nodup.file\" 44 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test.file\" 55 Sun%2C%2001%20Jan%20" + year + "%2020%3A19%3A00 FILE \n" + "201: \"test2.file\" 66 Sun%2C%2001%20Apr%202008%2000%3A00%3A00 FILE \n"] ] function checkData(request, data, ctx) { do_check_eq(tests[0][1], data); tests.shift(); next_test(); } function storeData(status, entry) { do_check_eq(status, Components.results.NS_OK); entry.setMetaDataElement("servertype", "0"); var os = entry.openOutputStream(0); var written = os.write(tests[0][0], tests[0][0].length); if (written != tests[0][0].length) { do_throw("os.write has not written all data!\n" + " Expected: " + written + "\n" + " Actual: " + tests[0][0].length + "\n"); } os.close(); entry.close(); var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService); var channel = ios.newChannel(URL, "", null); channel.asyncOpen(new ChannelListener(checkData, null, CL_ALLOW_UNKNOWN_CL), null); } function next_test() { if (tests.length == 0) do_test_finished(); else { asyncOpenCacheEntry(URL, "FTP", Components.interfaces.nsICache.STORE_ANYWHERE, Components.interfaces.nsICache.ACCESS_READ_WRITE, storeData); } } function
() { do_execute_soon(next_test); do_test_pending(); }
run_test
identifier_name
unwind.rs
// taken from https://github.com/thepowersgang/rust-barebones-kernel #[lang="panic_fmt"] #[no_mangle] pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) -> ! { // 'args' will print to the formatted string passed to panic! log!("file='{}', line={} :: {}", file, line, args); loop {} } #[lang="stack_exhausted"] #[no_mangle] pub extern "C" fn
() -> ! { loop {} } #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] pub enum _Unwind_Reason_Code { _URC_NO_REASON = 0, _URC_FOREIGN_EXCEPTION_CAUGHT = 1, _URC_FATAL_PHASE2_ERROR = 2, _URC_FATAL_PHASE1_ERROR = 3, _URC_NORMAL_STOP = 4, _URC_END_OF_STACK = 5, _URC_HANDLER_FOUND = 6, _URC_INSTALL_CONTEXT = 7, _URC_CONTINUE_UNWIND = 8, } #[allow(non_camel_case_types)] #[derive(Clone,Copy)] pub struct _Unwind_Context; #[allow(non_camel_case_types)] pub type _Unwind_Action = u32; static _UA_SEARCH_PHASE: _Unwind_Action = 1; #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] #[allow(raw_pointer_derive)] pub struct _Unwind_Exception { exception_class: u64, exception_cleanup: fn(_Unwind_Reason_Code, *const _Unwind_Exception), private: [u64; 2], } #[lang="eh_personality"] #[no_mangle] pub extern "C" fn rust_eh_personality(_version: isize, _actions: _Unwind_Action, _exception_class: u64, _exception_object: &_Unwind_Exception, _context: &_Unwind_Context) -> _Unwind_Reason_Code { loop {} } #[no_mangle] #[allow(non_snake_case)] pub extern "C" fn _Unwind_Resume() { loop {} }
__morestack
identifier_name
unwind.rs
// taken from https://github.com/thepowersgang/rust-barebones-kernel #[lang="panic_fmt"] #[no_mangle] pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) -> ! { // 'args' will print to the formatted string passed to panic! log!("file='{}', line={} :: {}", file, line, args); loop {} }
loop {} } #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] pub enum _Unwind_Reason_Code { _URC_NO_REASON = 0, _URC_FOREIGN_EXCEPTION_CAUGHT = 1, _URC_FATAL_PHASE2_ERROR = 2, _URC_FATAL_PHASE1_ERROR = 3, _URC_NORMAL_STOP = 4, _URC_END_OF_STACK = 5, _URC_HANDLER_FOUND = 6, _URC_INSTALL_CONTEXT = 7, _URC_CONTINUE_UNWIND = 8, } #[allow(non_camel_case_types)] #[derive(Clone,Copy)] pub struct _Unwind_Context; #[allow(non_camel_case_types)] pub type _Unwind_Action = u32; static _UA_SEARCH_PHASE: _Unwind_Action = 1; #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] #[allow(raw_pointer_derive)] pub struct _Unwind_Exception { exception_class: u64, exception_cleanup: fn(_Unwind_Reason_Code, *const _Unwind_Exception), private: [u64; 2], } #[lang="eh_personality"] #[no_mangle] pub extern "C" fn rust_eh_personality(_version: isize, _actions: _Unwind_Action, _exception_class: u64, _exception_object: &_Unwind_Exception, _context: &_Unwind_Context) -> _Unwind_Reason_Code { loop {} } #[no_mangle] #[allow(non_snake_case)] pub extern "C" fn _Unwind_Resume() { loop {} }
#[lang="stack_exhausted"] #[no_mangle] pub extern "C" fn __morestack() -> ! {
random_line_split
unwind.rs
// taken from https://github.com/thepowersgang/rust-barebones-kernel #[lang="panic_fmt"] #[no_mangle] pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) -> ! { // 'args' will print to the formatted string passed to panic! log!("file='{}', line={} :: {}", file, line, args); loop {} } #[lang="stack_exhausted"] #[no_mangle] pub extern "C" fn __morestack() -> ! { loop {} } #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] pub enum _Unwind_Reason_Code { _URC_NO_REASON = 0, _URC_FOREIGN_EXCEPTION_CAUGHT = 1, _URC_FATAL_PHASE2_ERROR = 2, _URC_FATAL_PHASE1_ERROR = 3, _URC_NORMAL_STOP = 4, _URC_END_OF_STACK = 5, _URC_HANDLER_FOUND = 6, _URC_INSTALL_CONTEXT = 7, _URC_CONTINUE_UNWIND = 8, } #[allow(non_camel_case_types)] #[derive(Clone,Copy)] pub struct _Unwind_Context; #[allow(non_camel_case_types)] pub type _Unwind_Action = u32; static _UA_SEARCH_PHASE: _Unwind_Action = 1; #[allow(non_camel_case_types)] #[repr(C)] #[derive(Clone,Copy)] #[allow(raw_pointer_derive)] pub struct _Unwind_Exception { exception_class: u64, exception_cleanup: fn(_Unwind_Reason_Code, *const _Unwind_Exception), private: [u64; 2], } #[lang="eh_personality"] #[no_mangle] pub extern "C" fn rust_eh_personality(_version: isize, _actions: _Unwind_Action, _exception_class: u64, _exception_object: &_Unwind_Exception, _context: &_Unwind_Context) -> _Unwind_Reason_Code
#[no_mangle] #[allow(non_snake_case)] pub extern "C" fn _Unwind_Resume() { loop {} }
{ loop {} }
identifier_body
Interface.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * This class is used to define interfaces (similar to Java interfaces). * * See the description of the {@link #define} method how an interface is * defined. */ qx.Bootstrap.define("qx.Interface", { statics : { /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Define a new interface. Interface definitions look much like class definitions. * * The main difference is that the bodies of functions defined in <code>members</code> * and <code>statics</code> are called before the original function with the * same arguments. This can be used to check the passed arguments. If the * checks fail, an exception should be thrown. It is convenient to use the * method defined in {@link qx.core.MAssert} to check the arguments. * * In the <code>build</code> version the checks are omitted. * * For properties only the names are required so the value of the properties * can be empty maps. * * Example: * <pre class='javascript'> * qx.Interface.define("name", * { * extend: [SuperInterfaces], * * statics: * { * PI : 3.14 * }, * * properties: {"color": {}, "name": {} }, * * members: * { * meth1: function() {}, * meth2: function(a, b) { this.assertArgumentsCount(arguments, 2, 2); }, * meth3: function(c) { this.assertInterface(c.constructor, qx.some.Interface); } * }, * * events : * { * keydown : "qx.event.type.KeySequence" * } * }); * </pre> * * @param name {String} name of the interface * @param config {Map ? null} Interface definition structure. The configuration map has the following keys: * <table> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> * <tr><th>extend</th><td>Interface |<br>Interface[]</td><td>Single interface or array of interfaces this interface inherits from.</td></tr> * <tr><th>members</th><td>Map</td><td>Map of members of the interface.</td></tr> * <tr><th>statics</th><td>Map</td><td> * Map of statics of the interface. The statics will not get copied into the target class. * This is the same behaviour as statics in mixins ({@link qx.Mixin#define}). * </td></tr> * <tr><th>properties</th><td>Map</td><td>Map of properties and their definitions.</td></tr> * <tr><th>events</th><td>Map</td><td>Map of event names and the corresponding event class name.</td></tr> * </table> */ define : function(name, config) { if (config) { // Normalize include if (config.extend && !(qx.Bootstrap.getClass(config.extend) === "Array")) { config.extend = [config.extend]; } // Validate incoming data if (qx.core.Environment.get("qx.debug")) { this.__validateConfig(name, config); } // Create interface from statics var iface = config.statics ? config.statics : {}; // Attach configuration if (config.extend) { iface.$$extends = config.extend; } if (config.properties) { iface.$$properties = config.properties; } if (config.members) { iface.$$members = config.members; } if (config.events) { iface.$$events = config.events; } } else { // Create empty interface var iface = {}; } // Add Basics iface.$$type = "Interface"; iface.name = name; // Attach toString iface.toString = this.genericToString; // Assign to namespace iface.basename = qx.Bootstrap.createNamespace(name, iface); // Add to registry qx.Interface.$$registry[name] = iface; // Return final interface return iface; }, /** * Returns an interface by name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name) { return this.$$registry[name]; }, /** * Determine if interface exists * * @param name {String} Interface name to check * @return {Boolean} true if interface exists */ isDefined : function(name) { return this.getByName(name) !== undefined; }, /** * Determine the number of interfaces which are defined * * @return {Number} the number of interfaces */ getTotalNumber : function() { return qx.Bootstrap.objectGetLength(this.$$registry); }, /** * Generates a list of all interfaces including their super interfaces * (resolved recursively) * * @param ifaces {Interface[] ? []} List of interfaces to be resolved * @return {Array} List of all interfaces */ flatten : function(ifaces) { if (!ifaces) { return []; } // we need to create a copy and not to modify the existing array var list = ifaces.concat(); for (var i=0, l=ifaces.length; i<l; i++) { if (ifaces[i].$$extends) { list.push.apply(list, this.flatten(ifaces[i].$$extends)); } } return list; }, /** * Assert members * * @param object {qx.core.Object} The object, which contains the methods * @param clazz {Class} class of the object * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ __assertMembers : function(object, clazz, iface, wrap) { // Validate members var members = iface.$$members; if (members) { for (var key in members) { if (qx.Bootstrap.isFunction(members[key])) { var isPropertyMethod = this.__isPropertyMethod(clazz, key); var hasMemberFunction = isPropertyMethod || qx.Bootstrap.isFunction(object[key]); if (!hasMemberFunction) { throw new Error( 'Implementation of method "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } // Only wrap members if the interface was not been applied yet. This // can easily be checked by the recursive hasInterface method. var shouldWrapFunction = wrap === true && !isPropertyMethod && !qx.util.OOUtil.hasInterface(clazz, iface); if (shouldWrapFunction) { object[key] = this.__wrapInterfaceMember( iface, object[key], key, members[key] ); } } else { // Other members are not checked more detailed because of // JavaScript's loose type handling if (typeof object[key] === undefined) { if (typeof object[key] !== "function") { throw new Error( 'Implementation of member "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } } } } } }, /** * Internal helper to detect if the method will be generated by the * property system. * * @param clazz {Class} The current class. * @param methodName {String} The name of the method. * * @return {Boolean} true, if the method will be generated by the property * system. */ __isPropertyMethod: function(clazz, methodName) { var match = methodName.match(/^(is|toggle|get|set|reset)(.*)$/); if (!match) { return false; } var propertyName = qx.Bootstrap.firstLow(match[2]); var isPropertyMethod = qx.util.OOUtil.getPropertyDefinition(clazz, propertyName); if (!isPropertyMethod) { return false; } var isBoolean = match[0] == "is" || match[0] == "toggle"; if (isBoolean) { return qx.util.OOUtil.getPropertyDefinition(clazz, propertyName).check == "Boolean"; } return true; }, /** * Assert properties * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertProperties : function(clazz, iface) { if (iface.$$properties) { for (var key in iface.$$properties) { if (!qx.util.OOUtil.getPropertyDefinition(clazz, key)) { throw new Error( 'The property "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Assert events * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertEvents : function(clazz, iface) { if (iface.$$events)
}, /** * Asserts that the given object implements all the methods defined in the * interface. This method throws an exception if the object does not * implement the interface. * * @param object {qx.core.Object} Object to check interface for * @param iface {Interface} The interface to verify */ assertObject : function(object, iface) { var clazz = object.constructor; this.__assertMembers(object, clazz, iface, false); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assertObject(object, extend[i]); } } }, /** * Checks if an interface is implemented by a class * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ assert : function(clazz, iface, wrap) { this.__assertMembers(clazz.prototype, clazz, iface, wrap); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assert(clazz, extend[i], wrap); } } }, /* --------------------------------------------------------------------------- PRIVATE/INTERNAL API --------------------------------------------------------------------------- */ /** * This method will be attached to all interface to return * a nice identifier for them. * * @internal * @return {String} The interface identifier */ genericToString : function() { return "[Interface " + this.name + "]"; }, /** Registry of all defined interfaces */ $$registry : {}, /** * Wrap a method with a precondition check. * * @signature function(iface, origFunction, functionName, preCondition) * @param iface {String} Name of the interface, where the pre condition * was defined. (Used in error messages). * @param origFunction {Function} function to wrap. * @param functionName {String} name of the function. (Used in error messages). * @param preCondition {Function}. This function gets called with the arguments of the * original function. If this function return true the original function is called. * Otherwise an exception is thrown. * @return {Function} wrapped function */ __wrapInterfaceMember : qx.core.Environment.select("qx.debug", { "true": function(iface, origFunction, functionName, preCondition) { function wrappedFunction() { // call precondition preCondition.apply(this, arguments); // call original function return origFunction.apply(this, arguments); } origFunction.wrapper = wrappedFunction; return wrappedFunction; }, "default" : function() {} }), /** {Map} allowed keys in interface definition */ __allowedKeys : qx.core.Environment.select("qx.debug", { "true": { "extend" : "object", // Interface | Interface[] "statics" : "object", // Map "members" : "object", // Map "properties" : "object", // Map "events" : "object" // Map }, "default" : null }), /** * Validates incoming configuration and checks keys and values * * @signature function(name, config) * @param name {String} The name of the class * @param config {Map} Configuration map */ __validateConfig : qx.core.Environment.select("qx.debug", { "true": function(name, config) { if (qx.core.Environment.get("qx.debug")) { // Validate keys var allowed = this.__allowedKeys; for (var key in config) { if (allowed[key] === undefined) { throw new Error('The configuration key "' + key + '" in class "' + name + '" is not allowed!'); } if (config[key] == null) { throw new Error("Invalid key '" + key + "' in interface '" + name + "'! The value is undefined/null!"); } if (allowed[key] !== null && typeof config[key] !== allowed[key]) { throw new Error('Invalid type of key "' + key + '" in interface "' + name + '"! The type of the key must be "' + allowed[key] + '"!'); } } // Validate maps var maps = [ "statics", "members", "properties", "events" ]; for (var i=0, l=maps.length; i<l; i++) { var key = maps[i]; if (config[key] !== undefined && ([ "Array", "RegExp", "Date" ].indexOf(qx.Bootstrap.getClass(config[key])) != -1 || config[key].classname !== undefined)) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! The value needs to be a map!'); } } // Validate extends if (config.extend) { for (var i=0, a=config.extend, l=a.length; i<l; i++) { if (a[i] == null) { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is undefined/null!"); } if (a[i].$$type !== "Interface") { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is not an interface!"); } } } // Validate statics if (config.statics) { for (var key in config.statics) { if (key.toUpperCase() !== key) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all uppercase.'); } switch(typeof config.statics[key]) { case "boolean": case "string": case "number": break; default: throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all of a primitive type.') } } } } }, "default" : function() {} }) } });
{ for (var key in iface.$$events) { if (!qx.util.OOUtil.supportsEvent(clazz, key)) { throw new Error( 'The event "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } }
conditional_block
Interface.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * This class is used to define interfaces (similar to Java interfaces). * * See the description of the {@link #define} method how an interface is * defined. */ qx.Bootstrap.define("qx.Interface", { statics : { /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Define a new interface. Interface definitions look much like class definitions. * * The main difference is that the bodies of functions defined in <code>members</code> * and <code>statics</code> are called before the original function with the * same arguments. This can be used to check the passed arguments. If the * checks fail, an exception should be thrown. It is convenient to use the * method defined in {@link qx.core.MAssert} to check the arguments. * * In the <code>build</code> version the checks are omitted. * * For properties only the names are required so the value of the properties * can be empty maps. * * Example: * <pre class='javascript'> * qx.Interface.define("name", * { * extend: [SuperInterfaces], * * statics: * { * PI : 3.14 * }, * * properties: {"color": {}, "name": {} }, * * members: * { * meth1: function() {}, * meth2: function(a, b) { this.assertArgumentsCount(arguments, 2, 2); }, * meth3: function(c) { this.assertInterface(c.constructor, qx.some.Interface); } * }, * * events : * { * keydown : "qx.event.type.KeySequence" * } * }); * </pre> * * @param name {String} name of the interface * @param config {Map ? null} Interface definition structure. The configuration map has the following keys: * <table> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> * <tr><th>extend</th><td>Interface |<br>Interface[]</td><td>Single interface or array of interfaces this interface inherits from.</td></tr> * <tr><th>members</th><td>Map</td><td>Map of members of the interface.</td></tr> * <tr><th>statics</th><td>Map</td><td> * Map of statics of the interface. The statics will not get copied into the target class. * This is the same behaviour as statics in mixins ({@link qx.Mixin#define}). * </td></tr> * <tr><th>properties</th><td>Map</td><td>Map of properties and their definitions.</td></tr> * <tr><th>events</th><td>Map</td><td>Map of event names and the corresponding event class name.</td></tr> * </table> */ define : function(name, config) { if (config) { // Normalize include if (config.extend && !(qx.Bootstrap.getClass(config.extend) === "Array")) { config.extend = [config.extend]; } // Validate incoming data if (qx.core.Environment.get("qx.debug")) { this.__validateConfig(name, config); } // Create interface from statics var iface = config.statics ? config.statics : {}; // Attach configuration if (config.extend) { iface.$$extends = config.extend; } if (config.properties) { iface.$$properties = config.properties; } if (config.members) { iface.$$members = config.members; } if (config.events) {
} } else { // Create empty interface var iface = {}; } // Add Basics iface.$$type = "Interface"; iface.name = name; // Attach toString iface.toString = this.genericToString; // Assign to namespace iface.basename = qx.Bootstrap.createNamespace(name, iface); // Add to registry qx.Interface.$$registry[name] = iface; // Return final interface return iface; }, /** * Returns an interface by name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name) { return this.$$registry[name]; }, /** * Determine if interface exists * * @param name {String} Interface name to check * @return {Boolean} true if interface exists */ isDefined : function(name) { return this.getByName(name) !== undefined; }, /** * Determine the number of interfaces which are defined * * @return {Number} the number of interfaces */ getTotalNumber : function() { return qx.Bootstrap.objectGetLength(this.$$registry); }, /** * Generates a list of all interfaces including their super interfaces * (resolved recursively) * * @param ifaces {Interface[] ? []} List of interfaces to be resolved * @return {Array} List of all interfaces */ flatten : function(ifaces) { if (!ifaces) { return []; } // we need to create a copy and not to modify the existing array var list = ifaces.concat(); for (var i=0, l=ifaces.length; i<l; i++) { if (ifaces[i].$$extends) { list.push.apply(list, this.flatten(ifaces[i].$$extends)); } } return list; }, /** * Assert members * * @param object {qx.core.Object} The object, which contains the methods * @param clazz {Class} class of the object * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ __assertMembers : function(object, clazz, iface, wrap) { // Validate members var members = iface.$$members; if (members) { for (var key in members) { if (qx.Bootstrap.isFunction(members[key])) { var isPropertyMethod = this.__isPropertyMethod(clazz, key); var hasMemberFunction = isPropertyMethod || qx.Bootstrap.isFunction(object[key]); if (!hasMemberFunction) { throw new Error( 'Implementation of method "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } // Only wrap members if the interface was not been applied yet. This // can easily be checked by the recursive hasInterface method. var shouldWrapFunction = wrap === true && !isPropertyMethod && !qx.util.OOUtil.hasInterface(clazz, iface); if (shouldWrapFunction) { object[key] = this.__wrapInterfaceMember( iface, object[key], key, members[key] ); } } else { // Other members are not checked more detailed because of // JavaScript's loose type handling if (typeof object[key] === undefined) { if (typeof object[key] !== "function") { throw new Error( 'Implementation of member "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } } } } } }, /** * Internal helper to detect if the method will be generated by the * property system. * * @param clazz {Class} The current class. * @param methodName {String} The name of the method. * * @return {Boolean} true, if the method will be generated by the property * system. */ __isPropertyMethod: function(clazz, methodName) { var match = methodName.match(/^(is|toggle|get|set|reset)(.*)$/); if (!match) { return false; } var propertyName = qx.Bootstrap.firstLow(match[2]); var isPropertyMethod = qx.util.OOUtil.getPropertyDefinition(clazz, propertyName); if (!isPropertyMethod) { return false; } var isBoolean = match[0] == "is" || match[0] == "toggle"; if (isBoolean) { return qx.util.OOUtil.getPropertyDefinition(clazz, propertyName).check == "Boolean"; } return true; }, /** * Assert properties * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertProperties : function(clazz, iface) { if (iface.$$properties) { for (var key in iface.$$properties) { if (!qx.util.OOUtil.getPropertyDefinition(clazz, key)) { throw new Error( 'The property "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Assert events * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertEvents : function(clazz, iface) { if (iface.$$events) { for (var key in iface.$$events) { if (!qx.util.OOUtil.supportsEvent(clazz, key)) { throw new Error( 'The event "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Asserts that the given object implements all the methods defined in the * interface. This method throws an exception if the object does not * implement the interface. * * @param object {qx.core.Object} Object to check interface for * @param iface {Interface} The interface to verify */ assertObject : function(object, iface) { var clazz = object.constructor; this.__assertMembers(object, clazz, iface, false); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assertObject(object, extend[i]); } } }, /** * Checks if an interface is implemented by a class * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ assert : function(clazz, iface, wrap) { this.__assertMembers(clazz.prototype, clazz, iface, wrap); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assert(clazz, extend[i], wrap); } } }, /* --------------------------------------------------------------------------- PRIVATE/INTERNAL API --------------------------------------------------------------------------- */ /** * This method will be attached to all interface to return * a nice identifier for them. * * @internal * @return {String} The interface identifier */ genericToString : function() { return "[Interface " + this.name + "]"; }, /** Registry of all defined interfaces */ $$registry : {}, /** * Wrap a method with a precondition check. * * @signature function(iface, origFunction, functionName, preCondition) * @param iface {String} Name of the interface, where the pre condition * was defined. (Used in error messages). * @param origFunction {Function} function to wrap. * @param functionName {String} name of the function. (Used in error messages). * @param preCondition {Function}. This function gets called with the arguments of the * original function. If this function return true the original function is called. * Otherwise an exception is thrown. * @return {Function} wrapped function */ __wrapInterfaceMember : qx.core.Environment.select("qx.debug", { "true": function(iface, origFunction, functionName, preCondition) { function wrappedFunction() { // call precondition preCondition.apply(this, arguments); // call original function return origFunction.apply(this, arguments); } origFunction.wrapper = wrappedFunction; return wrappedFunction; }, "default" : function() {} }), /** {Map} allowed keys in interface definition */ __allowedKeys : qx.core.Environment.select("qx.debug", { "true": { "extend" : "object", // Interface | Interface[] "statics" : "object", // Map "members" : "object", // Map "properties" : "object", // Map "events" : "object" // Map }, "default" : null }), /** * Validates incoming configuration and checks keys and values * * @signature function(name, config) * @param name {String} The name of the class * @param config {Map} Configuration map */ __validateConfig : qx.core.Environment.select("qx.debug", { "true": function(name, config) { if (qx.core.Environment.get("qx.debug")) { // Validate keys var allowed = this.__allowedKeys; for (var key in config) { if (allowed[key] === undefined) { throw new Error('The configuration key "' + key + '" in class "' + name + '" is not allowed!'); } if (config[key] == null) { throw new Error("Invalid key '" + key + "' in interface '" + name + "'! The value is undefined/null!"); } if (allowed[key] !== null && typeof config[key] !== allowed[key]) { throw new Error('Invalid type of key "' + key + '" in interface "' + name + '"! The type of the key must be "' + allowed[key] + '"!'); } } // Validate maps var maps = [ "statics", "members", "properties", "events" ]; for (var i=0, l=maps.length; i<l; i++) { var key = maps[i]; if (config[key] !== undefined && ([ "Array", "RegExp", "Date" ].indexOf(qx.Bootstrap.getClass(config[key])) != -1 || config[key].classname !== undefined)) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! The value needs to be a map!'); } } // Validate extends if (config.extend) { for (var i=0, a=config.extend, l=a.length; i<l; i++) { if (a[i] == null) { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is undefined/null!"); } if (a[i].$$type !== "Interface") { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is not an interface!"); } } } // Validate statics if (config.statics) { for (var key in config.statics) { if (key.toUpperCase() !== key) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all uppercase.'); } switch(typeof config.statics[key]) { case "boolean": case "string": case "number": break; default: throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all of a primitive type.') } } } } }, "default" : function() {} }) } });
iface.$$events = config.events;
random_line_split
Interface.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * This class is used to define interfaces (similar to Java interfaces). * * See the description of the {@link #define} method how an interface is * defined. */ qx.Bootstrap.define("qx.Interface", { statics : { /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Define a new interface. Interface definitions look much like class definitions. * * The main difference is that the bodies of functions defined in <code>members</code> * and <code>statics</code> are called before the original function with the * same arguments. This can be used to check the passed arguments. If the * checks fail, an exception should be thrown. It is convenient to use the * method defined in {@link qx.core.MAssert} to check the arguments. * * In the <code>build</code> version the checks are omitted. * * For properties only the names are required so the value of the properties * can be empty maps. * * Example: * <pre class='javascript'> * qx.Interface.define("name", * { * extend: [SuperInterfaces], * * statics: * { * PI : 3.14 * }, * * properties: {"color": {}, "name": {} }, * * members: * { * meth1: function() {}, * meth2: function(a, b) { this.assertArgumentsCount(arguments, 2, 2); }, * meth3: function(c) { this.assertInterface(c.constructor, qx.some.Interface); } * }, * * events : * { * keydown : "qx.event.type.KeySequence" * } * }); * </pre> * * @param name {String} name of the interface * @param config {Map ? null} Interface definition structure. The configuration map has the following keys: * <table> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> * <tr><th>extend</th><td>Interface |<br>Interface[]</td><td>Single interface or array of interfaces this interface inherits from.</td></tr> * <tr><th>members</th><td>Map</td><td>Map of members of the interface.</td></tr> * <tr><th>statics</th><td>Map</td><td> * Map of statics of the interface. The statics will not get copied into the target class. * This is the same behaviour as statics in mixins ({@link qx.Mixin#define}). * </td></tr> * <tr><th>properties</th><td>Map</td><td>Map of properties and their definitions.</td></tr> * <tr><th>events</th><td>Map</td><td>Map of event names and the corresponding event class name.</td></tr> * </table> */ define : function(name, config) { if (config) { // Normalize include if (config.extend && !(qx.Bootstrap.getClass(config.extend) === "Array")) { config.extend = [config.extend]; } // Validate incoming data if (qx.core.Environment.get("qx.debug")) { this.__validateConfig(name, config); } // Create interface from statics var iface = config.statics ? config.statics : {}; // Attach configuration if (config.extend) { iface.$$extends = config.extend; } if (config.properties) { iface.$$properties = config.properties; } if (config.members) { iface.$$members = config.members; } if (config.events) { iface.$$events = config.events; } } else { // Create empty interface var iface = {}; } // Add Basics iface.$$type = "Interface"; iface.name = name; // Attach toString iface.toString = this.genericToString; // Assign to namespace iface.basename = qx.Bootstrap.createNamespace(name, iface); // Add to registry qx.Interface.$$registry[name] = iface; // Return final interface return iface; }, /** * Returns an interface by name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name) { return this.$$registry[name]; }, /** * Determine if interface exists * * @param name {String} Interface name to check * @return {Boolean} true if interface exists */ isDefined : function(name) { return this.getByName(name) !== undefined; }, /** * Determine the number of interfaces which are defined * * @return {Number} the number of interfaces */ getTotalNumber : function() { return qx.Bootstrap.objectGetLength(this.$$registry); }, /** * Generates a list of all interfaces including their super interfaces * (resolved recursively) * * @param ifaces {Interface[] ? []} List of interfaces to be resolved * @return {Array} List of all interfaces */ flatten : function(ifaces) { if (!ifaces) { return []; } // we need to create a copy and not to modify the existing array var list = ifaces.concat(); for (var i=0, l=ifaces.length; i<l; i++) { if (ifaces[i].$$extends) { list.push.apply(list, this.flatten(ifaces[i].$$extends)); } } return list; }, /** * Assert members * * @param object {qx.core.Object} The object, which contains the methods * @param clazz {Class} class of the object * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ __assertMembers : function(object, clazz, iface, wrap) { // Validate members var members = iface.$$members; if (members) { for (var key in members) { if (qx.Bootstrap.isFunction(members[key])) { var isPropertyMethod = this.__isPropertyMethod(clazz, key); var hasMemberFunction = isPropertyMethod || qx.Bootstrap.isFunction(object[key]); if (!hasMemberFunction) { throw new Error( 'Implementation of method "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } // Only wrap members if the interface was not been applied yet. This // can easily be checked by the recursive hasInterface method. var shouldWrapFunction = wrap === true && !isPropertyMethod && !qx.util.OOUtil.hasInterface(clazz, iface); if (shouldWrapFunction) { object[key] = this.__wrapInterfaceMember( iface, object[key], key, members[key] ); } } else { // Other members are not checked more detailed because of // JavaScript's loose type handling if (typeof object[key] === undefined) { if (typeof object[key] !== "function") { throw new Error( 'Implementation of member "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } } } } } }, /** * Internal helper to detect if the method will be generated by the * property system. * * @param clazz {Class} The current class. * @param methodName {String} The name of the method. * * @return {Boolean} true, if the method will be generated by the property * system. */ __isPropertyMethod: function(clazz, methodName) { var match = methodName.match(/^(is|toggle|get|set|reset)(.*)$/); if (!match) { return false; } var propertyName = qx.Bootstrap.firstLow(match[2]); var isPropertyMethod = qx.util.OOUtil.getPropertyDefinition(clazz, propertyName); if (!isPropertyMethod) { return false; } var isBoolean = match[0] == "is" || match[0] == "toggle"; if (isBoolean) { return qx.util.OOUtil.getPropertyDefinition(clazz, propertyName).check == "Boolean"; } return true; }, /** * Assert properties * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertProperties : function(clazz, iface) { if (iface.$$properties) { for (var key in iface.$$properties) { if (!qx.util.OOUtil.getPropertyDefinition(clazz, key)) { throw new Error( 'The property "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Assert events * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertEvents : function(clazz, iface) { if (iface.$$events) { for (var key in iface.$$events) { if (!qx.util.OOUtil.supportsEvent(clazz, key)) { throw new Error( 'The event "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Asserts that the given object implements all the methods defined in the * interface. This method throws an exception if the object does not * implement the interface. * * @param object {qx.core.Object} Object to check interface for * @param iface {Interface} The interface to verify */ assertObject : function(object, iface) { var clazz = object.constructor; this.__assertMembers(object, clazz, iface, false); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assertObject(object, extend[i]); } } }, /** * Checks if an interface is implemented by a class * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ assert : function(clazz, iface, wrap) { this.__assertMembers(clazz.prototype, clazz, iface, wrap); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assert(clazz, extend[i], wrap); } } }, /* --------------------------------------------------------------------------- PRIVATE/INTERNAL API --------------------------------------------------------------------------- */ /** * This method will be attached to all interface to return * a nice identifier for them. * * @internal * @return {String} The interface identifier */ genericToString : function() { return "[Interface " + this.name + "]"; }, /** Registry of all defined interfaces */ $$registry : {}, /** * Wrap a method with a precondition check. * * @signature function(iface, origFunction, functionName, preCondition) * @param iface {String} Name of the interface, where the pre condition * was defined. (Used in error messages). * @param origFunction {Function} function to wrap. * @param functionName {String} name of the function. (Used in error messages). * @param preCondition {Function}. This function gets called with the arguments of the * original function. If this function return true the original function is called. * Otherwise an exception is thrown. * @return {Function} wrapped function */ __wrapInterfaceMember : qx.core.Environment.select("qx.debug", { "true": function(iface, origFunction, functionName, preCondition) { function
() { // call precondition preCondition.apply(this, arguments); // call original function return origFunction.apply(this, arguments); } origFunction.wrapper = wrappedFunction; return wrappedFunction; }, "default" : function() {} }), /** {Map} allowed keys in interface definition */ __allowedKeys : qx.core.Environment.select("qx.debug", { "true": { "extend" : "object", // Interface | Interface[] "statics" : "object", // Map "members" : "object", // Map "properties" : "object", // Map "events" : "object" // Map }, "default" : null }), /** * Validates incoming configuration and checks keys and values * * @signature function(name, config) * @param name {String} The name of the class * @param config {Map} Configuration map */ __validateConfig : qx.core.Environment.select("qx.debug", { "true": function(name, config) { if (qx.core.Environment.get("qx.debug")) { // Validate keys var allowed = this.__allowedKeys; for (var key in config) { if (allowed[key] === undefined) { throw new Error('The configuration key "' + key + '" in class "' + name + '" is not allowed!'); } if (config[key] == null) { throw new Error("Invalid key '" + key + "' in interface '" + name + "'! The value is undefined/null!"); } if (allowed[key] !== null && typeof config[key] !== allowed[key]) { throw new Error('Invalid type of key "' + key + '" in interface "' + name + '"! The type of the key must be "' + allowed[key] + '"!'); } } // Validate maps var maps = [ "statics", "members", "properties", "events" ]; for (var i=0, l=maps.length; i<l; i++) { var key = maps[i]; if (config[key] !== undefined && ([ "Array", "RegExp", "Date" ].indexOf(qx.Bootstrap.getClass(config[key])) != -1 || config[key].classname !== undefined)) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! The value needs to be a map!'); } } // Validate extends if (config.extend) { for (var i=0, a=config.extend, l=a.length; i<l; i++) { if (a[i] == null) { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is undefined/null!"); } if (a[i].$$type !== "Interface") { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is not an interface!"); } } } // Validate statics if (config.statics) { for (var key in config.statics) { if (key.toUpperCase() !== key) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all uppercase.'); } switch(typeof config.statics[key]) { case "boolean": case "string": case "number": break; default: throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all of a primitive type.') } } } } }, "default" : function() {} }) } });
wrappedFunction
identifier_name
Interface.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * This class is used to define interfaces (similar to Java interfaces). * * See the description of the {@link #define} method how an interface is * defined. */ qx.Bootstrap.define("qx.Interface", { statics : { /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Define a new interface. Interface definitions look much like class definitions. * * The main difference is that the bodies of functions defined in <code>members</code> * and <code>statics</code> are called before the original function with the * same arguments. This can be used to check the passed arguments. If the * checks fail, an exception should be thrown. It is convenient to use the * method defined in {@link qx.core.MAssert} to check the arguments. * * In the <code>build</code> version the checks are omitted. * * For properties only the names are required so the value of the properties * can be empty maps. * * Example: * <pre class='javascript'> * qx.Interface.define("name", * { * extend: [SuperInterfaces], * * statics: * { * PI : 3.14 * }, * * properties: {"color": {}, "name": {} }, * * members: * { * meth1: function() {}, * meth2: function(a, b) { this.assertArgumentsCount(arguments, 2, 2); }, * meth3: function(c) { this.assertInterface(c.constructor, qx.some.Interface); } * }, * * events : * { * keydown : "qx.event.type.KeySequence" * } * }); * </pre> * * @param name {String} name of the interface * @param config {Map ? null} Interface definition structure. The configuration map has the following keys: * <table> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> * <tr><th>extend</th><td>Interface |<br>Interface[]</td><td>Single interface or array of interfaces this interface inherits from.</td></tr> * <tr><th>members</th><td>Map</td><td>Map of members of the interface.</td></tr> * <tr><th>statics</th><td>Map</td><td> * Map of statics of the interface. The statics will not get copied into the target class. * This is the same behaviour as statics in mixins ({@link qx.Mixin#define}). * </td></tr> * <tr><th>properties</th><td>Map</td><td>Map of properties and their definitions.</td></tr> * <tr><th>events</th><td>Map</td><td>Map of event names and the corresponding event class name.</td></tr> * </table> */ define : function(name, config) { if (config) { // Normalize include if (config.extend && !(qx.Bootstrap.getClass(config.extend) === "Array")) { config.extend = [config.extend]; } // Validate incoming data if (qx.core.Environment.get("qx.debug")) { this.__validateConfig(name, config); } // Create interface from statics var iface = config.statics ? config.statics : {}; // Attach configuration if (config.extend) { iface.$$extends = config.extend; } if (config.properties) { iface.$$properties = config.properties; } if (config.members) { iface.$$members = config.members; } if (config.events) { iface.$$events = config.events; } } else { // Create empty interface var iface = {}; } // Add Basics iface.$$type = "Interface"; iface.name = name; // Attach toString iface.toString = this.genericToString; // Assign to namespace iface.basename = qx.Bootstrap.createNamespace(name, iface); // Add to registry qx.Interface.$$registry[name] = iface; // Return final interface return iface; }, /** * Returns an interface by name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name) { return this.$$registry[name]; }, /** * Determine if interface exists * * @param name {String} Interface name to check * @return {Boolean} true if interface exists */ isDefined : function(name) { return this.getByName(name) !== undefined; }, /** * Determine the number of interfaces which are defined * * @return {Number} the number of interfaces */ getTotalNumber : function() { return qx.Bootstrap.objectGetLength(this.$$registry); }, /** * Generates a list of all interfaces including their super interfaces * (resolved recursively) * * @param ifaces {Interface[] ? []} List of interfaces to be resolved * @return {Array} List of all interfaces */ flatten : function(ifaces) { if (!ifaces) { return []; } // we need to create a copy and not to modify the existing array var list = ifaces.concat(); for (var i=0, l=ifaces.length; i<l; i++) { if (ifaces[i].$$extends) { list.push.apply(list, this.flatten(ifaces[i].$$extends)); } } return list; }, /** * Assert members * * @param object {qx.core.Object} The object, which contains the methods * @param clazz {Class} class of the object * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ __assertMembers : function(object, clazz, iface, wrap) { // Validate members var members = iface.$$members; if (members) { for (var key in members) { if (qx.Bootstrap.isFunction(members[key])) { var isPropertyMethod = this.__isPropertyMethod(clazz, key); var hasMemberFunction = isPropertyMethod || qx.Bootstrap.isFunction(object[key]); if (!hasMemberFunction) { throw new Error( 'Implementation of method "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } // Only wrap members if the interface was not been applied yet. This // can easily be checked by the recursive hasInterface method. var shouldWrapFunction = wrap === true && !isPropertyMethod && !qx.util.OOUtil.hasInterface(clazz, iface); if (shouldWrapFunction) { object[key] = this.__wrapInterfaceMember( iface, object[key], key, members[key] ); } } else { // Other members are not checked more detailed because of // JavaScript's loose type handling if (typeof object[key] === undefined) { if (typeof object[key] !== "function") { throw new Error( 'Implementation of member "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } } } } } }, /** * Internal helper to detect if the method will be generated by the * property system. * * @param clazz {Class} The current class. * @param methodName {String} The name of the method. * * @return {Boolean} true, if the method will be generated by the property * system. */ __isPropertyMethod: function(clazz, methodName) { var match = methodName.match(/^(is|toggle|get|set|reset)(.*)$/); if (!match) { return false; } var propertyName = qx.Bootstrap.firstLow(match[2]); var isPropertyMethod = qx.util.OOUtil.getPropertyDefinition(clazz, propertyName); if (!isPropertyMethod) { return false; } var isBoolean = match[0] == "is" || match[0] == "toggle"; if (isBoolean) { return qx.util.OOUtil.getPropertyDefinition(clazz, propertyName).check == "Boolean"; } return true; }, /** * Assert properties * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertProperties : function(clazz, iface) { if (iface.$$properties) { for (var key in iface.$$properties) { if (!qx.util.OOUtil.getPropertyDefinition(clazz, key)) { throw new Error( 'The property "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Assert events * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertEvents : function(clazz, iface) { if (iface.$$events) { for (var key in iface.$$events) { if (!qx.util.OOUtil.supportsEvent(clazz, key)) { throw new Error( 'The event "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Asserts that the given object implements all the methods defined in the * interface. This method throws an exception if the object does not * implement the interface. * * @param object {qx.core.Object} Object to check interface for * @param iface {Interface} The interface to verify */ assertObject : function(object, iface) { var clazz = object.constructor; this.__assertMembers(object, clazz, iface, false); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assertObject(object, extend[i]); } } }, /** * Checks if an interface is implemented by a class * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ assert : function(clazz, iface, wrap) { this.__assertMembers(clazz.prototype, clazz, iface, wrap); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assert(clazz, extend[i], wrap); } } }, /* --------------------------------------------------------------------------- PRIVATE/INTERNAL API --------------------------------------------------------------------------- */ /** * This method will be attached to all interface to return * a nice identifier for them. * * @internal * @return {String} The interface identifier */ genericToString : function() { return "[Interface " + this.name + "]"; }, /** Registry of all defined interfaces */ $$registry : {}, /** * Wrap a method with a precondition check. * * @signature function(iface, origFunction, functionName, preCondition) * @param iface {String} Name of the interface, where the pre condition * was defined. (Used in error messages). * @param origFunction {Function} function to wrap. * @param functionName {String} name of the function. (Used in error messages). * @param preCondition {Function}. This function gets called with the arguments of the * original function. If this function return true the original function is called. * Otherwise an exception is thrown. * @return {Function} wrapped function */ __wrapInterfaceMember : qx.core.Environment.select("qx.debug", { "true": function(iface, origFunction, functionName, preCondition) { function wrappedFunction()
origFunction.wrapper = wrappedFunction; return wrappedFunction; }, "default" : function() {} }), /** {Map} allowed keys in interface definition */ __allowedKeys : qx.core.Environment.select("qx.debug", { "true": { "extend" : "object", // Interface | Interface[] "statics" : "object", // Map "members" : "object", // Map "properties" : "object", // Map "events" : "object" // Map }, "default" : null }), /** * Validates incoming configuration and checks keys and values * * @signature function(name, config) * @param name {String} The name of the class * @param config {Map} Configuration map */ __validateConfig : qx.core.Environment.select("qx.debug", { "true": function(name, config) { if (qx.core.Environment.get("qx.debug")) { // Validate keys var allowed = this.__allowedKeys; for (var key in config) { if (allowed[key] === undefined) { throw new Error('The configuration key "' + key + '" in class "' + name + '" is not allowed!'); } if (config[key] == null) { throw new Error("Invalid key '" + key + "' in interface '" + name + "'! The value is undefined/null!"); } if (allowed[key] !== null && typeof config[key] !== allowed[key]) { throw new Error('Invalid type of key "' + key + '" in interface "' + name + '"! The type of the key must be "' + allowed[key] + '"!'); } } // Validate maps var maps = [ "statics", "members", "properties", "events" ]; for (var i=0, l=maps.length; i<l; i++) { var key = maps[i]; if (config[key] !== undefined && ([ "Array", "RegExp", "Date" ].indexOf(qx.Bootstrap.getClass(config[key])) != -1 || config[key].classname !== undefined)) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! The value needs to be a map!'); } } // Validate extends if (config.extend) { for (var i=0, a=config.extend, l=a.length; i<l; i++) { if (a[i] == null) { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is undefined/null!"); } if (a[i].$$type !== "Interface") { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is not an interface!"); } } } // Validate statics if (config.statics) { for (var key in config.statics) { if (key.toUpperCase() !== key) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all uppercase.'); } switch(typeof config.statics[key]) { case "boolean": case "string": case "number": break; default: throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all of a primitive type.') } } } } }, "default" : function() {} }) } });
{ // call precondition preCondition.apply(this, arguments); // call original function return origFunction.apply(this, arguments); }
identifier_body
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import PackageFinder from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, ) from pip._internal.utils.packaging import get_installer logger = logging.getLogger(__name__) class ListCommand(Command): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ name = 'list' usage = """ %prog [options]""" summary = 'List installed packages.' def __init__(self, *args, **kw): super(ListCommand, self).__init__(*args, **kw) cmd_opts = self.cmd_opts cmd_opts.add_option( '-o', '--outdated', action='store_true', default=False, help='List outdated packages') cmd_opts.add_option( '-u', '--uptodate', action='store_true', default=False, help='List uptodate packages') cmd_opts.add_option( '-e', '--editable', action='store_true', default=False, help='List editable projects.') cmd_opts.add_option( '-l', '--local', action='store_true', default=False, help=('If in a virtualenv that has global access, do not list ' 'globally-installed packages.'), ) self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) cmd_opts.add_option( '--format', action='store', dest='list_format', default="columns", choices=('columns', 'freeze', 'json'), help="Select the output format among: columns (default), freeze, " "or json", ) cmd_opts.add_option( '--not-required', action='store_true', dest='not_required', help="List packages that are not dependencies of " "installed packages.", ) cmd_opts.add_option( '--exclude-editable', action='store_false', dest='include_editable', help='Exclude editable package from output.', ) cmd_opts.add_option( '--include-editable', action='store_true', dest='include_editable', help='Include editable package from output.', default=True, ) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts) def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts, session=session, ) def run(self, options, args): if options.outdated and options.uptodate: raise CommandError( "Options --outdated and --uptodate cannot be combined.") packages = get_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, include_editables=options.include_editable, ) # get_not_required must be called firstly in order to find and # filter out all dependencies correctly. Otherwise a package # can't be identified as requirement because some parent packages # could be filtered out before. if options.not_required: packages = self.get_not_required(packages, options) if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options) self.output_package_listing(packages, options) def get_outdated(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.parsed_version ] def get_uptodate(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.parsed_version ] def get_not_required(self, packages, options): dep_keys = set() for dist in packages: dep_keys.update(requirement.key for requirement in dist.requires()) return {pkg for pkg in packages if pkg.key not in dep_keys} def iter_packages_latest_infos(self, packages, options): index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.debug('Ignoring indexes: %s', ','.join(index_urls)) index_urls = [] with self._build_session(options) as session: finder = self._build_package_finder(options, index_urls, session) for dist in packages: typ = 'unknown' all_candidates = finder.find_all_candidates(dist.key) if not options.pre: # Remove prereleases all_candidates = [candidate for candidate in all_candidates if not candidate.version.is_prerelease] if not all_candidates: continue best_candidate = max(all_candidates, key=finder._candidate_sort_key) remote_version = best_candidate.version if best_candidate.location.is_wheel: typ = 'wheel' else: typ = 'sdist' # This is dirty but makes the rest of the code much cleaner dist.latest_version = remote_version dist.latest_filetype = typ yield dist def output_package_listing(self, packages, options): packages = sorted( packages, key=lambda dist: dist.project_name.lower(), ) if options.list_format == 'columns' and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == 'freeze': for dist in packages: if options.verbose >= 1: logger.info("%s==%s (%s)", dist.project_name, dist.version, dist.location) else: logger.info("%s==%s", dist.project_name, dist.version) elif options.list_format == 'json':
def output_package_listing_columns(self, data, header): # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join(map(lambda x: '-' * x, sizes))) for val in pkg_strings: logger.info(val) def tabulate(vals): # From pfmoore on GitHub: # https://github.com/pypa/pip/issues/3651#issuecomment-216932564 assert len(vals) > 0 sizes = [0] * max(len(x) for x in vals) for row in vals: sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)] result = [] for row in vals: display = " ".join([str(c).ljust(s) if c is not None else '' for s, c in zip_longest(sizes, row)]) result.append(display) return result, sizes def format_for_columns(pkgs, options): """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header def format_for_json(packages, options): data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.verbose >= 1: info['location'] = dist.location info['installer'] = get_installer(dist) if options.outdated: info['latest_version'] = six.text_type(dist.latest_version) info['latest_filetype'] = dist.latest_filetype data.append(info) return json.dumps(data)
logger.info(format_for_json(packages, options))
conditional_block
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import PackageFinder from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, ) from pip._internal.utils.packaging import get_installer logger = logging.getLogger(__name__) class ListCommand(Command): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ name = 'list' usage = """ %prog [options]""" summary = 'List installed packages.' def __init__(self, *args, **kw): super(ListCommand, self).__init__(*args, **kw) cmd_opts = self.cmd_opts cmd_opts.add_option( '-o', '--outdated', action='store_true', default=False, help='List outdated packages') cmd_opts.add_option( '-u', '--uptodate', action='store_true', default=False, help='List uptodate packages') cmd_opts.add_option( '-e', '--editable', action='store_true', default=False, help='List editable projects.') cmd_opts.add_option( '-l', '--local', action='store_true', default=False, help=('If in a virtualenv that has global access, do not list ' 'globally-installed packages.'), ) self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) cmd_opts.add_option( '--format', action='store', dest='list_format', default="columns", choices=('columns', 'freeze', 'json'), help="Select the output format among: columns (default), freeze, " "or json", ) cmd_opts.add_option( '--not-required', action='store_true', dest='not_required', help="List packages that are not dependencies of " "installed packages.", ) cmd_opts.add_option( '--exclude-editable', action='store_false', dest='include_editable', help='Exclude editable package from output.', ) cmd_opts.add_option( '--include-editable', action='store_true', dest='include_editable', help='Include editable package from output.', default=True, ) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts) def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts, session=session, ) def run(self, options, args): if options.outdated and options.uptodate: raise CommandError( "Options --outdated and --uptodate cannot be combined.") packages = get_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, include_editables=options.include_editable, ) # get_not_required must be called firstly in order to find and # filter out all dependencies correctly. Otherwise a package # can't be identified as requirement because some parent packages # could be filtered out before. if options.not_required: packages = self.get_not_required(packages, options) if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options) self.output_package_listing(packages, options) def get_outdated(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.parsed_version ] def get_uptodate(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.parsed_version ] def get_not_required(self, packages, options): dep_keys = set() for dist in packages: dep_keys.update(requirement.key for requirement in dist.requires()) return {pkg for pkg in packages if pkg.key not in dep_keys} def iter_packages_latest_infos(self, packages, options): index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.debug('Ignoring indexes: %s', ','.join(index_urls)) index_urls = [] with self._build_session(options) as session: finder = self._build_package_finder(options, index_urls, session) for dist in packages: typ = 'unknown' all_candidates = finder.find_all_candidates(dist.key) if not options.pre: # Remove prereleases all_candidates = [candidate for candidate in all_candidates if not candidate.version.is_prerelease] if not all_candidates: continue best_candidate = max(all_candidates, key=finder._candidate_sort_key) remote_version = best_candidate.version if best_candidate.location.is_wheel: typ = 'wheel' else: typ = 'sdist' # This is dirty but makes the rest of the code much cleaner dist.latest_version = remote_version dist.latest_filetype = typ yield dist def output_package_listing(self, packages, options): packages = sorted( packages, key=lambda dist: dist.project_name.lower(), ) if options.list_format == 'columns' and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == 'freeze': for dist in packages: if options.verbose >= 1: logger.info("%s==%s (%s)", dist.project_name, dist.version, dist.location) else: logger.info("%s==%s", dist.project_name, dist.version) elif options.list_format == 'json': logger.info(format_for_json(packages, options)) def output_package_listing_columns(self, data, header): # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join(map(lambda x: '-' * x, sizes))) for val in pkg_strings: logger.info(val) def tabulate(vals): # From pfmoore on GitHub: # https://github.com/pypa/pip/issues/3651#issuecomment-216932564 assert len(vals) > 0 sizes = [0] * max(len(x) for x in vals) for row in vals: sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)] result = [] for row in vals: display = " ".join([str(c).ljust(s) if c is not None else '' for s, c in zip_longest(sizes, row)]) result.append(display) return result, sizes def format_for_columns(pkgs, options): """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header def format_for_json(packages, options):
data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.verbose >= 1: info['location'] = dist.location info['installer'] = get_installer(dist) if options.outdated: info['latest_version'] = six.text_type(dist.latest_version) info['latest_filetype'] = dist.latest_filetype data.append(info) return json.dumps(data)
identifier_body
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import PackageFinder from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, ) from pip._internal.utils.packaging import get_installer logger = logging.getLogger(__name__) class ListCommand(Command): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ name = 'list' usage = """ %prog [options]""" summary = 'List installed packages.' def __init__(self, *args, **kw): super(ListCommand, self).__init__(*args, **kw) cmd_opts = self.cmd_opts cmd_opts.add_option( '-o', '--outdated', action='store_true', default=False, help='List outdated packages') cmd_opts.add_option( '-u', '--uptodate', action='store_true', default=False, help='List uptodate packages') cmd_opts.add_option( '-e', '--editable', action='store_true', default=False, help='List editable projects.') cmd_opts.add_option( '-l', '--local', action='store_true', default=False, help=('If in a virtualenv that has global access, do not list ' 'globally-installed packages.'), ) self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) cmd_opts.add_option( '--format', action='store', dest='list_format', default="columns", choices=('columns', 'freeze', 'json'), help="Select the output format among: columns (default), freeze, " "or json", ) cmd_opts.add_option( '--not-required', action='store_true', dest='not_required', help="List packages that are not dependencies of " "installed packages.", ) cmd_opts.add_option( '--exclude-editable', action='store_false', dest='include_editable', help='Exclude editable package from output.', ) cmd_opts.add_option( '--include-editable', action='store_true', dest='include_editable', help='Include editable package from output.', default=True, ) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts) def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts, session=session, ) def run(self, options, args): if options.outdated and options.uptodate: raise CommandError( "Options --outdated and --uptodate cannot be combined.") packages = get_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, include_editables=options.include_editable, ) # get_not_required must be called firstly in order to find and # filter out all dependencies correctly. Otherwise a package # can't be identified as requirement because some parent packages # could be filtered out before. if options.not_required: packages = self.get_not_required(packages, options) if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options) self.output_package_listing(packages, options) def get_outdated(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.parsed_version ] def get_uptodate(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.parsed_version ] def get_not_required(self, packages, options): dep_keys = set() for dist in packages: dep_keys.update(requirement.key for requirement in dist.requires()) return {pkg for pkg in packages if pkg.key not in dep_keys} def iter_packages_latest_infos(self, packages, options): index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.debug('Ignoring indexes: %s', ','.join(index_urls)) index_urls = [] with self._build_session(options) as session: finder = self._build_package_finder(options, index_urls, session) for dist in packages: typ = 'unknown' all_candidates = finder.find_all_candidates(dist.key) if not options.pre: # Remove prereleases all_candidates = [candidate for candidate in all_candidates if not candidate.version.is_prerelease] if not all_candidates: continue best_candidate = max(all_candidates, key=finder._candidate_sort_key) remote_version = best_candidate.version if best_candidate.location.is_wheel: typ = 'wheel' else: typ = 'sdist' # This is dirty but makes the rest of the code much cleaner dist.latest_version = remote_version dist.latest_filetype = typ yield dist def output_package_listing(self, packages, options): packages = sorted( packages, key=lambda dist: dist.project_name.lower(), ) if options.list_format == 'columns' and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == 'freeze': for dist in packages: if options.verbose >= 1: logger.info("%s==%s (%s)", dist.project_name, dist.version, dist.location) else: logger.info("%s==%s", dist.project_name, dist.version) elif options.list_format == 'json': logger.info(format_for_json(packages, options)) def output_package_listing_columns(self, data, header): # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join(map(lambda x: '-' * x, sizes)))
def tabulate(vals): # From pfmoore on GitHub: # https://github.com/pypa/pip/issues/3651#issuecomment-216932564 assert len(vals) > 0 sizes = [0] * max(len(x) for x in vals) for row in vals: sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)] result = [] for row in vals: display = " ".join([str(c).ljust(s) if c is not None else '' for s, c in zip_longest(sizes, row)]) result.append(display) return result, sizes def format_for_columns(pkgs, options): """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header def format_for_json(packages, options): data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.verbose >= 1: info['location'] = dist.location info['installer'] = get_installer(dist) if options.outdated: info['latest_version'] = six.text_type(dist.latest_version) info['latest_filetype'] = dist.latest_filetype data.append(info) return json.dumps(data)
for val in pkg_strings: logger.info(val)
random_line_split
list.py
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import PackageFinder from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, ) from pip._internal.utils.packaging import get_installer logger = logging.getLogger(__name__) class ListCommand(Command): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ name = 'list' usage = """ %prog [options]""" summary = 'List installed packages.' def __init__(self, *args, **kw): super(ListCommand, self).__init__(*args, **kw) cmd_opts = self.cmd_opts cmd_opts.add_option( '-o', '--outdated', action='store_true', default=False, help='List outdated packages') cmd_opts.add_option( '-u', '--uptodate', action='store_true', default=False, help='List uptodate packages') cmd_opts.add_option( '-e', '--editable', action='store_true', default=False, help='List editable projects.') cmd_opts.add_option( '-l', '--local', action='store_true', default=False, help=('If in a virtualenv that has global access, do not list ' 'globally-installed packages.'), ) self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) cmd_opts.add_option( '--format', action='store', dest='list_format', default="columns", choices=('columns', 'freeze', 'json'), help="Select the output format among: columns (default), freeze, " "or json", ) cmd_opts.add_option( '--not-required', action='store_true', dest='not_required', help="List packages that are not dependencies of " "installed packages.", ) cmd_opts.add_option( '--exclude-editable', action='store_false', dest='include_editable', help='Exclude editable package from output.', ) cmd_opts.add_option( '--include-editable', action='store_true', dest='include_editable', help='Include editable package from output.', default=True, ) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts) def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts, session=session, ) def run(self, options, args): if options.outdated and options.uptodate: raise CommandError( "Options --outdated and --uptodate cannot be combined.") packages = get_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, include_editables=options.include_editable, ) # get_not_required must be called firstly in order to find and # filter out all dependencies correctly. Otherwise a package # can't be identified as requirement because some parent packages # could be filtered out before. if options.not_required: packages = self.get_not_required(packages, options) if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options) self.output_package_listing(packages, options) def get_outdated(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.parsed_version ] def get_uptodate(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.parsed_version ] def
(self, packages, options): dep_keys = set() for dist in packages: dep_keys.update(requirement.key for requirement in dist.requires()) return {pkg for pkg in packages if pkg.key not in dep_keys} def iter_packages_latest_infos(self, packages, options): index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.debug('Ignoring indexes: %s', ','.join(index_urls)) index_urls = [] with self._build_session(options) as session: finder = self._build_package_finder(options, index_urls, session) for dist in packages: typ = 'unknown' all_candidates = finder.find_all_candidates(dist.key) if not options.pre: # Remove prereleases all_candidates = [candidate for candidate in all_candidates if not candidate.version.is_prerelease] if not all_candidates: continue best_candidate = max(all_candidates, key=finder._candidate_sort_key) remote_version = best_candidate.version if best_candidate.location.is_wheel: typ = 'wheel' else: typ = 'sdist' # This is dirty but makes the rest of the code much cleaner dist.latest_version = remote_version dist.latest_filetype = typ yield dist def output_package_listing(self, packages, options): packages = sorted( packages, key=lambda dist: dist.project_name.lower(), ) if options.list_format == 'columns' and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == 'freeze': for dist in packages: if options.verbose >= 1: logger.info("%s==%s (%s)", dist.project_name, dist.version, dist.location) else: logger.info("%s==%s", dist.project_name, dist.version) elif options.list_format == 'json': logger.info(format_for_json(packages, options)) def output_package_listing_columns(self, data, header): # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join(map(lambda x: '-' * x, sizes))) for val in pkg_strings: logger.info(val) def tabulate(vals): # From pfmoore on GitHub: # https://github.com/pypa/pip/issues/3651#issuecomment-216932564 assert len(vals) > 0 sizes = [0] * max(len(x) for x in vals) for row in vals: sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)] result = [] for row in vals: display = " ".join([str(c).ljust(s) if c is not None else '' for s, c in zip_longest(sizes, row)]) result.append(display) return result, sizes def format_for_columns(pkgs, options): """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header def format_for_json(packages, options): data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.verbose >= 1: info['location'] = dist.location info['installer'] = get_installer(dist) if options.outdated: info['latest_version'] = six.text_type(dist.latest_version) info['latest_filetype'] = dist.latest_filetype data.append(info) return json.dumps(data)
get_not_required
identifier_name
search.js
Search = function(data, input, result) { this.data = data; this.$input = $(input); this.$result = $(result); this.$current = null; this.$view = this.$result.parent(); this.searcher = new Searcher(data.index); this.init(); }; Search.prototype = $.extend({}, Navigation, new function() { var suid = 1; this.init = function() { var _this = this; var observer = function(e) { switch(e.originalEvent.keyCode) { case 38: // Event.KEY_UP case 40: // Event.KEY_DOWN return; } _this.search(_this.$input[0].value); }; this.$input.keyup(observer); this.$input.click(observer); // mac's clear field this.searcher.ready(function(results, isLast) { _this.addResults(results, isLast); }); this.initNavigation(); this.setNavigationActive(false); }; this.search = function(value, selectFirstMatch) { value = jQuery.trim(value).toLowerCase(); if (value) { this.setNavigationActive(true); } else { this.setNavigationActive(false); } if (value == '')
else if (value != this.lastQuery) { this.lastQuery = value; this.$result.attr('aria-busy', 'true'); this.$result.attr('aria-expanded', 'true'); this.firstRun = true; this.searcher.find(value); } }; this.addResults = function(results, isLast) { var target = this.$result.get(0); if (this.firstRun && (results.length > 0 || isLast)) { this.$current = null; this.$result.empty(); } for (var i=0, l = results.length; i < l; i++) { var item = this.renderItem.call(this, results[i]); item.setAttribute('id', 'search-result-' + target.childElementCount); target.appendChild(item); } if (this.firstRun && results.length > 0) { this.firstRun = false; this.$current = $(target.firstChild); this.$current.addClass('search-selected'); } if (jQuery.browser.msie) this.$element[0].className += ''; if (isLast) this.$result.attr('aria-busy', 'false'); }; this.move = function(isDown) { if (!this.$current) return; var $next = this.$current[isDown ? 'next' : 'prev'](); if ($next.length) { this.$current.removeClass('search-selected'); $next.addClass('search-selected'); this.$input.attr('aria-activedescendant', $next.attr('id')); this.scrollIntoView($next[0], this.$view[0]); this.$current = $next; this.$input.val($next[0].firstChild.firstChild.text); this.$input.select(); } return true; }; this.hlt = function(html) { return this.escapeHTML(html). replace(/\u0001/g, '<em>'). replace(/\u0002/g, '</em>'); }; this.escapeHTML = function(html) { return html.replace(/[&<>]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); } });
{ this.lastQuery = value; this.$result.empty(); this.$result.attr('aria-expanded', 'false'); this.setNavigationActive(false); }
conditional_block
search.js
Search = function(data, input, result) { this.data = data; this.$input = $(input); this.$result = $(result); this.$current = null; this.$view = this.$result.parent(); this.searcher = new Searcher(data.index); this.init(); }; Search.prototype = $.extend({}, Navigation, new function() { var suid = 1; this.init = function() { var _this = this; var observer = function(e) { switch(e.originalEvent.keyCode) { case 38: // Event.KEY_UP case 40: // Event.KEY_DOWN return; } _this.search(_this.$input[0].value); }; this.$input.keyup(observer); this.$input.click(observer); // mac's clear field this.searcher.ready(function(results, isLast) { _this.addResults(results, isLast); }); this.initNavigation(); this.setNavigationActive(false); }; this.search = function(value, selectFirstMatch) { value = jQuery.trim(value).toLowerCase(); if (value) { this.setNavigationActive(true); } else { this.setNavigationActive(false); } if (value == '') { this.lastQuery = value; this.$result.empty(); this.$result.attr('aria-expanded', 'false'); this.setNavigationActive(false); } else if (value != this.lastQuery) { this.lastQuery = value; this.$result.attr('aria-busy', 'true'); this.$result.attr('aria-expanded', 'true'); this.firstRun = true; this.searcher.find(value); } }; this.addResults = function(results, isLast) { var target = this.$result.get(0); if (this.firstRun && (results.length > 0 || isLast)) { this.$current = null; this.$result.empty(); } for (var i=0, l = results.length; i < l; i++) { var item = this.renderItem.call(this, results[i]); item.setAttribute('id', 'search-result-' + target.childElementCount); target.appendChild(item); } if (this.firstRun && results.length > 0) { this.firstRun = false; this.$current = $(target.firstChild); this.$current.addClass('search-selected'); } if (jQuery.browser.msie) this.$element[0].className += ''; if (isLast) this.$result.attr('aria-busy', 'false'); }; this.move = function(isDown) { if (!this.$current) return; var $next = this.$current[isDown ? 'next' : 'prev'](); if ($next.length) { this.$current.removeClass('search-selected'); $next.addClass('search-selected'); this.$input.attr('aria-activedescendant', $next.attr('id')); this.scrollIntoView($next[0], this.$view[0]); this.$current = $next; this.$input.val($next[0].firstChild.firstChild.text); this.$input.select(); }
replace(/\u0001/g, '<em>'). replace(/\u0002/g, '</em>'); }; this.escapeHTML = function(html) { return html.replace(/[&<>]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); } });
return true; }; this.hlt = function(html) { return this.escapeHTML(html).
random_line_split
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expected', 'e', None, 'Speficy file containing expected lookup results'], ] class DNSLookup(dnst.DNSTest): name = "DNSLookupTest" version = 0.1 usageOptions = UsageOptions def setUp(self):
def verify_results(self, results): for result in results: if result not in self.expected_results: return False return True @defer.inlineCallbacks def test_dns_comparison(self): """ Performs A lookup on specified host and matches the results against a set of expected results. When not specified, host and expected results default to "torproject.org" and ['38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222']. """ for s in self.dns_servers: dnsServer = (s, 53) results = yield self.performALookup(self.hostname, dnsServer) if results: if self.verify_results(results): self.report['TestStatus'] = 'OK' else: self.report['TestStatus'] = 'FAILED' self.report['TestException'] = 'unexpected results' @defer.inlineCallbacks def test_control_results(self): """ Googles 8.8.8.8 server is queried, in order to generate control data. """ results = yield self.performALookup(self.hostname, ("8.8.8.8", 53) ) if results: self.report['control_results'] = results
self.expected_results = [] self.dns_servers = [] if self.input: self.hostname = self.input elif self.localOptions['target']: self.hostname = self.localOptions['target'] else: self.hostname = "torproject.org" if self.localOptions['expected']: with open (self.localOptions['expected']) as file: for line in file: self.expected_results.append(line.strip()) else: self.expected_results = [ '154.35.132.70', '38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222' ] self.report['expected_results'] = self.expected_results with open('/etc/resolv.conf') as f: for line in f: if line.startswith('nameserver'): self.dns_servers.append(line.split(' ')[1].strip()) self.report['dns_servers'] = self.dns_servers
identifier_body
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expected', 'e', None, 'Speficy file containing expected lookup results'], ] class DNSLookup(dnst.DNSTest): name = "DNSLookupTest" version = 0.1 usageOptions = UsageOptions def setUp(self): self.expected_results = [] self.dns_servers = [] if self.input: self.hostname = self.input elif self.localOptions['target']: self.hostname = self.localOptions['target'] else: self.hostname = "torproject.org" if self.localOptions['expected']: with open (self.localOptions['expected']) as file: for line in file: self.expected_results.append(line.strip()) else: self.expected_results = [ '154.35.132.70', '38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222' ] self.report['expected_results'] = self.expected_results with open('/etc/resolv.conf') as f: for line in f: if line.startswith('nameserver'): self.dns_servers.append(line.split(' ')[1].strip()) self.report['dns_servers'] = self.dns_servers def verify_results(self, results): for result in results: if result not in self.expected_results: return False return True @defer.inlineCallbacks def test_dns_comparison(self): """ Performs A lookup on specified host and matches the results against a set of expected results. When not specified, host and expected results default to "torproject.org" and ['38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222']. """ for s in self.dns_servers: dnsServer = (s, 53) results = yield self.performALookup(self.hostname, dnsServer) if results: if self.verify_results(results): self.report['TestStatus'] = 'OK' else: self.report['TestStatus'] = 'FAILED' self.report['TestException'] = 'unexpected results' @defer.inlineCallbacks def
(self): """ Googles 8.8.8.8 server is queried, in order to generate control data. """ results = yield self.performALookup(self.hostname, ("8.8.8.8", 53) ) if results: self.report['control_results'] = results
test_control_results
identifier_name
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expected', 'e', None, 'Speficy file containing expected lookup results'], ] class DNSLookup(dnst.DNSTest): name = "DNSLookupTest" version = 0.1 usageOptions = UsageOptions def setUp(self): self.expected_results = [] self.dns_servers = [] if self.input: self.hostname = self.input elif self.localOptions['target']: self.hostname = self.localOptions['target']
if self.localOptions['expected']: with open (self.localOptions['expected']) as file: for line in file: self.expected_results.append(line.strip()) else: self.expected_results = [ '154.35.132.70', '38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222' ] self.report['expected_results'] = self.expected_results with open('/etc/resolv.conf') as f: for line in f: if line.startswith('nameserver'): self.dns_servers.append(line.split(' ')[1].strip()) self.report['dns_servers'] = self.dns_servers def verify_results(self, results): for result in results: if result not in self.expected_results: return False return True @defer.inlineCallbacks def test_dns_comparison(self): """ Performs A lookup on specified host and matches the results against a set of expected results. When not specified, host and expected results default to "torproject.org" and ['38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222']. """ for s in self.dns_servers: dnsServer = (s, 53) results = yield self.performALookup(self.hostname, dnsServer) if results: if self.verify_results(results): self.report['TestStatus'] = 'OK' else: self.report['TestStatus'] = 'FAILED' self.report['TestException'] = 'unexpected results' @defer.inlineCallbacks def test_control_results(self): """ Googles 8.8.8.8 server is queried, in order to generate control data. """ results = yield self.performALookup(self.hostname, ("8.8.8.8", 53) ) if results: self.report['control_results'] = results
else: self.hostname = "torproject.org"
random_line_split
dnscompare.py
# -*- coding: utf-8 -*- from ooni.utils import log from twisted.python import usage from twisted.internet import defer from ooni.templates import dnst class UsageOptions(usage.Options): optParameters = [ ['target', 't', None, 'Specify a single hostname to query.'], ['expected', 'e', None, 'Speficy file containing expected lookup results'], ] class DNSLookup(dnst.DNSTest): name = "DNSLookupTest" version = 0.1 usageOptions = UsageOptions def setUp(self): self.expected_results = [] self.dns_servers = [] if self.input: self.hostname = self.input elif self.localOptions['target']: self.hostname = self.localOptions['target'] else: self.hostname = "torproject.org" if self.localOptions['expected']: with open (self.localOptions['expected']) as file: for line in file: self.expected_results.append(line.strip()) else: self.expected_results = [ '154.35.132.70', '38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222' ] self.report['expected_results'] = self.expected_results with open('/etc/resolv.conf') as f: for line in f: if line.startswith('nameserver'): self.dns_servers.append(line.split(' ')[1].strip()) self.report['dns_servers'] = self.dns_servers def verify_results(self, results): for result in results: if result not in self.expected_results:
return True @defer.inlineCallbacks def test_dns_comparison(self): """ Performs A lookup on specified host and matches the results against a set of expected results. When not specified, host and expected results default to "torproject.org" and ['38.229.72.14', '38.229.72.16', '82.195.75.101', '86.59.30.40', '93.95.227.222']. """ for s in self.dns_servers: dnsServer = (s, 53) results = yield self.performALookup(self.hostname, dnsServer) if results: if self.verify_results(results): self.report['TestStatus'] = 'OK' else: self.report['TestStatus'] = 'FAILED' self.report['TestException'] = 'unexpected results' @defer.inlineCallbacks def test_control_results(self): """ Googles 8.8.8.8 server is queried, in order to generate control data. """ results = yield self.performALookup(self.hostname, ("8.8.8.8", 53) ) if results: self.report['control_results'] = results
return False
conditional_block
gcccuda.py
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for a GCC+CUDA compiler toolchain. :author: Kenneth Hoste (Ghent University) """ from easybuild.toolchains.compiler.cuda import Cuda from easybuild.toolchains.gcc import GccToolchain class GccCUDA(GccToolchain, Cuda):
"""Compiler toolchain with GCC and CUDA.""" NAME = 'gcccuda' COMPILER_MODULE_NAME = ['GCC', 'CUDA'] SUBTOOLCHAIN = GccToolchain.NAME
identifier_body
gcccuda.py
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for a GCC+CUDA compiler toolchain. :author: Kenneth Hoste (Ghent University) """ from easybuild.toolchains.compiler.cuda import Cuda from easybuild.toolchains.gcc import GccToolchain class
(GccToolchain, Cuda): """Compiler toolchain with GCC and CUDA.""" NAME = 'gcccuda' COMPILER_MODULE_NAME = ['GCC', 'CUDA'] SUBTOOLCHAIN = GccToolchain.NAME
GccCUDA
identifier_name
gcccuda.py
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for a GCC+CUDA compiler toolchain. :author: Kenneth Hoste (Ghent University) """ from easybuild.toolchains.compiler.cuda import Cuda from easybuild.toolchains.gcc import GccToolchain class GccCUDA(GccToolchain, Cuda): """Compiler toolchain with GCC and CUDA."""
NAME = 'gcccuda' COMPILER_MODULE_NAME = ['GCC', 'CUDA'] SUBTOOLCHAIN = GccToolchain.NAME
random_line_split
platform.d.ts
/* tslint:disable:class-name */ /** * Contains all kinds of information about the device, its operating system and software. */ declare module "platform" { /* * Enum holding platform names. */ export module platformNames { export var android: string; export var ios: string; } /* * An object containing device specific information. */ export class device { /** * Gets the manufacturer of the device. * For example: "Apple" or "HTC" or "Samsung". */ static manufacturer: string; /** * Gets the model of the device. * For example: "Nexus 5" or "iPhone". */ static model: string; /** * Gets the model of the device. * For example: "Android" or "iOS". */ static os: string; /** * Gets the OS version. * For example: 4.4.4(android), 8.1(ios) */ static osVersion: string; /** * Gets the OS version. * For example: 19(android), 8.1(ios). */ static sdkVersion: string; /** * Gets the type current device. * Available values: "phone", "tablet". */ static deviceType: string; /** * Gets the uuid */ static uuid: string; /** * Gets the preferred language. For example "en" or "en_US" */ static language: string; } /** * An object containing screen information. */ export interface ScreenMetrics { /** * Gets the absolute width of the screen in pixels. */ widthPixels: number; /** * Gets the absolute height of the screen in pixels. */ heightPixels: number; /** * Gets the absolute width of the screen in density independent pixels. */ widthDIPs: number; /** * Gets the absolute height of the screen in density independent pixels. */ heightDIPs: number;
* The logical density of the display. This is a scaling factor for the Density Independent Pixel unit. */ scale: number; } /** * An object describing general information about a display. */ export class screen { /** * Gets information about the main screen of the current device. */ static mainScreen: ScreenMetrics; } }
/**
random_line_split
platform.d.ts
/* tslint:disable:class-name */ /** * Contains all kinds of information about the device, its operating system and software. */ declare module "platform" { /* * Enum holding platform names. */ export module platformNames { export var android: string; export var ios: string; } /* * An object containing device specific information. */ export class
{ /** * Gets the manufacturer of the device. * For example: "Apple" or "HTC" or "Samsung". */ static manufacturer: string; /** * Gets the model of the device. * For example: "Nexus 5" or "iPhone". */ static model: string; /** * Gets the model of the device. * For example: "Android" or "iOS". */ static os: string; /** * Gets the OS version. * For example: 4.4.4(android), 8.1(ios) */ static osVersion: string; /** * Gets the OS version. * For example: 19(android), 8.1(ios). */ static sdkVersion: string; /** * Gets the type current device. * Available values: "phone", "tablet". */ static deviceType: string; /** * Gets the uuid */ static uuid: string; /** * Gets the preferred language. For example "en" or "en_US" */ static language: string; } /** * An object containing screen information. */ export interface ScreenMetrics { /** * Gets the absolute width of the screen in pixels. */ widthPixels: number; /** * Gets the absolute height of the screen in pixels. */ heightPixels: number; /** * Gets the absolute width of the screen in density independent pixels. */ widthDIPs: number; /** * Gets the absolute height of the screen in density independent pixels. */ heightDIPs: number; /** * The logical density of the display. This is a scaling factor for the Density Independent Pixel unit. */ scale: number; } /** * An object describing general information about a display. */ export class screen { /** * Gets information about the main screen of the current device. */ static mainScreen: ScreenMetrics; } }
device
identifier_name
player-name-check.js
'use strict'; /** * Confirm new player name */ module.exports = (srcPath) => { const EventUtil = require(srcPath + 'EventUtil'); return { event: state => (socket, args) => { const say = EventUtil.genSay(socket); const write = EventUtil.genWrite(socket); write(`<bold>${args.name} doesn't exist, would you like to create it?</bold> <cyan>[y/n]</cyan> `); socket.once('data', confirmation => { say(''); confirmation = confirmation.toString().trim().toLowerCase(); if (!/[yn]/.test(confirmation)) {
if (confirmation === 'n') { say(`Let's try again...`); return socket.emit('create-player', socket, args); } return socket.emit('finish-player', socket, args); }); } }; };
return socket.emit('player-name-check', socket, args); }
random_line_split
player-name-check.js
'use strict'; /** * Confirm new player name */ module.exports = (srcPath) => { const EventUtil = require(srcPath + 'EventUtil'); return { event: state => (socket, args) => { const say = EventUtil.genSay(socket); const write = EventUtil.genWrite(socket); write(`<bold>${args.name} doesn't exist, would you like to create it?</bold> <cyan>[y/n]</cyan> `); socket.once('data', confirmation => { say(''); confirmation = confirmation.toString().trim().toLowerCase(); if (!/[yn]/.test(confirmation))
if (confirmation === 'n') { say(`Let's try again...`); return socket.emit('create-player', socket, args); } return socket.emit('finish-player', socket, args); }); } }; };
{ return socket.emit('player-name-check', socket, args); }
conditional_block
test_qcut.py
import os import numpy as np import pytest from pandas import ( Categorical, DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pandas.core.algorithms import quantile import pandas.util.testing as tm from pandas.tseries.offsets import Day, Nano def test_qcut(): arr = np.random.randn(1000) # We store the bins as Index that have been # rounded to comparisons are a bit tricky. labels, bins = qcut(arr, 4, retbins=True) ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) result = labels.categories.left.values assert np.allclose(result, ex_bins[:-1], atol=1e-2) result = labels.categories.right.values assert np.allclose(result, ex_bins[1:], atol=1e-2) ex_levels = cut(arr, ex_bins, include_lowest=True) tm.assert_categorical_equal(labels, ex_levels) def test_qcut_bounds(): arr = np.random.randn(1000) factor = qcut(arr, 10, labels=False) assert len(np.unique(factor)) == 10 def test_qcut_specify_quantiles(): arr = np.random.randn(100) factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0]) expected = qcut(arr, 4) tm.assert_categorical_equal(factor, expected) def test_qcut_all_bins_same(): with pytest.raises(ValueError, match="edges.*unique"): qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3) def test_qcut_include_lowest(): values = np.arange(10) ii = qcut(values, 4) ex_levels = IntervalIndex( [ Interval(-0.001, 2.25), Interval(2.25, 4.5), Interval(4.5, 6.75), Interval(6.75, 9), ] ) tm.assert_index_equal(ii.categories, ex_levels) def test_qcut_nas(): arr = np.random.randn(100) arr[:20] = np.nan result = qcut(arr, 4) assert isna(result[:20]).all() def test_qcut_index(): result = qcut([0, 2], 2) intervals = [Interval(-0.001, 1), Interval(1, 2)] expected = Categorical(intervals, ordered=True) tm.assert_categorical_equal(result, expected) def test_qcut_binning_issues(datapath): # see gh-1978, gh-1979 cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv")) arr = np.loadtxt(cut_file) result = qcut(arr, 20) starts = [] ends = [] for lev in np.unique(result): s = lev.left e = lev.right assert s != e starts.append(float(s)) ends.append(float(e)) for (sp, sn), (ep, en) in zip( zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:]) ): assert sp < sn assert ep < en assert ep <= sn def test_qcut_return_intervals(): ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8]) res = qcut(ser, [0, 0.333, 0.666, 1]) exp_levels = np.array( [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)] ) exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True)) tm.assert_series_equal(res, exp) @pytest.mark.parametrize( "kwargs,msg", [ (dict(duplicates="drop"), None), (dict(), "Bin edges must be unique"), (dict(duplicates="raise"), "Bin edges must be unique"), (dict(duplicates="foo"), "invalid value for 'duplicates' parameter"), ], ) def test_qcut_duplicates_bin(kwargs, msg): # see gh-7751 values = [0, 0, 0, 0, 1, 2, 3] if msg is not None: with pytest.raises(ValueError, match=msg): qcut(values, 3, **kwargs) else:
@pytest.mark.parametrize( "data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)] ) @pytest.mark.parametrize("length", [1, 2]) @pytest.mark.parametrize("labels", [None, False]) def test_single_quantile(data, start, end, length, labels): # see gh-15431 ser = Series([data] * length) result = qcut(ser, 1, labels=labels) if labels is None: intervals = IntervalIndex([Interval(start, end)] * length, closed="right") expected = Series(intervals).astype(CDT(ordered=True)) else: expected = Series([0] * length) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "ser", [ Series(DatetimeIndex(["20180101", NaT, "20180103"])), Series(TimedeltaIndex(["0 days", NaT, "2 days"])), ], ids=lambda x: str(x.dtype), ) def test_qcut_nat(ser): # see gh-19768 intervals = IntervalIndex.from_tuples( [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])] ) expected = Series(Categorical(intervals, ordered=True)) result = qcut(ser, 2) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)]) def test_datetime_tz_qcut(bins): # see gh-19872 tz = "US/Eastern" ser = Series(date_range("20130101", periods=3, tz=tz)) result = qcut(ser, bins) expected = Series( IntervalIndex( [ Interval( Timestamp("2012-12-31 23:59:59.999999999", tz=tz), Timestamp("2013-01-01 16:00:00", tz=tz), ), Interval( Timestamp("2013-01-01 16:00:00", tz=tz), Timestamp("2013-01-02 08:00:00", tz=tz), ), Interval( Timestamp("2013-01-02 08:00:00", tz=tz), Timestamp("2013-01-03 00:00:00", tz=tz), ), ] ) ).astype(CDT(ordered=True)) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "arg,expected_bins", [ [ timedelta_range("1day", periods=3), TimedeltaIndex(["1 days", "2 days", "3 days"]), ], [ date_range("20180101", periods=3), DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]), ], ], ) def test_date_like_qcut_bins(arg, expected_bins): # see gh-19891 ser = Series(arg) result, result_bins = qcut(ser, 2, retbins=True) tm.assert_index_equal(result_bins, expected_bins)
result = qcut(values, 3, **kwargs) expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)]) tm.assert_index_equal(result.categories, expected)
conditional_block
test_qcut.py
import os import numpy as np import pytest from pandas import ( Categorical, DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pandas.core.algorithms import quantile import pandas.util.testing as tm from pandas.tseries.offsets import Day, Nano def test_qcut(): arr = np.random.randn(1000) # We store the bins as Index that have been # rounded to comparisons are a bit tricky. labels, bins = qcut(arr, 4, retbins=True) ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) result = labels.categories.left.values assert np.allclose(result, ex_bins[:-1], atol=1e-2) result = labels.categories.right.values assert np.allclose(result, ex_bins[1:], atol=1e-2) ex_levels = cut(arr, ex_bins, include_lowest=True) tm.assert_categorical_equal(labels, ex_levels) def test_qcut_bounds(): arr = np.random.randn(1000) factor = qcut(arr, 10, labels=False) assert len(np.unique(factor)) == 10 def test_qcut_specify_quantiles(): arr = np.random.randn(100) factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0]) expected = qcut(arr, 4) tm.assert_categorical_equal(factor, expected) def test_qcut_all_bins_same(): with pytest.raises(ValueError, match="edges.*unique"): qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3) def test_qcut_include_lowest():
def test_qcut_nas(): arr = np.random.randn(100) arr[:20] = np.nan result = qcut(arr, 4) assert isna(result[:20]).all() def test_qcut_index(): result = qcut([0, 2], 2) intervals = [Interval(-0.001, 1), Interval(1, 2)] expected = Categorical(intervals, ordered=True) tm.assert_categorical_equal(result, expected) def test_qcut_binning_issues(datapath): # see gh-1978, gh-1979 cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv")) arr = np.loadtxt(cut_file) result = qcut(arr, 20) starts = [] ends = [] for lev in np.unique(result): s = lev.left e = lev.right assert s != e starts.append(float(s)) ends.append(float(e)) for (sp, sn), (ep, en) in zip( zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:]) ): assert sp < sn assert ep < en assert ep <= sn def test_qcut_return_intervals(): ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8]) res = qcut(ser, [0, 0.333, 0.666, 1]) exp_levels = np.array( [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)] ) exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True)) tm.assert_series_equal(res, exp) @pytest.mark.parametrize( "kwargs,msg", [ (dict(duplicates="drop"), None), (dict(), "Bin edges must be unique"), (dict(duplicates="raise"), "Bin edges must be unique"), (dict(duplicates="foo"), "invalid value for 'duplicates' parameter"), ], ) def test_qcut_duplicates_bin(kwargs, msg): # see gh-7751 values = [0, 0, 0, 0, 1, 2, 3] if msg is not None: with pytest.raises(ValueError, match=msg): qcut(values, 3, **kwargs) else: result = qcut(values, 3, **kwargs) expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)]) tm.assert_index_equal(result.categories, expected) @pytest.mark.parametrize( "data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)] ) @pytest.mark.parametrize("length", [1, 2]) @pytest.mark.parametrize("labels", [None, False]) def test_single_quantile(data, start, end, length, labels): # see gh-15431 ser = Series([data] * length) result = qcut(ser, 1, labels=labels) if labels is None: intervals = IntervalIndex([Interval(start, end)] * length, closed="right") expected = Series(intervals).astype(CDT(ordered=True)) else: expected = Series([0] * length) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "ser", [ Series(DatetimeIndex(["20180101", NaT, "20180103"])), Series(TimedeltaIndex(["0 days", NaT, "2 days"])), ], ids=lambda x: str(x.dtype), ) def test_qcut_nat(ser): # see gh-19768 intervals = IntervalIndex.from_tuples( [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])] ) expected = Series(Categorical(intervals, ordered=True)) result = qcut(ser, 2) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)]) def test_datetime_tz_qcut(bins): # see gh-19872 tz = "US/Eastern" ser = Series(date_range("20130101", periods=3, tz=tz)) result = qcut(ser, bins) expected = Series( IntervalIndex( [ Interval( Timestamp("2012-12-31 23:59:59.999999999", tz=tz), Timestamp("2013-01-01 16:00:00", tz=tz), ), Interval( Timestamp("2013-01-01 16:00:00", tz=tz), Timestamp("2013-01-02 08:00:00", tz=tz), ), Interval( Timestamp("2013-01-02 08:00:00", tz=tz), Timestamp("2013-01-03 00:00:00", tz=tz), ), ] ) ).astype(CDT(ordered=True)) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "arg,expected_bins", [ [ timedelta_range("1day", periods=3), TimedeltaIndex(["1 days", "2 days", "3 days"]), ], [ date_range("20180101", periods=3), DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]), ], ], ) def test_date_like_qcut_bins(arg, expected_bins): # see gh-19891 ser = Series(arg) result, result_bins = qcut(ser, 2, retbins=True) tm.assert_index_equal(result_bins, expected_bins)
values = np.arange(10) ii = qcut(values, 4) ex_levels = IntervalIndex( [ Interval(-0.001, 2.25), Interval(2.25, 4.5), Interval(4.5, 6.75), Interval(6.75, 9), ] ) tm.assert_index_equal(ii.categories, ex_levels)
identifier_body
test_qcut.py
import os import numpy as np import pytest from pandas import (
DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pandas.core.algorithms import quantile import pandas.util.testing as tm from pandas.tseries.offsets import Day, Nano def test_qcut(): arr = np.random.randn(1000) # We store the bins as Index that have been # rounded to comparisons are a bit tricky. labels, bins = qcut(arr, 4, retbins=True) ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) result = labels.categories.left.values assert np.allclose(result, ex_bins[:-1], atol=1e-2) result = labels.categories.right.values assert np.allclose(result, ex_bins[1:], atol=1e-2) ex_levels = cut(arr, ex_bins, include_lowest=True) tm.assert_categorical_equal(labels, ex_levels) def test_qcut_bounds(): arr = np.random.randn(1000) factor = qcut(arr, 10, labels=False) assert len(np.unique(factor)) == 10 def test_qcut_specify_quantiles(): arr = np.random.randn(100) factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0]) expected = qcut(arr, 4) tm.assert_categorical_equal(factor, expected) def test_qcut_all_bins_same(): with pytest.raises(ValueError, match="edges.*unique"): qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3) def test_qcut_include_lowest(): values = np.arange(10) ii = qcut(values, 4) ex_levels = IntervalIndex( [ Interval(-0.001, 2.25), Interval(2.25, 4.5), Interval(4.5, 6.75), Interval(6.75, 9), ] ) tm.assert_index_equal(ii.categories, ex_levels) def test_qcut_nas(): arr = np.random.randn(100) arr[:20] = np.nan result = qcut(arr, 4) assert isna(result[:20]).all() def test_qcut_index(): result = qcut([0, 2], 2) intervals = [Interval(-0.001, 1), Interval(1, 2)] expected = Categorical(intervals, ordered=True) tm.assert_categorical_equal(result, expected) def test_qcut_binning_issues(datapath): # see gh-1978, gh-1979 cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv")) arr = np.loadtxt(cut_file) result = qcut(arr, 20) starts = [] ends = [] for lev in np.unique(result): s = lev.left e = lev.right assert s != e starts.append(float(s)) ends.append(float(e)) for (sp, sn), (ep, en) in zip( zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:]) ): assert sp < sn assert ep < en assert ep <= sn def test_qcut_return_intervals(): ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8]) res = qcut(ser, [0, 0.333, 0.666, 1]) exp_levels = np.array( [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)] ) exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True)) tm.assert_series_equal(res, exp) @pytest.mark.parametrize( "kwargs,msg", [ (dict(duplicates="drop"), None), (dict(), "Bin edges must be unique"), (dict(duplicates="raise"), "Bin edges must be unique"), (dict(duplicates="foo"), "invalid value for 'duplicates' parameter"), ], ) def test_qcut_duplicates_bin(kwargs, msg): # see gh-7751 values = [0, 0, 0, 0, 1, 2, 3] if msg is not None: with pytest.raises(ValueError, match=msg): qcut(values, 3, **kwargs) else: result = qcut(values, 3, **kwargs) expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)]) tm.assert_index_equal(result.categories, expected) @pytest.mark.parametrize( "data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)] ) @pytest.mark.parametrize("length", [1, 2]) @pytest.mark.parametrize("labels", [None, False]) def test_single_quantile(data, start, end, length, labels): # see gh-15431 ser = Series([data] * length) result = qcut(ser, 1, labels=labels) if labels is None: intervals = IntervalIndex([Interval(start, end)] * length, closed="right") expected = Series(intervals).astype(CDT(ordered=True)) else: expected = Series([0] * length) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "ser", [ Series(DatetimeIndex(["20180101", NaT, "20180103"])), Series(TimedeltaIndex(["0 days", NaT, "2 days"])), ], ids=lambda x: str(x.dtype), ) def test_qcut_nat(ser): # see gh-19768 intervals = IntervalIndex.from_tuples( [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])] ) expected = Series(Categorical(intervals, ordered=True)) result = qcut(ser, 2) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)]) def test_datetime_tz_qcut(bins): # see gh-19872 tz = "US/Eastern" ser = Series(date_range("20130101", periods=3, tz=tz)) result = qcut(ser, bins) expected = Series( IntervalIndex( [ Interval( Timestamp("2012-12-31 23:59:59.999999999", tz=tz), Timestamp("2013-01-01 16:00:00", tz=tz), ), Interval( Timestamp("2013-01-01 16:00:00", tz=tz), Timestamp("2013-01-02 08:00:00", tz=tz), ), Interval( Timestamp("2013-01-02 08:00:00", tz=tz), Timestamp("2013-01-03 00:00:00", tz=tz), ), ] ) ).astype(CDT(ordered=True)) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "arg,expected_bins", [ [ timedelta_range("1day", periods=3), TimedeltaIndex(["1 days", "2 days", "3 days"]), ], [ date_range("20180101", periods=3), DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]), ], ], ) def test_date_like_qcut_bins(arg, expected_bins): # see gh-19891 ser = Series(arg) result, result_bins = qcut(ser, 2, retbins=True) tm.assert_index_equal(result_bins, expected_bins)
Categorical,
random_line_split
test_qcut.py
import os import numpy as np import pytest from pandas import ( Categorical, DatetimeIndex, Interval, IntervalIndex, NaT, Series, TimedeltaIndex, Timestamp, cut, date_range, isna, qcut, timedelta_range, ) from pandas.api.types import CategoricalDtype as CDT from pandas.core.algorithms import quantile import pandas.util.testing as tm from pandas.tseries.offsets import Day, Nano def test_qcut(): arr = np.random.randn(1000) # We store the bins as Index that have been # rounded to comparisons are a bit tricky. labels, bins = qcut(arr, 4, retbins=True) ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0]) result = labels.categories.left.values assert np.allclose(result, ex_bins[:-1], atol=1e-2) result = labels.categories.right.values assert np.allclose(result, ex_bins[1:], atol=1e-2) ex_levels = cut(arr, ex_bins, include_lowest=True) tm.assert_categorical_equal(labels, ex_levels) def test_qcut_bounds(): arr = np.random.randn(1000) factor = qcut(arr, 10, labels=False) assert len(np.unique(factor)) == 10 def test_qcut_specify_quantiles(): arr = np.random.randn(100) factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0]) expected = qcut(arr, 4) tm.assert_categorical_equal(factor, expected) def test_qcut_all_bins_same(): with pytest.raises(ValueError, match="edges.*unique"): qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3) def test_qcut_include_lowest(): values = np.arange(10) ii = qcut(values, 4) ex_levels = IntervalIndex( [ Interval(-0.001, 2.25), Interval(2.25, 4.5), Interval(4.5, 6.75), Interval(6.75, 9), ] ) tm.assert_index_equal(ii.categories, ex_levels) def test_qcut_nas(): arr = np.random.randn(100) arr[:20] = np.nan result = qcut(arr, 4) assert isna(result[:20]).all() def test_qcut_index(): result = qcut([0, 2], 2) intervals = [Interval(-0.001, 1), Interval(1, 2)] expected = Categorical(intervals, ordered=True) tm.assert_categorical_equal(result, expected) def
(datapath): # see gh-1978, gh-1979 cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv")) arr = np.loadtxt(cut_file) result = qcut(arr, 20) starts = [] ends = [] for lev in np.unique(result): s = lev.left e = lev.right assert s != e starts.append(float(s)) ends.append(float(e)) for (sp, sn), (ep, en) in zip( zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:]) ): assert sp < sn assert ep < en assert ep <= sn def test_qcut_return_intervals(): ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8]) res = qcut(ser, [0, 0.333, 0.666, 1]) exp_levels = np.array( [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)] ) exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True)) tm.assert_series_equal(res, exp) @pytest.mark.parametrize( "kwargs,msg", [ (dict(duplicates="drop"), None), (dict(), "Bin edges must be unique"), (dict(duplicates="raise"), "Bin edges must be unique"), (dict(duplicates="foo"), "invalid value for 'duplicates' parameter"), ], ) def test_qcut_duplicates_bin(kwargs, msg): # see gh-7751 values = [0, 0, 0, 0, 1, 2, 3] if msg is not None: with pytest.raises(ValueError, match=msg): qcut(values, 3, **kwargs) else: result = qcut(values, 3, **kwargs) expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)]) tm.assert_index_equal(result.categories, expected) @pytest.mark.parametrize( "data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)] ) @pytest.mark.parametrize("length", [1, 2]) @pytest.mark.parametrize("labels", [None, False]) def test_single_quantile(data, start, end, length, labels): # see gh-15431 ser = Series([data] * length) result = qcut(ser, 1, labels=labels) if labels is None: intervals = IntervalIndex([Interval(start, end)] * length, closed="right") expected = Series(intervals).astype(CDT(ordered=True)) else: expected = Series([0] * length) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "ser", [ Series(DatetimeIndex(["20180101", NaT, "20180103"])), Series(TimedeltaIndex(["0 days", NaT, "2 days"])), ], ids=lambda x: str(x.dtype), ) def test_qcut_nat(ser): # see gh-19768 intervals = IntervalIndex.from_tuples( [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])] ) expected = Series(Categorical(intervals, ordered=True)) result = qcut(ser, 2) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)]) def test_datetime_tz_qcut(bins): # see gh-19872 tz = "US/Eastern" ser = Series(date_range("20130101", periods=3, tz=tz)) result = qcut(ser, bins) expected = Series( IntervalIndex( [ Interval( Timestamp("2012-12-31 23:59:59.999999999", tz=tz), Timestamp("2013-01-01 16:00:00", tz=tz), ), Interval( Timestamp("2013-01-01 16:00:00", tz=tz), Timestamp("2013-01-02 08:00:00", tz=tz), ), Interval( Timestamp("2013-01-02 08:00:00", tz=tz), Timestamp("2013-01-03 00:00:00", tz=tz), ), ] ) ).astype(CDT(ordered=True)) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "arg,expected_bins", [ [ timedelta_range("1day", periods=3), TimedeltaIndex(["1 days", "2 days", "3 days"]), ], [ date_range("20180101", periods=3), DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]), ], ], ) def test_date_like_qcut_bins(arg, expected_bins): # see gh-19891 ser = Series(arg) result, result_bins = qcut(ser, 2, retbins=True) tm.assert_index_equal(result_bins, expected_bins)
test_qcut_binning_issues
identifier_name
lint.py
#!/usr/bin/env python # # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs Android's lint tool.""" import argparse import os import re import sys import traceback from xml.dom import minidom from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _OnStaleMd5(changes, lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, sources, jar_path, cache_dir, android_sdk_version, resource_dir=None, classpath=None, can_fail_build=False, silent=False): def _RelativizePath(path): """Returns relative path to top-level src dir. Args: path: A path relative to cwd. """ return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not config_path or not processed_config_path: return if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') if not silent: print >> sys.stderr for issue in issues: issue_id = issue.attributes['id'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error = '%s:%s %s: %s [warning]' % (path, line, message, issue_id) else: # Issues in class files don't have a line number. error = '%s %s: %s [warning]' % (path, message, issue_id) print >> sys.stderr, error.encode('utf-8') for attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line.encode('utf-8') return len(issues) # Need to include all sources when a resource_dir is set so that resources are # not marked as unused. # TODO(agrieve): Figure out how IDEs do incremental linting. if not resource_dir and changes.AddedOrModifiedOnly(): changed_paths = set(changes.IterChangedPaths()) sources = [s for s in sources if s in changed_paths] with build_utils.TempDir() as temp_dir: _ProcessConfigFile() cmd = [ _RelativizePath(lint_path), '-Werror', '--exitcode', '--showall', '--xml', _RelativizePath(result_path), ] if jar_path: # --classpath is just for .class files for this one target. cmd.extend(['--classpath', _RelativizePath(jar_path)]) if processed_config_path: cmd.extend(['--config', _RelativizePath(processed_config_path)]) if resource_dir: cmd.extend(['--resources', _RelativizePath(resource_dir)]) if classpath: # --libraries is the classpath (excluding active target). cp = ':'.join(_RelativizePath(p) for p in classpath) cmd.extend(['--libraries', cp]) # There may be multiple source files with the same basename (but in # different directories). It is difficult to determine what part of the path # corresponds to the java package, and so instead just link the source files # into temporary directories (creating a new one whenever there is a name # conflict). src_dirs = [] def NewSourceDir(): new_dir = os.path.join(temp_dir, str(len(src_dirs))) os.mkdir(new_dir) src_dirs.append(new_dir) return new_dir def PathInDir(d, src): return os.path.join(d, os.path.basename(src)) for src in sources: src_dir = None for d in src_dirs: if not os.path.exists(PathInDir(d, src)): src_dir = d break if not src_dir: src_dir = NewSourceDir() cmd.extend(['--sources', _RelativizePath(src_dir)]) os.symlink(os.path.abspath(src), PathInDir(src_dir, src)) project_dir = NewSourceDir() if android_sdk_version: # Create dummy project.properies file in a temporary "project" directory. # It is the only way to add Android SDK to the Lint's classpath. Proper # classpath is necessary for most source-level checks. with open(os.path.join(project_dir, 'project.properties'), 'w') \ as propfile: print >> propfile, 'target=android-{}'.format(android_sdk_version) # Put the manifest in a temporary directory in order to avoid lint detecting # sibling res/ and src/ directories (which should be pass explicitly if they # are to be included). if manifest_path: os.symlink(os.path.abspath(manifest_path), PathInDir(project_dir, manifest_path)) cmd.append(project_dir) if os.path.exists(result_path): os.remove(result_path) env = {} stderr_filter = None if cache_dir: env['_JAVA_OPTIONS'] = '-Duser.home=%s' % _RelativizePath(cache_dir) # When _JAVA_OPTIONS is set, java prints to stderr: # Picked up _JAVA_OPTIONS: ... # # We drop all lines that contain _JAVA_OPTIONS from the output stderr_filter = lambda l: re.sub(r'.*_JAVA_OPTIONS.*\n?', '', l) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT, env=env or None,
if not os.path.exists(result_path): raise # Sometimes produces empty (almost) files: if os.path.getsize(result_path) < 10: if can_fail_build: raise elif not silent: traceback.print_exc() return # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() if not can_fail_build: return if can_fail_build and not silent: traceback.print_exc() # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() raise _ProcessResultFile() msg = ('\nLint found %d new issues.\n' ' - For full explanation refer to %s\n' % (num_issues, _RelativizePath(result_path))) if config_path: msg += (' - Wanna suppress these issues?\n' ' 1. Read comment in %s\n' ' 2. Run "python %s %s"\n' % (_RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) if not silent: print >> sys.stderr, msg if can_fail_build: raise Exception('Lint failed.') def main(): parser = argparse.ArgumentParser() build_utils.AddDepfileOption(parser) parser.add_argument('--lint-path', required=True, help='Path to lint executable.') parser.add_argument('--product-dir', required=True, help='Path to product dir.') parser.add_argument('--result-path', required=True, help='Path to XML lint result file.') parser.add_argument('--cache-dir', required=True, help='Path to the directory in which the android cache ' 'directory tree should be stored.') parser.add_argument('--platform-xml-path', required=True, help='Path to api-platforms.xml') parser.add_argument('--android-sdk-version', help='Version (API level) of the Android SDK used for ' 'building.') parser.add_argument('--create-cache', action='store_true', help='Mark the lint cache file as an output rather than ' 'an input.') parser.add_argument('--can-fail-build', action='store_true', help='If set, script will exit with nonzero exit status' ' if lint errors are present') parser.add_argument('--config-path', help='Path to lint suppressions file.') parser.add_argument('--enable', action='store_true', help='Run lint instead of just touching stamp.') parser.add_argument('--jar-path', help='Jar file containing class files.') parser.add_argument('--java-files', help='Paths to java files.') parser.add_argument('--manifest-path', help='Path to AndroidManifest.xml') parser.add_argument('--classpath', default=[], action='append', help='GYP-list of classpath .jar files') parser.add_argument('--processed-config-path', help='Path to processed lint suppressions file.') parser.add_argument('--resource-dir', help='Path to resource dir.') parser.add_argument('--silent', action='store_true', help='If set, script will not log anything.') parser.add_argument('--src-dirs', help='Directories containing java files.') parser.add_argument('--stamp', help='Path to touch on success.') args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:])) if args.enable: sources = [] if args.src_dirs: src_dirs = build_utils.ParseGypList(args.src_dirs) sources = build_utils.FindInDirectories(src_dirs, '*.java') elif args.java_files: sources = build_utils.ParseGypList(args.java_files) if args.config_path and not args.processed_config_path: parser.error('--config-path specified without --processed-config-path') elif args.processed_config_path and not args.config_path: parser.error('--processed-config-path specified without --config-path') input_paths = [ args.lint_path, args.platform_xml_path, ] if args.config_path: input_paths.append(args.config_path) if args.jar_path: input_paths.append(args.jar_path) if args.manifest_path: input_paths.append(args.manifest_path) if args.resource_dir: input_paths.extend(build_utils.FindInDirectory(args.resource_dir, '*')) if sources: input_paths.extend(sources) classpath = [] for gyp_list in args.classpath: classpath.extend(build_utils.ParseGypList(gyp_list)) input_paths.extend(classpath) input_strings = [] if args.android_sdk_version: input_strings.append(args.android_sdk_version) if args.processed_config_path: input_strings.append(args.processed_config_path) output_paths = [ args.result_path ] build_utils.CallAndWriteDepfileIfStale( lambda changes: _OnStaleMd5(changes, args.lint_path, args.config_path, args.processed_config_path, args.manifest_path, args.result_path, args.product_dir, sources, args.jar_path, args.cache_dir, args.android_sdk_version, resource_dir=args.resource_dir, classpath=classpath, can_fail_build=args.can_fail_build, silent=args.silent), args, input_paths=input_paths, input_strings=input_strings, output_paths=output_paths, pass_changes=True, depfile_deps=classpath) if __name__ == '__main__': sys.exit(main())
stderr_filter=stderr_filter) except build_utils.CalledProcessError: # There is a problem with lint usage
random_line_split
lint.py
#!/usr/bin/env python # # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs Android's lint tool.""" import argparse import os import re import sys import traceback from xml.dom import minidom from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _OnStaleMd5(changes, lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, sources, jar_path, cache_dir, android_sdk_version, resource_dir=None, classpath=None, can_fail_build=False, silent=False): def _RelativizePath(path): """Returns relative path to top-level src dir. Args: path: A path relative to cwd. """ return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def
(): if not config_path or not processed_config_path: return if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') if not silent: print >> sys.stderr for issue in issues: issue_id = issue.attributes['id'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error = '%s:%s %s: %s [warning]' % (path, line, message, issue_id) else: # Issues in class files don't have a line number. error = '%s %s: %s [warning]' % (path, message, issue_id) print >> sys.stderr, error.encode('utf-8') for attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line.encode('utf-8') return len(issues) # Need to include all sources when a resource_dir is set so that resources are # not marked as unused. # TODO(agrieve): Figure out how IDEs do incremental linting. if not resource_dir and changes.AddedOrModifiedOnly(): changed_paths = set(changes.IterChangedPaths()) sources = [s for s in sources if s in changed_paths] with build_utils.TempDir() as temp_dir: _ProcessConfigFile() cmd = [ _RelativizePath(lint_path), '-Werror', '--exitcode', '--showall', '--xml', _RelativizePath(result_path), ] if jar_path: # --classpath is just for .class files for this one target. cmd.extend(['--classpath', _RelativizePath(jar_path)]) if processed_config_path: cmd.extend(['--config', _RelativizePath(processed_config_path)]) if resource_dir: cmd.extend(['--resources', _RelativizePath(resource_dir)]) if classpath: # --libraries is the classpath (excluding active target). cp = ':'.join(_RelativizePath(p) for p in classpath) cmd.extend(['--libraries', cp]) # There may be multiple source files with the same basename (but in # different directories). It is difficult to determine what part of the path # corresponds to the java package, and so instead just link the source files # into temporary directories (creating a new one whenever there is a name # conflict). src_dirs = [] def NewSourceDir(): new_dir = os.path.join(temp_dir, str(len(src_dirs))) os.mkdir(new_dir) src_dirs.append(new_dir) return new_dir def PathInDir(d, src): return os.path.join(d, os.path.basename(src)) for src in sources: src_dir = None for d in src_dirs: if not os.path.exists(PathInDir(d, src)): src_dir = d break if not src_dir: src_dir = NewSourceDir() cmd.extend(['--sources', _RelativizePath(src_dir)]) os.symlink(os.path.abspath(src), PathInDir(src_dir, src)) project_dir = NewSourceDir() if android_sdk_version: # Create dummy project.properies file in a temporary "project" directory. # It is the only way to add Android SDK to the Lint's classpath. Proper # classpath is necessary for most source-level checks. with open(os.path.join(project_dir, 'project.properties'), 'w') \ as propfile: print >> propfile, 'target=android-{}'.format(android_sdk_version) # Put the manifest in a temporary directory in order to avoid lint detecting # sibling res/ and src/ directories (which should be pass explicitly if they # are to be included). if manifest_path: os.symlink(os.path.abspath(manifest_path), PathInDir(project_dir, manifest_path)) cmd.append(project_dir) if os.path.exists(result_path): os.remove(result_path) env = {} stderr_filter = None if cache_dir: env['_JAVA_OPTIONS'] = '-Duser.home=%s' % _RelativizePath(cache_dir) # When _JAVA_OPTIONS is set, java prints to stderr: # Picked up _JAVA_OPTIONS: ... # # We drop all lines that contain _JAVA_OPTIONS from the output stderr_filter = lambda l: re.sub(r'.*_JAVA_OPTIONS.*\n?', '', l) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT, env=env or None, stderr_filter=stderr_filter) except build_utils.CalledProcessError: # There is a problem with lint usage if not os.path.exists(result_path): raise # Sometimes produces empty (almost) files: if os.path.getsize(result_path) < 10: if can_fail_build: raise elif not silent: traceback.print_exc() return # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() if not can_fail_build: return if can_fail_build and not silent: traceback.print_exc() # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() raise _ProcessResultFile() msg = ('\nLint found %d new issues.\n' ' - For full explanation refer to %s\n' % (num_issues, _RelativizePath(result_path))) if config_path: msg += (' - Wanna suppress these issues?\n' ' 1. Read comment in %s\n' ' 2. Run "python %s %s"\n' % (_RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) if not silent: print >> sys.stderr, msg if can_fail_build: raise Exception('Lint failed.') def main(): parser = argparse.ArgumentParser() build_utils.AddDepfileOption(parser) parser.add_argument('--lint-path', required=True, help='Path to lint executable.') parser.add_argument('--product-dir', required=True, help='Path to product dir.') parser.add_argument('--result-path', required=True, help='Path to XML lint result file.') parser.add_argument('--cache-dir', required=True, help='Path to the directory in which the android cache ' 'directory tree should be stored.') parser.add_argument('--platform-xml-path', required=True, help='Path to api-platforms.xml') parser.add_argument('--android-sdk-version', help='Version (API level) of the Android SDK used for ' 'building.') parser.add_argument('--create-cache', action='store_true', help='Mark the lint cache file as an output rather than ' 'an input.') parser.add_argument('--can-fail-build', action='store_true', help='If set, script will exit with nonzero exit status' ' if lint errors are present') parser.add_argument('--config-path', help='Path to lint suppressions file.') parser.add_argument('--enable', action='store_true', help='Run lint instead of just touching stamp.') parser.add_argument('--jar-path', help='Jar file containing class files.') parser.add_argument('--java-files', help='Paths to java files.') parser.add_argument('--manifest-path', help='Path to AndroidManifest.xml') parser.add_argument('--classpath', default=[], action='append', help='GYP-list of classpath .jar files') parser.add_argument('--processed-config-path', help='Path to processed lint suppressions file.') parser.add_argument('--resource-dir', help='Path to resource dir.') parser.add_argument('--silent', action='store_true', help='If set, script will not log anything.') parser.add_argument('--src-dirs', help='Directories containing java files.') parser.add_argument('--stamp', help='Path to touch on success.') args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:])) if args.enable: sources = [] if args.src_dirs: src_dirs = build_utils.ParseGypList(args.src_dirs) sources = build_utils.FindInDirectories(src_dirs, '*.java') elif args.java_files: sources = build_utils.ParseGypList(args.java_files) if args.config_path and not args.processed_config_path: parser.error('--config-path specified without --processed-config-path') elif args.processed_config_path and not args.config_path: parser.error('--processed-config-path specified without --config-path') input_paths = [ args.lint_path, args.platform_xml_path, ] if args.config_path: input_paths.append(args.config_path) if args.jar_path: input_paths.append(args.jar_path) if args.manifest_path: input_paths.append(args.manifest_path) if args.resource_dir: input_paths.extend(build_utils.FindInDirectory(args.resource_dir, '*')) if sources: input_paths.extend(sources) classpath = [] for gyp_list in args.classpath: classpath.extend(build_utils.ParseGypList(gyp_list)) input_paths.extend(classpath) input_strings = [] if args.android_sdk_version: input_strings.append(args.android_sdk_version) if args.processed_config_path: input_strings.append(args.processed_config_path) output_paths = [ args.result_path ] build_utils.CallAndWriteDepfileIfStale( lambda changes: _OnStaleMd5(changes, args.lint_path, args.config_path, args.processed_config_path, args.manifest_path, args.result_path, args.product_dir, sources, args.jar_path, args.cache_dir, args.android_sdk_version, resource_dir=args.resource_dir, classpath=classpath, can_fail_build=args.can_fail_build, silent=args.silent), args, input_paths=input_paths, input_strings=input_strings, output_paths=output_paths, pass_changes=True, depfile_deps=classpath) if __name__ == '__main__': sys.exit(main())
_ProcessConfigFile
identifier_name
lint.py
#!/usr/bin/env python # # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs Android's lint tool.""" import argparse import os import re import sys import traceback from xml.dom import minidom from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _OnStaleMd5(changes, lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, sources, jar_path, cache_dir, android_sdk_version, resource_dir=None, classpath=None, can_fail_build=False, silent=False): def _RelativizePath(path): """Returns relative path to top-level src dir. Args: path: A path relative to cwd. """ return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not config_path or not processed_config_path: return if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') if not silent: print >> sys.stderr for issue in issues: issue_id = issue.attributes['id'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error = '%s:%s %s: %s [warning]' % (path, line, message, issue_id) else: # Issues in class files don't have a line number. error = '%s %s: %s [warning]' % (path, message, issue_id) print >> sys.stderr, error.encode('utf-8') for attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line.encode('utf-8') return len(issues) # Need to include all sources when a resource_dir is set so that resources are # not marked as unused. # TODO(agrieve): Figure out how IDEs do incremental linting. if not resource_dir and changes.AddedOrModifiedOnly(): changed_paths = set(changes.IterChangedPaths()) sources = [s for s in sources if s in changed_paths] with build_utils.TempDir() as temp_dir: _ProcessConfigFile() cmd = [ _RelativizePath(lint_path), '-Werror', '--exitcode', '--showall', '--xml', _RelativizePath(result_path), ] if jar_path: # --classpath is just for .class files for this one target. cmd.extend(['--classpath', _RelativizePath(jar_path)]) if processed_config_path: cmd.extend(['--config', _RelativizePath(processed_config_path)]) if resource_dir: cmd.extend(['--resources', _RelativizePath(resource_dir)]) if classpath: # --libraries is the classpath (excluding active target). cp = ':'.join(_RelativizePath(p) for p in classpath) cmd.extend(['--libraries', cp]) # There may be multiple source files with the same basename (but in # different directories). It is difficult to determine what part of the path # corresponds to the java package, and so instead just link the source files # into temporary directories (creating a new one whenever there is a name # conflict). src_dirs = [] def NewSourceDir(): new_dir = os.path.join(temp_dir, str(len(src_dirs))) os.mkdir(new_dir) src_dirs.append(new_dir) return new_dir def PathInDir(d, src): return os.path.join(d, os.path.basename(src)) for src in sources: src_dir = None for d in src_dirs: if not os.path.exists(PathInDir(d, src)): src_dir = d break if not src_dir: src_dir = NewSourceDir() cmd.extend(['--sources', _RelativizePath(src_dir)]) os.symlink(os.path.abspath(src), PathInDir(src_dir, src)) project_dir = NewSourceDir() if android_sdk_version: # Create dummy project.properies file in a temporary "project" directory. # It is the only way to add Android SDK to the Lint's classpath. Proper # classpath is necessary for most source-level checks. with open(os.path.join(project_dir, 'project.properties'), 'w') \ as propfile: print >> propfile, 'target=android-{}'.format(android_sdk_version) # Put the manifest in a temporary directory in order to avoid lint detecting # sibling res/ and src/ directories (which should be pass explicitly if they # are to be included). if manifest_path: os.symlink(os.path.abspath(manifest_path), PathInDir(project_dir, manifest_path)) cmd.append(project_dir) if os.path.exists(result_path): os.remove(result_path) env = {} stderr_filter = None if cache_dir: env['_JAVA_OPTIONS'] = '-Duser.home=%s' % _RelativizePath(cache_dir) # When _JAVA_OPTIONS is set, java prints to stderr: # Picked up _JAVA_OPTIONS: ... # # We drop all lines that contain _JAVA_OPTIONS from the output stderr_filter = lambda l: re.sub(r'.*_JAVA_OPTIONS.*\n?', '', l) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT, env=env or None, stderr_filter=stderr_filter) except build_utils.CalledProcessError: # There is a problem with lint usage if not os.path.exists(result_path): raise # Sometimes produces empty (almost) files: if os.path.getsize(result_path) < 10: if can_fail_build: raise elif not silent: traceback.print_exc() return # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() if not can_fail_build: return if can_fail_build and not silent: traceback.print_exc() # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() raise _ProcessResultFile() msg = ('\nLint found %d new issues.\n' ' - For full explanation refer to %s\n' % (num_issues, _RelativizePath(result_path))) if config_path: msg += (' - Wanna suppress these issues?\n' ' 1. Read comment in %s\n' ' 2. Run "python %s %s"\n' % (_RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) if not silent: print >> sys.stderr, msg if can_fail_build: raise Exception('Lint failed.') def main(): parser = argparse.ArgumentParser() build_utils.AddDepfileOption(parser) parser.add_argument('--lint-path', required=True, help='Path to lint executable.') parser.add_argument('--product-dir', required=True, help='Path to product dir.') parser.add_argument('--result-path', required=True, help='Path to XML lint result file.') parser.add_argument('--cache-dir', required=True, help='Path to the directory in which the android cache ' 'directory tree should be stored.') parser.add_argument('--platform-xml-path', required=True, help='Path to api-platforms.xml') parser.add_argument('--android-sdk-version', help='Version (API level) of the Android SDK used for ' 'building.') parser.add_argument('--create-cache', action='store_true', help='Mark the lint cache file as an output rather than ' 'an input.') parser.add_argument('--can-fail-build', action='store_true', help='If set, script will exit with nonzero exit status' ' if lint errors are present') parser.add_argument('--config-path', help='Path to lint suppressions file.') parser.add_argument('--enable', action='store_true', help='Run lint instead of just touching stamp.') parser.add_argument('--jar-path', help='Jar file containing class files.') parser.add_argument('--java-files', help='Paths to java files.') parser.add_argument('--manifest-path', help='Path to AndroidManifest.xml') parser.add_argument('--classpath', default=[], action='append', help='GYP-list of classpath .jar files') parser.add_argument('--processed-config-path', help='Path to processed lint suppressions file.') parser.add_argument('--resource-dir', help='Path to resource dir.') parser.add_argument('--silent', action='store_true', help='If set, script will not log anything.') parser.add_argument('--src-dirs', help='Directories containing java files.') parser.add_argument('--stamp', help='Path to touch on success.') args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:])) if args.enable: sources = [] if args.src_dirs: src_dirs = build_utils.ParseGypList(args.src_dirs) sources = build_utils.FindInDirectories(src_dirs, '*.java') elif args.java_files:
if args.config_path and not args.processed_config_path: parser.error('--config-path specified without --processed-config-path') elif args.processed_config_path and not args.config_path: parser.error('--processed-config-path specified without --config-path') input_paths = [ args.lint_path, args.platform_xml_path, ] if args.config_path: input_paths.append(args.config_path) if args.jar_path: input_paths.append(args.jar_path) if args.manifest_path: input_paths.append(args.manifest_path) if args.resource_dir: input_paths.extend(build_utils.FindInDirectory(args.resource_dir, '*')) if sources: input_paths.extend(sources) classpath = [] for gyp_list in args.classpath: classpath.extend(build_utils.ParseGypList(gyp_list)) input_paths.extend(classpath) input_strings = [] if args.android_sdk_version: input_strings.append(args.android_sdk_version) if args.processed_config_path: input_strings.append(args.processed_config_path) output_paths = [ args.result_path ] build_utils.CallAndWriteDepfileIfStale( lambda changes: _OnStaleMd5(changes, args.lint_path, args.config_path, args.processed_config_path, args.manifest_path, args.result_path, args.product_dir, sources, args.jar_path, args.cache_dir, args.android_sdk_version, resource_dir=args.resource_dir, classpath=classpath, can_fail_build=args.can_fail_build, silent=args.silent), args, input_paths=input_paths, input_strings=input_strings, output_paths=output_paths, pass_changes=True, depfile_deps=classpath) if __name__ == '__main__': sys.exit(main())
sources = build_utils.ParseGypList(args.java_files)
conditional_block
lint.py
#!/usr/bin/env python # # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs Android's lint tool.""" import argparse import os import re import sys import traceback from xml.dom import minidom from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _OnStaleMd5(changes, lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, sources, jar_path, cache_dir, android_sdk_version, resource_dir=None, classpath=None, can_fail_build=False, silent=False):
def main(): parser = argparse.ArgumentParser() build_utils.AddDepfileOption(parser) parser.add_argument('--lint-path', required=True, help='Path to lint executable.') parser.add_argument('--product-dir', required=True, help='Path to product dir.') parser.add_argument('--result-path', required=True, help='Path to XML lint result file.') parser.add_argument('--cache-dir', required=True, help='Path to the directory in which the android cache ' 'directory tree should be stored.') parser.add_argument('--platform-xml-path', required=True, help='Path to api-platforms.xml') parser.add_argument('--android-sdk-version', help='Version (API level) of the Android SDK used for ' 'building.') parser.add_argument('--create-cache', action='store_true', help='Mark the lint cache file as an output rather than ' 'an input.') parser.add_argument('--can-fail-build', action='store_true', help='If set, script will exit with nonzero exit status' ' if lint errors are present') parser.add_argument('--config-path', help='Path to lint suppressions file.') parser.add_argument('--enable', action='store_true', help='Run lint instead of just touching stamp.') parser.add_argument('--jar-path', help='Jar file containing class files.') parser.add_argument('--java-files', help='Paths to java files.') parser.add_argument('--manifest-path', help='Path to AndroidManifest.xml') parser.add_argument('--classpath', default=[], action='append', help='GYP-list of classpath .jar files') parser.add_argument('--processed-config-path', help='Path to processed lint suppressions file.') parser.add_argument('--resource-dir', help='Path to resource dir.') parser.add_argument('--silent', action='store_true', help='If set, script will not log anything.') parser.add_argument('--src-dirs', help='Directories containing java files.') parser.add_argument('--stamp', help='Path to touch on success.') args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:])) if args.enable: sources = [] if args.src_dirs: src_dirs = build_utils.ParseGypList(args.src_dirs) sources = build_utils.FindInDirectories(src_dirs, '*.java') elif args.java_files: sources = build_utils.ParseGypList(args.java_files) if args.config_path and not args.processed_config_path: parser.error('--config-path specified without --processed-config-path') elif args.processed_config_path and not args.config_path: parser.error('--processed-config-path specified without --config-path') input_paths = [ args.lint_path, args.platform_xml_path, ] if args.config_path: input_paths.append(args.config_path) if args.jar_path: input_paths.append(args.jar_path) if args.manifest_path: input_paths.append(args.manifest_path) if args.resource_dir: input_paths.extend(build_utils.FindInDirectory(args.resource_dir, '*')) if sources: input_paths.extend(sources) classpath = [] for gyp_list in args.classpath: classpath.extend(build_utils.ParseGypList(gyp_list)) input_paths.extend(classpath) input_strings = [] if args.android_sdk_version: input_strings.append(args.android_sdk_version) if args.processed_config_path: input_strings.append(args.processed_config_path) output_paths = [ args.result_path ] build_utils.CallAndWriteDepfileIfStale( lambda changes: _OnStaleMd5(changes, args.lint_path, args.config_path, args.processed_config_path, args.manifest_path, args.result_path, args.product_dir, sources, args.jar_path, args.cache_dir, args.android_sdk_version, resource_dir=args.resource_dir, classpath=classpath, can_fail_build=args.can_fail_build, silent=args.silent), args, input_paths=input_paths, input_strings=input_strings, output_paths=output_paths, pass_changes=True, depfile_deps=classpath) if __name__ == '__main__': sys.exit(main())
def _RelativizePath(path): """Returns relative path to top-level src dir. Args: path: A path relative to cwd. """ return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not config_path or not processed_config_path: return if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') if not silent: print >> sys.stderr for issue in issues: issue_id = issue.attributes['id'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error = '%s:%s %s: %s [warning]' % (path, line, message, issue_id) else: # Issues in class files don't have a line number. error = '%s %s: %s [warning]' % (path, message, issue_id) print >> sys.stderr, error.encode('utf-8') for attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line.encode('utf-8') return len(issues) # Need to include all sources when a resource_dir is set so that resources are # not marked as unused. # TODO(agrieve): Figure out how IDEs do incremental linting. if not resource_dir and changes.AddedOrModifiedOnly(): changed_paths = set(changes.IterChangedPaths()) sources = [s for s in sources if s in changed_paths] with build_utils.TempDir() as temp_dir: _ProcessConfigFile() cmd = [ _RelativizePath(lint_path), '-Werror', '--exitcode', '--showall', '--xml', _RelativizePath(result_path), ] if jar_path: # --classpath is just for .class files for this one target. cmd.extend(['--classpath', _RelativizePath(jar_path)]) if processed_config_path: cmd.extend(['--config', _RelativizePath(processed_config_path)]) if resource_dir: cmd.extend(['--resources', _RelativizePath(resource_dir)]) if classpath: # --libraries is the classpath (excluding active target). cp = ':'.join(_RelativizePath(p) for p in classpath) cmd.extend(['--libraries', cp]) # There may be multiple source files with the same basename (but in # different directories). It is difficult to determine what part of the path # corresponds to the java package, and so instead just link the source files # into temporary directories (creating a new one whenever there is a name # conflict). src_dirs = [] def NewSourceDir(): new_dir = os.path.join(temp_dir, str(len(src_dirs))) os.mkdir(new_dir) src_dirs.append(new_dir) return new_dir def PathInDir(d, src): return os.path.join(d, os.path.basename(src)) for src in sources: src_dir = None for d in src_dirs: if not os.path.exists(PathInDir(d, src)): src_dir = d break if not src_dir: src_dir = NewSourceDir() cmd.extend(['--sources', _RelativizePath(src_dir)]) os.symlink(os.path.abspath(src), PathInDir(src_dir, src)) project_dir = NewSourceDir() if android_sdk_version: # Create dummy project.properies file in a temporary "project" directory. # It is the only way to add Android SDK to the Lint's classpath. Proper # classpath is necessary for most source-level checks. with open(os.path.join(project_dir, 'project.properties'), 'w') \ as propfile: print >> propfile, 'target=android-{}'.format(android_sdk_version) # Put the manifest in a temporary directory in order to avoid lint detecting # sibling res/ and src/ directories (which should be pass explicitly if they # are to be included). if manifest_path: os.symlink(os.path.abspath(manifest_path), PathInDir(project_dir, manifest_path)) cmd.append(project_dir) if os.path.exists(result_path): os.remove(result_path) env = {} stderr_filter = None if cache_dir: env['_JAVA_OPTIONS'] = '-Duser.home=%s' % _RelativizePath(cache_dir) # When _JAVA_OPTIONS is set, java prints to stderr: # Picked up _JAVA_OPTIONS: ... # # We drop all lines that contain _JAVA_OPTIONS from the output stderr_filter = lambda l: re.sub(r'.*_JAVA_OPTIONS.*\n?', '', l) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT, env=env or None, stderr_filter=stderr_filter) except build_utils.CalledProcessError: # There is a problem with lint usage if not os.path.exists(result_path): raise # Sometimes produces empty (almost) files: if os.path.getsize(result_path) < 10: if can_fail_build: raise elif not silent: traceback.print_exc() return # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() if not can_fail_build: return if can_fail_build and not silent: traceback.print_exc() # There are actual lint issues try: num_issues = _ParseAndShowResultFile() except Exception: # pylint: disable=broad-except if not silent: print 'Lint created unparseable xml file...' print 'File contents:' with open(result_path) as f: print f.read() raise _ProcessResultFile() msg = ('\nLint found %d new issues.\n' ' - For full explanation refer to %s\n' % (num_issues, _RelativizePath(result_path))) if config_path: msg += (' - Wanna suppress these issues?\n' ' 1. Read comment in %s\n' ' 2. Run "python %s %s"\n' % (_RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) if not silent: print >> sys.stderr, msg if can_fail_build: raise Exception('Lint failed.')
identifier_body
test_update.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be) # # 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. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################ from django.contrib.messages import get_messages, SUCCESS from django.test import TestCase from django.urls import reverse from django.utils.translation import gettext_lazy as _ from waffle.testutils import override_flag from base.models.enums.entity_type import FACULTY from base.models.enums.learning_container_year_types import EXTERNAL from base.models.enums.organization_type import MAIN from base.tests.factories.academic_calendar import generate_learning_unit_edition_calendars from base.tests.factories.academic_year import create_current_academic_year from base.tests.factories.entity import EntityWithVersionFactory from base.tests.factories.external_learning_unit_year import ExternalLearningUnitYearFactory from base.tests.factories.learning_unit_year import LearningUnitYearFullFactory from base.tests.factories.person import PersonFactory from base.tests.forms.test_external_learning_unit import get_valid_external_learning_unit_form_data from base.views.learning_units.update import update_learning_unit from learning_unit.tests.factories.central_manager import CentralManagerFactory @override_flag('learning_unit_update', active=True) class TestUpdateExternalLearningUnitView(TestCase): @classmethod def setUpTestData(cls): cls.entity = EntityWithVersionFactory(organization__type=MAIN, version__entity_type=FACULTY) cls.manager = CentralManagerFactory(entity=cls.entity, with_child=True) cls.person = cls.manager.person cls.academic_year = create_current_academic_year() generate_learning_unit_edition_calendars([cls.academic_year]) cls.luy = LearningUnitYearFullFactory( academic_year=cls.academic_year, internship_subtype=None, acronym="EFAC1000", learning_container_year__container_type=EXTERNAL, learning_container_year__requirement_entity=cls.entity, learning_container_year__allocation_entity=cls.entity, ) cls.data = get_valid_external_learning_unit_form_data(cls.academic_year, cls.luy, cls.entity) cls.url = reverse(update_learning_unit, args=[cls.luy.pk]) def setUp(self): self.external = ExternalLearningUnitYearFactory(learning_unit_year=self.luy) self.client.force_login(self.person.user) def test_update_get(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_update_get_permission_denied(self): self.client.force_login(PersonFactory().user) response = self.client.get(self.url) self.assertEqual(response.status_code, 403) def test_update_post(self): response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.level for m in get_messages(response.wsgi_request)] self.assertEqual(messages, [SUCCESS]) def test_update_message_with_report(self): self.data['postponement'] = "1" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (with report).")) def test_update_message_without_report(self): s
elf.data['postponement'] = "0" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (without report)."))
identifier_body
test_update.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be) # # 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. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################ from django.contrib.messages import get_messages, SUCCESS from django.test import TestCase from django.urls import reverse from django.utils.translation import gettext_lazy as _ from waffle.testutils import override_flag from base.models.enums.entity_type import FACULTY from base.models.enums.learning_container_year_types import EXTERNAL from base.models.enums.organization_type import MAIN from base.tests.factories.academic_calendar import generate_learning_unit_edition_calendars from base.tests.factories.academic_year import create_current_academic_year from base.tests.factories.entity import EntityWithVersionFactory from base.tests.factories.external_learning_unit_year import ExternalLearningUnitYearFactory from base.tests.factories.learning_unit_year import LearningUnitYearFullFactory from base.tests.factories.person import PersonFactory from base.tests.forms.test_external_learning_unit import get_valid_external_learning_unit_form_data from base.views.learning_units.update import update_learning_unit from learning_unit.tests.factories.central_manager import CentralManagerFactory @override_flag('learning_unit_update', active=True) class TestUpdateExternalLearningUnitView(TestCase): @classmethod def setUpTestData(cls): cls.entity = EntityWithVersionFactory(organization__type=MAIN, version__entity_type=FACULTY) cls.manager = CentralManagerFactory(entity=cls.entity, with_child=True) cls.person = cls.manager.person cls.academic_year = create_current_academic_year() generate_learning_unit_edition_calendars([cls.academic_year]) cls.luy = LearningUnitYearFullFactory( academic_year=cls.academic_year, internship_subtype=None, acronym="EFAC1000", learning_container_year__container_type=EXTERNAL, learning_container_year__requirement_entity=cls.entity, learning_container_year__allocation_entity=cls.entity, ) cls.data = get_valid_external_learning_unit_form_data(cls.academic_year, cls.luy, cls.entity) cls.url = reverse(update_learning_unit, args=[cls.luy.pk]) def setUp(self): self.external = ExternalLearningUnitYearFactory(learning_unit_year=self.luy) self.client.force_login(self.person.user) def test_update_get(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_update_get_permission_denied(self): self.client.force_login(PersonFactory().user) response = self.client.get(self.url) self.assertEqual(response.status_code, 403) def test_update_post(self): response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.level for m in get_messages(response.wsgi_request)] self.assertEqual(messages, [SUCCESS]) def test_update_message_with_report(self): self.data['postponement'] = "1" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (with report).")) def t
self): self.data['postponement'] = "0" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (without report)."))
est_update_message_without_report(
identifier_name
test_update.py
############################################################################ # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be) # # 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. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################ from django.contrib.messages import get_messages, SUCCESS from django.test import TestCase from django.urls import reverse from django.utils.translation import gettext_lazy as _ from waffle.testutils import override_flag from base.models.enums.entity_type import FACULTY from base.models.enums.learning_container_year_types import EXTERNAL from base.models.enums.organization_type import MAIN from base.tests.factories.academic_calendar import generate_learning_unit_edition_calendars from base.tests.factories.academic_year import create_current_academic_year from base.tests.factories.entity import EntityWithVersionFactory from base.tests.factories.external_learning_unit_year import ExternalLearningUnitYearFactory from base.tests.factories.learning_unit_year import LearningUnitYearFullFactory from base.tests.factories.person import PersonFactory from base.tests.forms.test_external_learning_unit import get_valid_external_learning_unit_form_data from base.views.learning_units.update import update_learning_unit from learning_unit.tests.factories.central_manager import CentralManagerFactory @override_flag('learning_unit_update', active=True) class TestUpdateExternalLearningUnitView(TestCase): @classmethod def setUpTestData(cls): cls.entity = EntityWithVersionFactory(organization__type=MAIN, version__entity_type=FACULTY) cls.manager = CentralManagerFactory(entity=cls.entity, with_child=True) cls.person = cls.manager.person cls.academic_year = create_current_academic_year() generate_learning_unit_edition_calendars([cls.academic_year]) cls.luy = LearningUnitYearFullFactory( academic_year=cls.academic_year, internship_subtype=None,
learning_container_year__container_type=EXTERNAL, learning_container_year__requirement_entity=cls.entity, learning_container_year__allocation_entity=cls.entity, ) cls.data = get_valid_external_learning_unit_form_data(cls.academic_year, cls.luy, cls.entity) cls.url = reverse(update_learning_unit, args=[cls.luy.pk]) def setUp(self): self.external = ExternalLearningUnitYearFactory(learning_unit_year=self.luy) self.client.force_login(self.person.user) def test_update_get(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) def test_update_get_permission_denied(self): self.client.force_login(PersonFactory().user) response = self.client.get(self.url) self.assertEqual(response.status_code, 403) def test_update_post(self): response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.level for m in get_messages(response.wsgi_request)] self.assertEqual(messages, [SUCCESS]) def test_update_message_with_report(self): self.data['postponement'] = "1" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (with report).")) def test_update_message_without_report(self): self.data['postponement'] = "0" response = self.client.post(self.url, data=self.data) self.assertEqual(response.status_code, 302) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertEqual(messages[0], _("The learning unit has been updated (without report)."))
acronym="EFAC1000",
random_line_split
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ return; } jQuery.bt.options.closeWhenOthersOpen = true; var beautytips = Drupal.settings.beautytips; // On ajax page loads, if the same settings are added // to the page, then it can mess up the settings. // If this is fixed in Drupal, then this can be removed. function
(originalArray, count) { for (var key in originalArray) { if (key == 'cssStyles') { originalArray[key] = fixArray(originalArray[key], count); } else if (originalArray[key].length == count) { originalArray[key] = originalArray[key][0]; } else { length = Math.round(originalArray[key].length / count); originalArray[key] = originalArray[key].slice(0, length); } } return originalArray; } // Add the the tooltips to the page for (var key in beautytips) { // If there's an ajax page load on a page, drupal can add these // settings more than once and it adds the settings instead of replaces. // We have to fix these here. if (typeof(Drupal.settings.beautytips[key]['cssSelect']) == 'object') { var count = Drupal.settings.beautytips[key]['cssSelect'].length; beautytips[key] = fixArray(beautytips[key], count); Drupal.settings.beautytips[key] = beautytips[key]; } // Build array of options that were passed to beautytips_add_beautyips var btOptions = new Array(); if (beautytips[key]['list']) { for ( var k = 0; k < beautytips[key]['list'].length; k++) { btOptions[beautytips[key]['list'][k]] = beautytips[key][beautytips[key]['list'][k]]; } } if (beautytips[key]['cssSelect']) { if (beautytips[key]['animate']) { btOptions = beautytipsAddAnimations(beautytips[key]['animate'], btOptions); } if (beautytips[key]['keepOpenWhenHovering']) { btOptions['trigger'] = 'hoverIntent'; btOptions['hoverIntentOpts'] = { interval: 0, timeout: 500, } // from: http://stackoverflow.com/questions/4034671/how-to-make-jquery-beauty-tip-stay-open-as-long-as-the-cursor-is-over-the-toolti btOptions['postShow'] = function(box) { $(box).hoverIntent({ over: function() { $(this).data('hasmouse', true); }, out: function() { $(this).data('hasmouse', false); $(box).hide(); }, timeout: 300, }); } btOptions['hideTip'] = function(box, callback) { if ($(box).data('hasmouse')) { return; } $(box).hide(); callback(); } } // Run any java script that needs to be run when the page loads if (beautytips[key]['contentSelector'] && beautytips[key]['preEval']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this, false)) { eval(beautytips[key]['contentSelector']); } }); } if (beautytips[key]['text']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(beautytips[key]['text'], btOptions); } }); } else if (beautytips[key]['ajaxPath']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { if (beautytips[key]['ajaxDisableLink']) { $(this).click(function(event) { event.preventDefault(); }); } $(this).bt(btOptions); } }); } else { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(btOptions); } }); } } btOptions.length = 0; } } } /** * Determine if an element has already been processed. */ function beautytipsProcessed(element, addClass) { if ($(element).hasClass('beautytips-module-processed')) { return true; } if (addClass != false) { $(element).addClass('beautytips-module-processed'); } return false; } function beautytipsAddAnimations(animations, btOptions) { switch (animations['on']) { case 'none': break; case 'fadeIn': btOptions['showTip'] = function(box) { $(box).fadeIn(500); }; break; case 'slideIn': break; } switch (animations['off']) { case 'none': break; case 'fadeOut': btOptions['hideTip'] = function(box, callback) { $(box).animate({opacity: 0}, 500, callback); }; break; case 'slideOut': btOptions['hideTip'] = function(box, callback) { var width = $("body").width(); $(box).animate({"left": "+=" + width + "px"}, "slow", callback); } break; } return btOptions; } })(jQuery);
fixArray
identifier_name
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ return; } jQuery.bt.options.closeWhenOthersOpen = true; var beautytips = Drupal.settings.beautytips; // On ajax page loads, if the same settings are added // to the page, then it can mess up the settings. // If this is fixed in Drupal, then this can be removed. function fixArray(originalArray, count) { for (var key in originalArray) { if (key == 'cssStyles') { originalArray[key] = fixArray(originalArray[key], count); } else if (originalArray[key].length == count) { originalArray[key] = originalArray[key][0]; } else { length = Math.round(originalArray[key].length / count); originalArray[key] = originalArray[key].slice(0, length); } } return originalArray; } // Add the the tooltips to the page for (var key in beautytips) { // If there's an ajax page load on a page, drupal can add these // settings more than once and it adds the settings instead of replaces. // We have to fix these here. if (typeof(Drupal.settings.beautytips[key]['cssSelect']) == 'object') { var count = Drupal.settings.beautytips[key]['cssSelect'].length; beautytips[key] = fixArray(beautytips[key], count); Drupal.settings.beautytips[key] = beautytips[key]; } // Build array of options that were passed to beautytips_add_beautyips var btOptions = new Array(); if (beautytips[key]['list']) { for ( var k = 0; k < beautytips[key]['list'].length; k++) { btOptions[beautytips[key]['list'][k]] = beautytips[key][beautytips[key]['list'][k]]; } } if (beautytips[key]['cssSelect']) { if (beautytips[key]['animate']) { btOptions = beautytipsAddAnimations(beautytips[key]['animate'], btOptions); } if (beautytips[key]['keepOpenWhenHovering']) { btOptions['trigger'] = 'hoverIntent'; btOptions['hoverIntentOpts'] = { interval: 0, timeout: 500, } // from: http://stackoverflow.com/questions/4034671/how-to-make-jquery-beauty-tip-stay-open-as-long-as-the-cursor-is-over-the-toolti btOptions['postShow'] = function(box) { $(box).hoverIntent({ over: function() { $(this).data('hasmouse', true); }, out: function() { $(this).data('hasmouse', false); $(box).hide(); }, timeout: 300, }); } btOptions['hideTip'] = function(box, callback) { if ($(box).data('hasmouse')) { return; } $(box).hide(); callback(); } } // Run any java script that needs to be run when the page loads if (beautytips[key]['contentSelector'] && beautytips[key]['preEval']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this, false)) { eval(beautytips[key]['contentSelector']); } }); } if (beautytips[key]['text']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(beautytips[key]['text'], btOptions); } }); } else if (beautytips[key]['ajaxPath']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { if (beautytips[key]['ajaxDisableLink']) { $(this).click(function(event) { event.preventDefault(); }); } $(this).bt(btOptions); } }); } else { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(btOptions); } }); } } btOptions.length = 0; } } } /** * Determine if an element has already been processed. */ function beautytipsProcessed(element, addClass) { if ($(element).hasClass('beautytips-module-processed')) { return true; } if (addClass != false) { $(element).addClass('beautytips-module-processed'); } return false; } function beautytipsAddAnimations(animations, btOptions)
})(jQuery);
{ switch (animations['on']) { case 'none': break; case 'fadeIn': btOptions['showTip'] = function(box) { $(box).fadeIn(500); }; break; case 'slideIn': break; } switch (animations['off']) { case 'none': break; case 'fadeOut': btOptions['hideTip'] = function(box, callback) { $(box).animate({opacity: 0}, 500, callback); }; break; case 'slideOut': btOptions['hideTip'] = function(box, callback) { var width = $("body").width(); $(box).animate({"left": "+=" + width + "px"}, "slow", callback); } break; } return btOptions; }
identifier_body
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ return; } jQuery.bt.options.closeWhenOthersOpen = true; var beautytips = Drupal.settings.beautytips; // On ajax page loads, if the same settings are added // to the page, then it can mess up the settings. // If this is fixed in Drupal, then this can be removed. function fixArray(originalArray, count) { for (var key in originalArray) { if (key == 'cssStyles') { originalArray[key] = fixArray(originalArray[key], count); } else if (originalArray[key].length == count) { originalArray[key] = originalArray[key][0]; } else { length = Math.round(originalArray[key].length / count); originalArray[key] = originalArray[key].slice(0, length); } } return originalArray; } // Add the the tooltips to the page for (var key in beautytips) { // If there's an ajax page load on a page, drupal can add these // settings more than once and it adds the settings instead of replaces. // We have to fix these here. if (typeof(Drupal.settings.beautytips[key]['cssSelect']) == 'object') { var count = Drupal.settings.beautytips[key]['cssSelect'].length; beautytips[key] = fixArray(beautytips[key], count); Drupal.settings.beautytips[key] = beautytips[key]; } // Build array of options that were passed to beautytips_add_beautyips var btOptions = new Array(); if (beautytips[key]['list']) { for ( var k = 0; k < beautytips[key]['list'].length; k++) { btOptions[beautytips[key]['list'][k]] = beautytips[key][beautytips[key]['list'][k]]; } } if (beautytips[key]['cssSelect']) { if (beautytips[key]['animate']) { btOptions = beautytipsAddAnimations(beautytips[key]['animate'], btOptions); } if (beautytips[key]['keepOpenWhenHovering']) { btOptions['trigger'] = 'hoverIntent'; btOptions['hoverIntentOpts'] = { interval: 0, timeout: 500, } // from: http://stackoverflow.com/questions/4034671/how-to-make-jquery-beauty-tip-stay-open-as-long-as-the-cursor-is-over-the-toolti btOptions['postShow'] = function(box) { $(box).hoverIntent({ over: function() { $(this).data('hasmouse', true); }, out: function() { $(this).data('hasmouse', false); $(box).hide(); }, timeout: 300, }); } btOptions['hideTip'] = function(box, callback) { if ($(box).data('hasmouse')) {
return; } $(box).hide(); callback(); } } // Run any java script that needs to be run when the page loads if (beautytips[key]['contentSelector'] && beautytips[key]['preEval']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this, false)) { eval(beautytips[key]['contentSelector']); } }); } if (beautytips[key]['text']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(beautytips[key]['text'], btOptions); } }); } else if (beautytips[key]['ajaxPath']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { if (beautytips[key]['ajaxDisableLink']) { $(this).click(function(event) { event.preventDefault(); }); } $(this).bt(btOptions); } }); } else { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(btOptions); } }); } } btOptions.length = 0; } } } /** * Determine if an element has already been processed. */ function beautytipsProcessed(element, addClass) { if ($(element).hasClass('beautytips-module-processed')) { return true; } if (addClass != false) { $(element).addClass('beautytips-module-processed'); } return false; } function beautytipsAddAnimations(animations, btOptions) { switch (animations['on']) { case 'none': break; case 'fadeIn': btOptions['showTip'] = function(box) { $(box).fadeIn(500); }; break; case 'slideIn': break; } switch (animations['off']) { case 'none': break; case 'fadeOut': btOptions['hideTip'] = function(box, callback) { $(box).animate({opacity: 0}, 500, callback); }; break; case 'slideOut': btOptions['hideTip'] = function(box, callback) { var width = $("body").width(); $(box).animate({"left": "+=" + width + "px"}, "slow", callback); } break; } return btOptions; } })(jQuery);
random_line_split
beautytips.js
/** * Defines the default beautytip and adds them to the content on the page */ (function ($) { Drupal.behaviors.beautytips = { attach: function(context, settings) { // Fix for drupal attach behaviors in case the plugin is not attached. if (typeof(jQuery.bt) == 'undefined' && jQuery.bt == null){ return; } jQuery.bt.options.closeWhenOthersOpen = true; var beautytips = Drupal.settings.beautytips; // On ajax page loads, if the same settings are added // to the page, then it can mess up the settings. // If this is fixed in Drupal, then this can be removed. function fixArray(originalArray, count) { for (var key in originalArray) { if (key == 'cssStyles') { originalArray[key] = fixArray(originalArray[key], count); } else if (originalArray[key].length == count) { originalArray[key] = originalArray[key][0]; } else { length = Math.round(originalArray[key].length / count); originalArray[key] = originalArray[key].slice(0, length); } } return originalArray; } // Add the the tooltips to the page for (var key in beautytips) { // If there's an ajax page load on a page, drupal can add these // settings more than once and it adds the settings instead of replaces. // We have to fix these here. if (typeof(Drupal.settings.beautytips[key]['cssSelect']) == 'object') { var count = Drupal.settings.beautytips[key]['cssSelect'].length; beautytips[key] = fixArray(beautytips[key], count); Drupal.settings.beautytips[key] = beautytips[key]; } // Build array of options that were passed to beautytips_add_beautyips var btOptions = new Array(); if (beautytips[key]['list']) { for ( var k = 0; k < beautytips[key]['list'].length; k++) { btOptions[beautytips[key]['list'][k]] = beautytips[key][beautytips[key]['list'][k]]; } } if (beautytips[key]['cssSelect']) { if (beautytips[key]['animate']) { btOptions = beautytipsAddAnimations(beautytips[key]['animate'], btOptions); } if (beautytips[key]['keepOpenWhenHovering']) { btOptions['trigger'] = 'hoverIntent'; btOptions['hoverIntentOpts'] = { interval: 0, timeout: 500, } // from: http://stackoverflow.com/questions/4034671/how-to-make-jquery-beauty-tip-stay-open-as-long-as-the-cursor-is-over-the-toolti btOptions['postShow'] = function(box) { $(box).hoverIntent({ over: function() { $(this).data('hasmouse', true); }, out: function() { $(this).data('hasmouse', false); $(box).hide(); }, timeout: 300, }); } btOptions['hideTip'] = function(box, callback) { if ($(box).data('hasmouse')) { return; } $(box).hide(); callback(); } } // Run any java script that needs to be run when the page loads if (beautytips[key]['contentSelector'] && beautytips[key]['preEval']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this, false)) { eval(beautytips[key]['contentSelector']); } }); } if (beautytips[key]['text']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(beautytips[key]['text'], btOptions); } }); } else if (beautytips[key]['ajaxPath']) { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { if (beautytips[key]['ajaxDisableLink']) { $(this).click(function(event) { event.preventDefault(); }); } $(this).bt(btOptions); } }); } else { $(beautytips[key]['cssSelect']).each(function() { if (!beautytipsProcessed(this)) { $(this).bt(btOptions); } }); } } btOptions.length = 0; } } } /** * Determine if an element has already been processed. */ function beautytipsProcessed(element, addClass) { if ($(element).hasClass('beautytips-module-processed')) { return true; } if (addClass != false)
return false; } function beautytipsAddAnimations(animations, btOptions) { switch (animations['on']) { case 'none': break; case 'fadeIn': btOptions['showTip'] = function(box) { $(box).fadeIn(500); }; break; case 'slideIn': break; } switch (animations['off']) { case 'none': break; case 'fadeOut': btOptions['hideTip'] = function(box, callback) { $(box).animate({opacity: 0}, 500, callback); }; break; case 'slideOut': btOptions['hideTip'] = function(box, callback) { var width = $("body").width(); $(box).animate({"left": "+=" + width + "px"}, "slow", callback); } break; } return btOptions; } })(jQuery);
{ $(element).addClass('beautytips-module-processed'); }
conditional_block
cond-macro.rs
// Copyright 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. fn clamp<T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T
fn main() { assert_eq!(clamp(1, 2, 4), 2); assert_eq!(clamp(8, 2, 4), 4); assert_eq!(clamp(3, 2, 4), 3); }
{ cond!( (x > mx) { mx } (x < mn) { mn } _ { x } ) }
identifier_body
cond-macro.rs
// Copyright 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. fn clamp<T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T { cond!( (x > mx) { mx } (x < mn) { mn } _ { x } ) } fn main() { assert_eq!(clamp(1, 2, 4), 2); assert_eq!(clamp(8, 2, 4), 4); assert_eq!(clamp(3, 2, 4), 3); }
random_line_split
cond-macro.rs
// Copyright 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. fn
<T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T { cond!( (x > mx) { mx } (x < mn) { mn } _ { x } ) } fn main() { assert_eq!(clamp(1, 2, 4), 2); assert_eq!(clamp(8, 2, 4), 4); assert_eq!(clamp(3, 2, 4), 3); }
clamp
identifier_name
result.rs
//! A module describing Lox-specific Result and Error types use object::Object; use std::result; use std::error; use std::fmt; use std::io; /// A Lox-Specific Result Type pub type Result<T> = result::Result<T, Error>; /// A Lox-Specific Error #[derive(Debug)] pub enum
{ /// Returned if the CLI command is used incorrectly Usage, /// Returned if there is an error reading from a file or stdin IO(io::Error), /// Returned if the scanner encounters an error Lexical(u64, String, String), /// Returned if the parser encounters an error Parse(u64, String, String), /// Returned if there is an error at runtime Runtime(u64, String, String), /// Sentinel error for break statements Break(u64), /// Sentinel error for return statements Return(u64, Object), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IO(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Usage => write!(f, "Usage: rlox [script]"), Error::IO(ref e) => e.fmt(f), Error::Lexical(ref line, ref msg, ref whence) => write!(f, "Lexical Error [line {}] {}: {:?}", line, msg, whence), Error::Parse(ref line, ref msg, ref near) => write!(f, "Parse Error [line {}] {}: near {}", line, msg, &near), Error::Runtime(ref line, ref msg, ref near) => write!(f, "Runtime Error [line {}] {}: near {}", line, msg, &near), Error::Break(ref line) => write!(f, "Runtime Error [line {}] unexpected break statement", line), Error::Return(ref line, _) => write!(f, "Runtime Error [line {}] unexpected return statement", line), } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Usage => "usage error", Error::IO(ref e) => e.description(), Error::Lexical(_, _, _) => "lexical error", Error::Parse(_, _, _) => "parse error", Error::Runtime(_, _, _) => "runtime error", Error::Break(_) => "break error", Error::Return(_, _) => "return error", } } fn cause(&self) -> Option<&error::Error> { match *self { Error::IO(ref e) => e.cause(), _ => None, } } }
Error
identifier_name
result.rs
//! A module describing Lox-specific Result and Error types
use std::fmt; use std::io; /// A Lox-Specific Result Type pub type Result<T> = result::Result<T, Error>; /// A Lox-Specific Error #[derive(Debug)] pub enum Error { /// Returned if the CLI command is used incorrectly Usage, /// Returned if there is an error reading from a file or stdin IO(io::Error), /// Returned if the scanner encounters an error Lexical(u64, String, String), /// Returned if the parser encounters an error Parse(u64, String, String), /// Returned if there is an error at runtime Runtime(u64, String, String), /// Sentinel error for break statements Break(u64), /// Sentinel error for return statements Return(u64, Object), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IO(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Usage => write!(f, "Usage: rlox [script]"), Error::IO(ref e) => e.fmt(f), Error::Lexical(ref line, ref msg, ref whence) => write!(f, "Lexical Error [line {}] {}: {:?}", line, msg, whence), Error::Parse(ref line, ref msg, ref near) => write!(f, "Parse Error [line {}] {}: near {}", line, msg, &near), Error::Runtime(ref line, ref msg, ref near) => write!(f, "Runtime Error [line {}] {}: near {}", line, msg, &near), Error::Break(ref line) => write!(f, "Runtime Error [line {}] unexpected break statement", line), Error::Return(ref line, _) => write!(f, "Runtime Error [line {}] unexpected return statement", line), } } } impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Usage => "usage error", Error::IO(ref e) => e.description(), Error::Lexical(_, _, _) => "lexical error", Error::Parse(_, _, _) => "parse error", Error::Runtime(_, _, _) => "runtime error", Error::Break(_) => "break error", Error::Return(_, _) => "return error", } } fn cause(&self) -> Option<&error::Error> { match *self { Error::IO(ref e) => e.cause(), _ => None, } } }
use object::Object; use std::result; use std::error;
random_line_split
pipeline.py
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3]) fork the pipeline in two paths and has two outputs (stage2 and stage3). It is used during the construction of Pipeline. """ def __init__(self, *branches): self.forked_branches: list = list(branches) class Pipeline(): """ This class create a multithreaded pipeline. It automatically links together every contiguous stages. E.g.: Pipeline(Signal(), PipelineStage(), PipelineFork([PipelineStage(), PipelineStage()], [PipelineStage()] )) """ def __init__(self, input_signal: Signal, *stages): self._output_queues = [] self._stages: list = list(stages) self._link_stages(self._stages) self._stages[0]._queue_in = input_signal.signal_queue def get_output_queue(self, queue_index=0) -> StoppableQueue: """Return a ref to the queue given by queue_index""" return self._output_queues[queue_index] def read_output_queue(self, queue_index=0): """Wait to read a data in a queue given by queue_index""" return self._output_queues[queue_index].get() def start(self): """Start all pipelines stages.""" self._start(self._stages) def shutdown(self): """ shutdowns every child thread (PipelineStage)""" self._shutdown(self._stages) def join(self): """Ensure every thread (PipelineStage) of the pipeline are done""" for stage in self._stages: stage.join() def _link_pipeline_fork(self, stages: list, index: int): for fork in stages[index].forked_branches: stages[index - 1].add_queue_out(fork[0].queue_in) self._link_stages(fork) def _link_stages(self, stages: list):
def _start(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches: self._start(forked_branch) else: stage.start() def _shutdown(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches: self._shutdown(forked_branch) else: stage.shutdown()
for i in range(1, len(stages)): if type(stages[i]) == PipelineFork: self._link_pipeline_fork(stages, i) else: stages[i - 1].add_queue_out(stages[i].queue_in) if issubclass(type(stages[-1]), PipelineStage): output_queue = StoppableQueue(PIPELINE_QUEUE_SIZE) stages[-1].add_queue_out(output_queue) self._output_queues.append(output_queue)
identifier_body
pipeline.py
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3]) fork the pipeline in two paths and has two outputs (stage2 and stage3). It is used during the construction of Pipeline. """ def __init__(self, *branches): self.forked_branches: list = list(branches) class Pipeline(): """ This class create a multithreaded pipeline. It automatically links together every contiguous stages. E.g.: Pipeline(Signal(), PipelineStage(), PipelineFork([PipelineStage(), PipelineStage()], [PipelineStage()] )) """ def __init__(self, input_signal: Signal, *stages): self._output_queues = [] self._stages: list = list(stages) self._link_stages(self._stages) self._stages[0]._queue_in = input_signal.signal_queue def get_output_queue(self, queue_index=0) -> StoppableQueue: """Return a ref to the queue given by queue_index""" return self._output_queues[queue_index]
def start(self): """Start all pipelines stages.""" self._start(self._stages) def shutdown(self): """ shutdowns every child thread (PipelineStage)""" self._shutdown(self._stages) def join(self): """Ensure every thread (PipelineStage) of the pipeline are done""" for stage in self._stages: stage.join() def _link_pipeline_fork(self, stages: list, index: int): for fork in stages[index].forked_branches: stages[index - 1].add_queue_out(fork[0].queue_in) self._link_stages(fork) def _link_stages(self, stages: list): for i in range(1, len(stages)): if type(stages[i]) == PipelineFork: self._link_pipeline_fork(stages, i) else: stages[i - 1].add_queue_out(stages[i].queue_in) if issubclass(type(stages[-1]), PipelineStage): output_queue = StoppableQueue(PIPELINE_QUEUE_SIZE) stages[-1].add_queue_out(output_queue) self._output_queues.append(output_queue) def _start(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches: self._start(forked_branch) else: stage.start() def _shutdown(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches: self._shutdown(forked_branch) else: stage.shutdown()
def read_output_queue(self, queue_index=0): """Wait to read a data in a queue given by queue_index""" return self._output_queues[queue_index].get()
random_line_split
pipeline.py
from pymuse.pipelinestages.pipeline_stage import PipelineStage from pymuse.utils.stoppablequeue import StoppableQueue from pymuse.signal import Signal from pymuse.constants import PIPELINE_QUEUE_SIZE class PipelineFork(): """ This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3]) fork the pipeline in two paths and has two outputs (stage2 and stage3). It is used during the construction of Pipeline. """ def __init__(self, *branches): self.forked_branches: list = list(branches) class Pipeline(): """ This class create a multithreaded pipeline. It automatically links together every contiguous stages. E.g.: Pipeline(Signal(), PipelineStage(), PipelineFork([PipelineStage(), PipelineStage()], [PipelineStage()] )) """ def __init__(self, input_signal: Signal, *stages): self._output_queues = [] self._stages: list = list(stages) self._link_stages(self._stages) self._stages[0]._queue_in = input_signal.signal_queue def get_output_queue(self, queue_index=0) -> StoppableQueue: """Return a ref to the queue given by queue_index""" return self._output_queues[queue_index] def read_output_queue(self, queue_index=0): """Wait to read a data in a queue given by queue_index""" return self._output_queues[queue_index].get() def start(self): """Start all pipelines stages.""" self._start(self._stages) def shutdown(self): """ shutdowns every child thread (PipelineStage)""" self._shutdown(self._stages) def join(self): """Ensure every thread (PipelineStage) of the pipeline are done""" for stage in self._stages: stage.join() def _link_pipeline_fork(self, stages: list, index: int): for fork in stages[index].forked_branches: stages[index - 1].add_queue_out(fork[0].queue_in) self._link_stages(fork) def _link_stages(self, stages: list): for i in range(1, len(stages)): if type(stages[i]) == PipelineFork: self._link_pipeline_fork(stages, i) else: stages[i - 1].add_queue_out(stages[i].queue_in) if issubclass(type(stages[-1]), PipelineStage): output_queue = StoppableQueue(PIPELINE_QUEUE_SIZE) stages[-1].add_queue_out(output_queue) self._output_queues.append(output_queue) def _start(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches:
else: stage.start() def _shutdown(self, stages: list): for stage in stages: if type(stage) == PipelineFork: for forked_branch in stage.forked_branches: self._shutdown(forked_branch) else: stage.shutdown()
self._start(forked_branch)
conditional_block