text stringlengths 2 1.04M | meta dict |
|---|---|
npx xslt3 -xsl:build/generator/links.sef.json -json:test/test.json
npx xslt3 -xsl:build/generator/links.sef.json -json:test/test.json -im:attr
npx xslt3 -xsl:build/generator/lists.sef.json -json:test/test.json
npx xslt3 -xsl:build/generator/lists.sef.json -json:test/test.json -im:attr
npx xslt3 -xsl:build/generator/pr-domain.sef.json -json:test/test.json
npx xslt3 -xsl:build/generator/pr-domain.sef.json -json:test/test.json -im:attr | {
"content_hash": "d8d59dc3ec514ba722de98bd8ab2b845",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 79,
"avg_line_length": 72.66666666666667,
"alnum_prop": 0.7844036697247706,
"repo_name": "jelovirt/pdf-generator",
"id": "36640fee3b28e0b9d7a0f7443c6252516f7293ab",
"size": "449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2125"
},
{
"name": "Java",
"bytes": "20640"
},
{
"name": "JavaScript",
"bytes": "14086"
},
{
"name": "SCSS",
"bytes": "11781"
},
{
"name": "Shell",
"bytes": "693"
},
{
"name": "TypeScript",
"bytes": "280494"
},
{
"name": "XSLT",
"bytes": "185426"
}
],
"symlink_target": ""
} |
(function () {
'use strict';
angular
.module('app')
.controller('ManageProjectController', ManageProjectController);
ManageProjectController.$inject = ['$document', '$ionicModal', '$ionicLoading', '$ionicPopover', '$ionicPopup',
'$log', '$scope', '$state', '$q', '$window', 'FormFactory', 'HelpersFactory', 'ImageFactory', 'LiveDBFactory',
'LocalStorageFactory', 'OtherMapsFactory', 'ProjectFactory', 'RemoteServerFactory', 'SpotFactory', 'UserFactory',
'IS_WEB'];
function ManageProjectController($document, $ionicModal, $ionicLoading, $ionicPopover, $ionicPopup, $log, $scope,
$state, $q, $window, FormFactory, HelpersFactory, ImageFactory, LiveDBFactory,
LocalStorageFactory, OtherMapsFactory, ProjectFactory, RemoteServerFactory,
SpotFactory, UserFactory, IS_WEB) {
var vm = this;
var downloadErrors = false;
var neededEditedImagesIds = [];
var notifyMessages = [];
var uploadErrors = false;
var user = UserFactory.getUser();
vm.activeDatasets = [];
vm.data = {};
vm.datasets = [];
vm.exportFileName = undefined;
vm.exportForDistFileName = undefined;
vm.exportForAVOFileName = undefined;
vm.exportItems = {};
vm.fileBrowserModal = {};
vm.importItem = undefined;
vm.newDatasetName = '';
vm.newProjectModal = {};
vm.otherFeatureTypes = [];
vm.popover = {};
vm.project = {};
vm.projects = [];
vm.showNewProject = false;
vm.showNewProjectDetail = false;
vm.showExitProjectModal = true;
vm.showProject = false;
vm.showProjectButtons = false;
vm.switchProjectModal = {};
vm.titleText = 'Manage Projects';
vm.areDatasetsOn = areDatasetsOn;
vm.deleteDataset = deleteDataset;
vm.deleteProject = deleteProject;
vm.deleteType = deleteType;
vm.exportAVOCSV = exportAVOCSV;
vm.exportProject = exportProject;
vm.exportProjectForDistribution = exportProjectForDistribution;
vm.filterDefaultTypes = filterDefaultTypes;
vm.getNumberOfSpots = getNumberOfSpots;
vm.goToProjectDescription = goToProjectDescription;
vm.hideLoading = hideLoading;
vm.importProject = importProject;
vm.importProjectForDistribution = importProjectForDistribution;
vm.importSelectedFile = importSelectedFile;
vm.importSelectedFileForDistribution = importSelectedFileForDistribution;
vm.initializeUpload = initializeUpload;
vm.initializeDownload = initializeDownload;
vm.isDatasetOn = isDatasetOn;
vm.isSyncReady = isSyncReady;
vm.newDataset = newDataset;
vm.newProject = newProject;
vm.selectProject = selectProject;
vm.setSpotsDataset = setSpotsDataset;
vm.startNewProject = startNewProject;
vm.switchProject = switchProject;
vm.syncDataset = syncDataset;
vm.toggleDataset = toggleDataset;
activate();
/**
* Private Functions
*/
function activate() {
initializeProject();
createPageInteractions();
ProjectFactory.setUser(user);
FormFactory.setForm('project');
if (!IS_WEB && $window.cordova) LocalStorageFactory.checkImagesDir();
if (!IS_WEB && !$window.cordova) $log.warn('Not Web but unable get image directory. Running for development?');
if (_.isEmpty(vm.project)) {
vm.showExitProjectModal = false;
var startPopupText = 'Please create a new project to continue.';
if (vm.isSyncReady()) {
var confirmPopup = $ionicPopup.confirm({
title: 'Set Your Project',
template: 'Please create a new project or open an existing project to continue.',
okText: 'Select Existing Project',
cancelText: 'Create New Project',
cancelType: 'button-positive'
});
confirmPopup.then(function (res) {
if (res) switchProject();
else startNewProject()
});
}
else {
var alertPopup = $ionicPopup.alert({
title: 'Welcome to StraboSpot',
template: 'Please press OK below and create a new project to continue.'
});
alertPopup.then(function (res) {
startNewProject()
});
}
}
}
// Make sure the date and time aren't null
// ToDo: This can be cleaned up when we no longer need date and time, just datetime
function checkValidDateTime(spot) {
if (!spot.properties.date || !spot.properties.time) {
var date = spot.properties.date || spot.properties.time;
if (!date) {
date = new Date(Date.now());
date.setMilliseconds(0);
}
spot.properties.date = spot.properties.time = date.toISOString();
SpotFactory.save(spot);
}
return spot;
}
function createPageInteractions() {
$ionicModal.fromTemplateUrl('app/project/manage/new-project-modal.html', {
'scope': $scope,
'animation': 'slide-in-up',
'backdropClickToClose': false,
'hardwareBackButtonClose': false
}).then(function (modal) {
vm.newProjectModal = modal;
});
$ionicModal.fromTemplateUrl('app/project/manage/switch-project-modal.html', {
'scope': $scope,
'animation': 'slide-in-up',
'backdropClickToClose': false,
'hardwareBackButtonClose': false
}).then(function (modal) {
vm.switchProjectModal = modal;
});
$ionicPopover.fromTemplateUrl('app/project/manage/manage-project-popover.html', {
'scope': $scope
}).then(function (popover) {
vm.popover = popover;
});
$ionicModal.fromTemplateUrl('app/project/manage/file-browser-modal.html', {
'scope': $scope,
'animation': 'slide-in-up',
'backdropClickToClose': false,
'hardwareBackButtonClose': false
}).then(function (modal) {
vm.fileBrowserModal = modal;
});
$ionicModal.fromTemplateUrl('app/project/manage/file-for-distribution-browser-modal.html', {
'scope': $scope,
'animation': 'slide-in-up',
'backdropClickToClose': false,
'hardwareBackButtonClose': false
}).then(function (modal) {
vm.fileForDistributionBrowserModal = modal;
});
// Cleanup the modal and popover when we're done with them
$scope.$on('$destroy', function () {
vm.switchProjectModal.remove();
vm.newProjectModal.remove();
vm.popover.remove();
});
}
function destroyProject() {
return ProjectFactory.destroyProject().then(function () {
return SpotFactory.clearAllSpots()/*.then(function () {
return ImageFactory.deleteAllImages();
})*/;
});
}
function downloadDataset(dataset) {
var deferred = $q.defer(); // init promise
outputMessage('Downloading Dataset ' + dataset.name + '...');
downloadSpots(dataset.id)
.then(saveSpots)
.then(gatherNeededImages)
.then(downloadImages)
.finally(function () {
if (!downloadErrors) deferred.resolve();
else deferred.reject('ERROR');
})
.catch(function (err) {
downloadErrors = true;
$log.log('Error downloading dataset.', err);
deferred.reject(err);
});
return deferred.promise;
}
function downloadImage(imageId, encodedLogin) {
var deferred = $q.defer(); // init promise
var serverURL = RemoteServerFactory.getDbUrl();
var lastOccur = serverURL.lastIndexOf("/");
var url = serverURL.substr(0, lastOccur) + '/pi/' + imageId;
//var url = 'https://strabospot.org/pi/' + imageId; //change this to look at db location
var devicePath = LocalStorageFactory.getDevicePath();
var imagesDirectory = LocalStorageFactory.getImagesDirectory();
var fileTransfer = new FileTransfer();
LocalStorageFactory.checkImagesDir().then(function () {
fileTransfer.download(url, devicePath + imagesDirectory + '/' + imageId + '.jpg', function (entry) {
console.log('download complete: ' + entry.toURL());
deferred.resolve();
}, function (error) {
$log.log('image download error: ', error);
deferred.reject(error);
});
});
return deferred.promise;
}
function downloadImages(neededImagesIds) {
if (!IS_WEB && $window.cordova && neededImagesIds.length > 0) {
var promises = [];
var imagesDownloadedCount = 0;
var imagesFailedCount = 0;
var savedImagesCount = 0;
return LocalStorageFactory.checkImagesDir().then(function () {
_.each(neededImagesIds, function (neededImageId) {
var promise = downloadImage(neededImageId, UserFactory.getUser().encoded_login)
.then(function () {
imagesDownloadedCount++;
savedImagesCount++;
notifyMessages.pop();
outputMessage(
'NEW/MODIFIED Images Downloaded: ' + imagesDownloadedCount + ' of ' + neededImagesIds.length +
'<br>NEW/MODIFIED Images Saved: ' + savedImagesCount + ' of ' + neededImagesIds.length);
}, function (err) {
imagesFailedCount++;
$log.error('Error downloading Image', neededImageId, 'Error:', err);
});
promises.push(promise);
});
return $q.all(promises).then(function () {
if (imagesFailedCount > 0) {
downloadErrors = true;
outputMessage('Image Downloads Failed: ' + imagesFailedCount);
}
});
});
}
else if (!IS_WEB && !$window.cordova && neededImagesIds.length > 0) {
$log.warn('No Cordova so unable to download images. Running for development?');
notifyMessages.pop();
outputMessage('Unable to Download Images');
}
}
function downloadProject() {
notifyMessages = ['<ion-spinner></ion-spinner><br>Downloading Project...'];
$ionicLoading.show({'template': notifyMessages});
return ProjectFactory.loadProjectRemote(vm.project).then(function () {
var deferred = $q.defer();
var currentRequest = 0;
// Download datasets synchronously
function makeNextRequest() {
downloadDataset(vm.activeDatasets[currentRequest]).then(function () {
currentRequest++;
if (currentRequest > 0 && currentRequest < vm.activeDatasets.length) {
notifyMessages.push('------------------------');
$ionicLoading.show({'template': notifyMessages.join('<br>')});
}
if (currentRequest < vm.activeDatasets.length) makeNextRequest();
else deferred.resolve();
}, function (err) {
deferred.reject(err);
});
}
if (currentRequest < vm.activeDatasets.length) makeNextRequest();
else deferred.resolve();
return deferred.promise;
});
}
function downloadSpots(datasetId) {
notifyMessages.push('Downloading Spots ...');
return RemoteServerFactory.getDatasetSpots(datasetId, UserFactory.getUser().encoded_login)
.then(function (response) {
$log.log('Get DatasetSpots Response:', response);
notifyMessages.pop();
outputMessage('Downloaded Spots');
var spots = {};
if (response.data && response.data.features) spots = response.data.features;
return {'spots': spots, 'datasetId': datasetId}
}, function (err) {
downloadErrors = true;
notifyMessages.pop();
outputMessage('Error Downloading Spots');
if (err.statusText) outputMessage('Server Error: ' + err.statusText);
throw err;
});
}
function exportData() {
var deferred = $q.defer(); // init promise
var dateString = ProjectFactory.getTimeStamp();
vm.exportFileName = dateString + '_' + vm.project.description.project_name.replace(/\s/g, '');
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="vm.exportFileName">',
title: 'Confirm or Change File Name',
subTitle: 'If you change the file name please do not use spaces, special characters (except a dash or underscore) or add a file extension.',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function (e) {
if (!vm.exportFileName) e.preventDefault();
else return vm.exportFileName = vm.exportFileName.replace(/[^\w- ]/g, '');
}
}
]
});
myPopup.then(function (res) {
if (res) {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Exporting Project Text Data...'});
LocalStorageFactory.exportProject(vm.exportFileName).then(function (filePath) {
$ionicPopup.alert({
'title': 'Success!',
'template': 'Project text data written to ' + filePath
}).then(function () {
deferred.resolve();
});
}, function (err) {
$ionicPopup.alert({
'title': 'Error!',
'template': 'Error exporting project text data. ' + err + ' Ending export.'
}).then(function () {
deferred.reject();
});
}).finally(function () {
$ionicLoading.hide();
});
}
});
return deferred.promise;
}
function exportDataForDistribution() {
var deferred = $q.defer(); // init promise
var dateString = ProjectFactory.getTimeStamp();
vm.exportForDistFileName = dateString + '_' + vm.project.description.project_name.replace(/\s/g, '');
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="vm.exportForDistFileName">',
title: 'Confirm or Change Folder Name',
subTitle: 'If you change the folder name please do not use spaces, special characters (except a dash or underscore) or add a file extension.',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function (e) {
if (!vm.exportForDistFileName) e.preventDefault();
else return vm.exportForDistFileName = vm.exportForDistFileName.replace(/[^\w- ]/g, '');
}
}
]
});
myPopup.then(function (res) {
if (res) {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Exporting Data...'});
LocalStorageFactory.exportProjectForDistribution(vm.exportForDistFileName).then(function (filePath) {
$ionicPopup.alert({
'title': 'Success!',
'template': 'Project data written to ' + filePath
}).then(function () {
deferred.resolve();
});
}, function (err) {
$ionicPopup.alert({
'title': 'Error!',
'template': 'Error exporting project data. ' + err + ' Ending export.'
}).then(function () {
deferred.reject();
});
}).finally(function () {
$ionicLoading.hide();
});
}
});
return deferred.promise;
}
function exportProjectForDistribution() {
vm.popover.hide().then(function () {
exportDataForDistribution();
});
}
function exportDataForAVOCSV() {
var deferred = $q.defer(); // init promise
var dateString = ProjectFactory.getTimeStamp();
vm.exportForAVOFileName = dateString + '_' + vm.project.description.project_name.replace(/\s/g, '');
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="vm.exportForAVOFileName">',
title: 'Confirm or Change CSV File Name',
subTitle: 'If you change the file name please do not use spaces, special characters (except a dash or underscore) or add a file extension.',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function (e) {
if (!vm.exportForAVOFileName) e.preventDefault();
else return vm.exportForAVOFileName = vm.exportForAVOFileName.replace(/[^\w- ]/g, '');
}
}
]
});
myPopup.then(function (res) {
if (res) {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Exporting Data...'});
LocalStorageFactory.exportProjectForAVO(vm.exportForAVOFileName).then(function (filePath) {
var templateText = "";
if (LocalStorageFactory.getDeviceName() == "iOS") {
templateText = 'AVO data has been written to /StraboCSV/' + filePath + '.csv and data has been copied to clipboard.';
}
else templateText = 'AVO data has been written to /StraboCSV/' + filePath + '.csv';
$ionicPopup.alert({
'title': 'Success!',
'template': templateText
}).then(function () {
deferred.resolve();
});
}, function (err) {
$ionicPopup.alert({
'title': 'Error!',
'template': 'Error exporting CSV data. ' + err + ''
}).then(function () {
deferred.reject();
});
}).finally(function () {
$ionicLoading.hide();
});
}
});
return deferred.promise;
}
function exportAVOCSV() {
vm.popover.hide().then(function () {
exportDataForAVOCSV();
});
}
// Determine which images aren't already on the device and need to be downloaded
function gatherNeededImages(spots) {
var neededImagesIds = [];
if (!IS_WEB && $window.cordova) {
var promises = [];
outputMessage('Determining needed images...');
_.each(spots, function (spot) {
if (spot.properties.images) {
_.each(spot.properties.images, function (image) {
var promise = LocalStorageFactory.getImageById(image.id)
.then(function (src) {
if (src === 'img/image-not-found.png') {
$log.log('Need to download image', image.id);
neededImagesIds.push(image.id);
}
else $log.log('Image', image.id, 'already exists on device. Not downloading.');
});
promises.push(promise);
});
}
});
return Promise.all(promises).then(function () {
notifyMessages.pop();
outputMessage('NEW images to download: ' + neededImagesIds.length +
'<br> MODIFIED images to download: ' + neededEditedImagesIds.length);
neededImagesIds = _.union(neededImagesIds, neededEditedImagesIds);
return Promise.resolve(neededImagesIds);
});
}
else if (!IS_WEB && !$window.cordova) {
$log.warn('No Cordova so unable to download images. Running for development?');
notifyMessages.pop();
outputMessage('Unable to Download Images');
return Promise.resolve(neededImagesIds);
}
}
function importData() {
vm.fileNames = [];
LocalStorageFactory.gatherLocalFiles().then(function (entries) {
//$log.log(entries);
_.each(_.pluck(entries, 'name'), function (file) {
if (file.endsWith('.json')) vm.fileNames.push(file.split('.')[0]);
});
if (!_.isEmpty(vm.fileNames)) vm.fileBrowserModal.show();
else {
$ionicPopup.alert({
'title': 'Files Not Found!',
'template': 'No valid files to import found. Export a file first.'
});
}
}, function (err) {
if (err === 1) {
$ionicPopup.alert({
'title': 'Import Folder Not Found!',
'template': 'The StraboSpot folder was not found. Export a file first or create this folder and add a valid project file.'
});
}
else {
$ionicPopup.alert({
'title': 'Error!',
'template': 'Error finding local files. Error code: ' + err
});
}
});
}
function importDataForDistribution() {
vm.fileForDistributionNames = [];
LocalStorageFactory.gatherLocalDistributionFiles().then(function (entries) {
$log.log("Distributed Files: ", entries);
_.each(_.pluck(entries, 'name'), function (file) {
if (file.charAt(0) != '.') {
vm.fileForDistributionNames.push(file);
}
});
if (!_.isEmpty(vm.fileForDistributionNames)) vm.fileForDistributionBrowserModal.show();
else {
$ionicPopup.alert({
'title': 'Files Not Found!',
'template': 'No valid files to import found. Export a file first.'
});
}
}, function (err) {
if (err === 1) {
$ionicPopup.alert({
'title': 'Import Folder Not Found!',
'template': 'The StraboSpot folder was not found. Export a file first or create this folder and add a valid project file.'
});
}
else {
$ionicPopup.alert({
'title': 'Error!',
'template': 'Error finding local files. Error code: ' + err
});
}
});
}
function initializeDownloadDataset(dataset) {
downloadErrors = false;
// Make sure dataset exists on server first (ie. it is not a new dataset)
RemoteServerFactory.getDataset(dataset.id, UserFactory.getUser().encoded_login).then(function () {
notifyMessages = [];
notifyMessages = ['<ion-spinner></ion-spinner>'];
$ionicLoading.show({'template': notifyMessages});
downloadDataset(dataset).then(function () {
notifyMessages.splice(0, 1);
if (!downloadErrors) outputMessage('<br>Dataset Updated Successfully!');
else outputMessage('<br>Errors Updating Dataset!');
setSpotsDataset();
}, function (err) {
notifyMessages.splice(0, 1);
outputMessage('<br>Error Updating Dataset! Error: ' + err);
}).finally(function () {
$ionicLoading.show({
scope: $scope, template: notifyMessages.join('<br>') + '<br><br>' +
'<a class="button button-clear button-outline button-light" ng-click="vm.hideLoading()">OK</a>'
});
});
}, function () {
setSpotsDataset();
});
}
function initializeProject() {
$ionicLoading.show();
vm.project = ProjectFactory.getCurrentProject();
vm.datasets = ProjectFactory.getCurrentDatasets();
vm.activeDatasets = ProjectFactory.getActiveDatasets();
vm.spotsDataset = ProjectFactory.getSpotsDataset();
vm.otherFeatureTypes = ProjectFactory.getOtherFeatures();
if (areDatasetsOn() && _.isEmpty(vm.spotsDataset)) {
ProjectFactory.saveSpotsDataset(vm.activeDatasets[0]);
vm.spotsDataset = ProjectFactory.getSpotsDataset();
}
vm.showProject = !_.isEmpty(vm.project);
$ionicLoading.hide();
}
function loadProjectRemote(project) {
$ionicLoading.show();
destroyProject().then(function () {
ProjectFactory.loadProjectRemote(project).then(function () {
vm.switchProjectModal.hide();
initializeProject();
}, function (err) {
$ionicPopup.alert({
'title': 'Error communicating with server!',
'template': err
});
$ionicLoading.hide();
});
}, function () {
$ionicLoading.hide();
});
}
function outputMessage(msg) {
notifyMessages.push(msg);
$ionicLoading.show({'template': notifyMessages.join('<br>')});
}
function reloadProject() {
$log.log('Reloading project ...');
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Reloading Project..'});
ProjectFactory.prepProject().then(function () {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Reloaded Project<br>Loading Spots...'});
SpotFactory.loadSpots().then(function () {
$ionicLoading.hide();
$ionicPopup.alert({
'title': 'Success!',
'template': 'Finished importing project.'
});
$state.reload();
});
});
}
function saveSpot(spot, datasetId) {
// If the geometry coordinates contain any null values, delete the geometry; it shouldn't be defined
if (spot.geometry && spot.geometry.coordinates) {
if (_.indexOf(_.flatten(spot.geometry.coordinates), null) !== -1) {
delete spot.geometry;
}
}
return SpotFactory.saveDownloadedSpot(spot).then(function () {
ProjectFactory.addSpotToDataset(spot.properties.id, datasetId);
});
}
function saveSpots(data) {
var spots = data.spots;
var datasetId = data.datasetId;
var originalSpotsIds = ProjectFactory.getSpotIds()[datasetId];
//$log.log(spots);
var promises = [];
var spotsNeededCount = 0;
var spotsSavedCount = 0;
$ionicLoading.show({'template': notifyMessages.join('<br>')});
_.each(spots, function (spot) {
// Only need to save Spot if downloaded Spot differs from local Spot
var savedSpot = SpotFactory.getSpotById(spot.properties.id);
if (!_.isEqual(spot, savedSpot)) {
$log.log('New/Modified Spot:', spot);
spotsNeededCount++;
// Check for edited Images that need to be downloaded
if (savedSpot && spot.properties.images && savedSpot.properties.images) {
_.each(spot.properties.images, function (image) {
var editedImageProps = _.find(savedSpot.properties.images, function (savedImage) {
return savedImage.id && image.id && savedImage.id === image.id && image.modified_timestamp
&& savedImage.modified_timestamp && image.modified_timestamp > savedImage.modified_timestamp;
});
if (editedImageProps) neededEditedImagesIds.push(editedImageProps.id);
});
}
var promise = saveSpot(spot, datasetId)
.then(function () {
spotsSavedCount++;
notifyMessages.pop();
outputMessage('NEW/MODIFIED Spots Saved: ' + spotsSavedCount + ' of ' + spotsNeededCount);
});
promises.push(promise);
}
});
outputMessage('NEW/MODIFIED Spots to save: ' + spotsNeededCount);
return $q.all(promises).then(function () {
$log.log('Finished saving Spots');
// Delete Spots for this dataset that are stored locally but are not on the server
var downloadedSpotsIds = _.map(spots, function (spot) {
return spot.properties.id;
});
var spotsToDestroyIds = _.difference(originalSpotsIds, downloadedSpotsIds);
if (spotsToDestroyIds.length > 0) $log.log('Spots to destroy bc they are not on server', spotsToDestroyIds);
_.each(spotsToDestroyIds, function (spotToDestroyId) {
SpotFactory.destroy(spotToDestroyId);
});
return spots;
});
}
function upload() {
notifyMessages = ['<ion-spinner></ion-spinner><br>'];
return uploadProject()
.then(uploadDatasets)
.catch(function (err) {
$log.error('Upload errors');
uploadErrors = true;
throw err;
});
}
function uploadDataset(dataset) {
var deferred = $q.defer(); // init promise
outputMessage('Uploading Dataset ' + dataset.name + '...');
var project = ProjectFactory.getCurrentProject();
RemoteServerFactory.updateDataset(dataset, UserFactory.getUser().encoded_login)
.then(function (response) {
$log.log('Finished updating dataset', dataset, '. Response:', response);
RemoteServerFactory.addDatasetToProject(project.id, dataset.id, UserFactory.getUser().encoded_login)
.then(function (response2) {
$log.log('Finished adding dataset to project', project, '. Response:', response2);
uploadSpots(dataset).then(function () {
$log.log('Uploaded Spots');
deferred.resolve();
}, function () {
$log.log('Error uploading Spots');
deferred.reject();
});
},
function (err) {
uploadErrors = true;
$log.error('Error adding dataset to project. Response:', err);
outputMessage('Error Updating Dataset.');
if (err.statusText) outputMessage('Server Error: ' + err.statusText);
deferred.reject();
});
}, function (err) {
uploadErrors = true;
$log.log('Error updating dataset');
outputMessage('Error Updating Dataset.');
if (err.statusText) outputMessage('Server Error: ' + err.statusText);
deferred.reject();
});
return deferred.promise;
}
function uploadDatasets() {
var deferred = $q.defer(); // init promise
var datasets = ProjectFactory.getActiveDatasets();
var currentRequest = 0;
// Upload datasets synchronously
function makeNextRequest() {
uploadDataset(datasets[currentRequest]).then(function () {
currentRequest++;
if (currentRequest > 0 && currentRequest < datasets.length) {
notifyMessages.push('------------------------');
$ionicLoading.show({'template': notifyMessages.join('<br>')});
}
if (currentRequest < datasets.length) makeNextRequest();
else deferred.resolve();
}, function () {
$log.error('Error uploading dataset.');
deferred.reject('Error uploading dataset.');
});
}
if (currentRequest < datasets.length) makeNextRequest();
else deferred.resolve();
return deferred.promise;
}
function uploadImages(spots) {
return new Promise(function (resolve, reject1) {
spots = _.values(spots);
var imagesToUploadCount = 0;
var imagesUploadedCount = 0;
var imagesUploadFailedCount = 0;
var iSpotLoop = 0;
var iImagesLoop = 0;
outputMessage('Gathering Images to Upload...');
function areMoreImages(spot) {
return _.has(spot, 'properties') && _.has(spot.properties,
'images') && iImagesLoop < spot.properties.images.length;
}
function areMoreSpots() {
return iSpotLoop + 1 < spots.length;
}
// Upload images synchronously
function makeNextSpotRequest(spot) {
if (areMoreImages(spot)) {
$log.log('Found image:', spot.properties.images[iImagesLoop].id, spot.properties.images[iImagesLoop],
'in Spot:', spot);
makeNextImageRequest(spot.properties.images[iImagesLoop]).then(function () {
makeNextSpotRequest(spots[iSpotLoop]);
});
}
else if (areMoreSpots()) {
iSpotLoop++;
iImagesLoop = 0;
makeNextSpotRequest(spots[iSpotLoop]);
}
else {
if (imagesToUploadCount === 0) {
notifyMessages.pop();
outputMessage('No NEW Images to Upload');
}
else {
outputMessage('Finished Uploading Images');
if (imagesUploadFailedCount > 0) outputMessage('Images Failed: ' + imagesUploadFailedCount);
}
resolve();
}
}
function makeNextImageRequest(imageProps) {
return shouldUploadImage(imageProps)
.then(getImageFile)
.then(convertImageFile)
.then(uploadImage)
.catch(function (err) {
if (err !== 'already exists') {
uploadErrors = true;
imagesUploadFailedCount++;
$log.error(err);
}
})
.finally(function () {
iImagesLoop++;
return Promise.resolve();
})
}
function shouldUploadImage(imageProps) {
return RemoteServerFactory.verifyImageExistance(imageProps.id, UserFactory.getUser().encoded_login)
.then(function (response) {
if (response.data
&& ((response.data.modified_timestamp && imageProps.modified_timestamp
&& imageProps.modified_timestamp > response.data.modified_timestamp)
|| (!response.data.modified_timestamp && imageProps.modified_timestamp))) {
$log.log('Need to upload image:', imageProps.id);
imagesToUploadCount++;
notifyMessages.pop();
return Promise.resolve(imageProps);
}
else {
$log.log('No need to upload image:', imageProps.id, 'Server response:', response);
return Promise.reject('already exists');
}
}, function () {
$log.log('Need to upload image:', imageProps.id);
imagesToUploadCount++;
notifyMessages.pop();
return Promise.resolve(imageProps);
});
}
function getImageFile(imageProps) {
outputMessage('Processing image...');
$log.log('Getting file URI ...');
return ImageFactory.getImageFileURIById(imageProps.id).then(function (src) {
if (src !== 'img/image-not-found.png') {
$log.log('Got file URI for image', imageProps.id, src);
return Promise.resolve([imageProps, src]);
}
else return Promise.reject('Local file not found for image', imageProps.id);
}, function () {
return Promise.reject('Local file not found for image', imageProps.id);
});
}
function convertImageFile(data) {
var imageProps = data[0];
var src = data[1];
$log.log('Converting file URI to Blob...');
return HelpersFactory.fileURItoBlob(src).then(function (blob) {
$log.log('Finished converting file URI to blob for image', imageProps.id);
return Promise.resolve([imageProps, blob]);
}, function () {
return Promise.reject('Error converting file URI to blob for image', imageProps.id);
});
}
function uploadImage(data) {
var imageProps = data[0];
var blob = data[1];
notifyMessages.pop();
var count = imagesUploadedCount + 1;
outputMessage('Uploading image ' + count + '...');
$log.log('Uploading image', imageProps.id, 'to server...');
return RemoteServerFactory.uploadImage(imageProps, blob, UserFactory.getUser().encoded_login).then(function () {
imagesUploadedCount++;
notifyMessages.pop();
outputMessage('Images Uploaded: ' + imagesUploadedCount);
$log.log('Finished uploading image', imageProps.id, 'to the server');
return Promise.resolve();
}, function () {
return Promise.reject('Error uploading image', imageProps.id);
});
}
if (iSpotLoop < spots.length) makeNextSpotRequest(spots[iSpotLoop]);
else resolve();
});
}
function uploadProject() {
var deferred = $q.defer(); // init promise
var project = angular.fromJson(angular.toJson(ProjectFactory.getCurrentProject()));
if (!_.isEmpty(OtherMapsFactory.getOtherMaps())) project.other_maps = OtherMapsFactory.getOtherMaps();
RemoteServerFactory.updateProject(project, UserFactory.getUser().encoded_login).then(
function (response) {
$log.log('Finished uploading project', project, '. Response:', response);
notifyMessages.push('Uploaded project properties.');
$ionicLoading.show({'template': notifyMessages.join('<br>')});
deferred.resolve();
},
function (response) {
uploadErrors = true;
$log.log('Error uploading project', project, '. Response:', response);
if (response.data && response.data.Error) deferred.reject(response.data.Error);
deferred.reject();
});
return deferred.promise;
}
function uploadSpots(dataset) {
var spots = SpotFactory.getSpotsByDatasetId(dataset.id);
var totalSpotCount = _.size(spots);
_.each(spots, function (spot) {
spot = checkValidDateTime(spot);
// ToDo: With new image database src isn't supposed to be in Spot but leave this code for now just in case
_.each(spot.properties.images, function (image, i) {
spot.properties.images[i] = _.omit(image, 'src');
});
});
if (_.isEmpty(spots)) {
outputMessage('No Spots to Upload');
return $q.when(null);
}
else {
// Create a feature collection of spots to upload for this dataset
var spotCollection = {
'type': 'FeatureCollection',
'features': _.values(spots)
};
outputMessage('Uploading ' + totalSpotCount + ' Spots...');
return RemoteServerFactory.updateDatasetSpots(dataset.id, spotCollection, UserFactory.getUser().encoded_login)
.then(function () {
notifyMessages.pop();
outputMessage('Finished Uploading ' + totalSpotCount + ' Spots');
return uploadImages(spots);
}, function (err) {
uploadErrors = true;
outputMessage('Error updating Spots in dataset' + dataset.name);
if (err && err.data && err.data.Error) $log.error(err.data.Error);
if (err && err.statusText) outputMessage('Server Error: ' + err.statusText);
return Promise.reject('Error updating Spots in dataset');
});
}
}
/**
* Public Functions
*/
function areDatasetsOn() {
return !_.isEmpty(vm.activeDatasets);
}
function deleteDataset(dataset) {
var remainingActiveDatasets = _.reject(vm.activeDatasets, function (activeDataset) {
return activeDataset.id === dataset.id;
});
if (_.isEmpty(remainingActiveDatasets)) {
$ionicPopup.alert({
'title': 'Too Few Active Datasets!',
'template': 'You must set another active dataset before you delete the dataset ' + dataset.name + '.'
});
}
else {
var confirmPopup = $ionicPopup.confirm({
'title': 'Delete Dataset Warning!',
'template': 'Are you sure you want to <span style="color:red">DELETE</span> the Dataset' +
' <b>' + dataset.name + '</b>? This will also delete the Spots in this dataset.',
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) {
ProjectFactory.destroyDataset(dataset).then(function (spotsToDestroy) {
_.each(spotsToDestroy, function (spotToDestroy) {
SpotFactory.destroy(spotToDestroy);
});
initializeProject();
});
}
});
}
}
function deleteProject(project) {
var confirmPopup = $ionicPopup.confirm({
'title': 'Delete Project Warning!',
'template': 'Are you sure you want to <span style="color:red">DELETE</span> the project' +
' <b>' + project.name + '</b>. This will also delete all datasets and Spots contained within the project.',
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) {
RemoteServerFactory.deleteProject(project.id, UserFactory.getUser().encoded_login).then(function () {
if (vm.project.id === project.id) {
destroyProject().then(function () {
initializeProject();
});
}
ProjectFactory.loadProjectsRemote().then(function (projects) {
vm.projects = projects;
}, function (err) {
$ionicPopup.alert({
'title': 'Error communicating with server!',
'template': err
});
});
});
}
});
}
function deleteType(i) {
var customTypes = _.reject(vm.otherFeatureTypes, function (type) {
return _.contains(ProjectFactory.getDefaultOtherFeatureTypes(), type);
});
var usedType = _.filter(SpotFactory.getSpots(), function (spot) {
if (spot.properties.other_features) {
return _.find(spot.properties.other_features, function (otherFeature) {
return otherFeature.type === customTypes[i];
}) || false;
}
return false;
});
var spotNames = [];
_.each(usedType, function (spot) {
spotNames.push(spot.properties.name);
});
if (usedType.length === 1) {
$ionicPopup.alert({
'title': 'Type in Use',
'template': 'This type is used in the following Spot. Please remove the type from this Spot before' +
' deleting this type. Spot: ' + spotNames.join(', ')
});
}
else if (usedType.length > 1) {
$ionicPopup.alert({
'title': 'Type in Use',
'template': 'This type is used in the following Spots. Please remove the type from these Spots before' +
' deleting this type. Spots: ' + spotNames.join(', ')
});
}
else {
ProjectFactory.destroyOtherFeature(i + ProjectFactory.getDefaultOtherFeatureTypes().length - 1);
}
}
function doCreateNewProject() {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner>'});
destroyProject().then(function () {
ProjectFactory.createNewProject(vm.data).then(function () {
$log.log('Save Project to LiveDB:', ProjectFactory.getCurrentProject());
LiveDBFactory.save(null, ProjectFactory.getCurrentProject(), ProjectFactory.getSpotsDataset());
$ionicLoading.hide();
vm.newProjectModal.hide();
initializeProject();
});
});
}
function exportProject() {
vm.popover.hide().then(function () {
exportData();
});
}
function filterDefaultTypes(type) {
return _.indexOf(ProjectFactory.getDefaultOtherFeatureTypes(), type) === -1;
}
function getNumberOfSpots(dataset) {
var spots = ProjectFactory.getSpotIds()[dataset.id];
if (_.isEmpty(spots)) return '(0 Spots)';
else if (spots.length === 1) return '(1 Spot)';
return '(' + spots.length + ' Spots)';
}
function goToProjectDescription() {
$state.go('app.description');
}
function hideLoading() {
$ionicLoading.hide();
}
function importProject() {
vm.popover.hide().then(function () {
importData();
});
}
function importProjectForDistribution() {
vm.popover.hide().then(function () {
importDataForDistribution();
});
}
function importSelectedFile(name) {
vm.fileBrowserModal.hide().then(function () {
var confirmPopup = $ionicPopup.confirm({
'title': 'Warning!!!',
'template': 'This will <span style="color:red">OVERWRITE</span> the current open project. Do you want to continue?',
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Destroying Current Project..'});
$log.log('Destroying current project ...');
var promises = [];
promises.push(ProjectFactory.destroyProject());
promises.push(SpotFactory.clearAllSpots());
//promises.push(ImageFactory.deleteAllImages());
$q.all(promises).then(function () {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Importing Project..'});
LocalStorageFactory.importProject(name + '.json').then(function () {
reloadProject();
}, function (err) {
$ionicLoading.hide();
$ionicPopup.alert({
'title': 'Error!',
'template': 'Error importing project. ' + err
});
});
});
}
});
});
}
function importSelectedFileForDistribution(name) {
vm.fileForDistributionBrowserModal.hide().then(function () {
var confirmPopup = $ionicPopup.confirm({
'title': 'Warning!!!',
'template': 'This will <span style="color:red">OVERWRITE</span> the current open project. Do you want to continue?',
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Destroying Current Project..'});
$log.log('Destroying current project ...');
var promises = [];
promises.push(ProjectFactory.destroyProject());
promises.push(SpotFactory.clearAllSpots());
//promises.push(ImageFactory.deleteAllImages());
$q.all(promises).then(function () {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Importing Project..'});
LocalStorageFactory.importProjectForDistribution(name).then(function () {
reloadProject();
}, function (err) {
$ionicLoading.hide();
$ionicPopup.alert({
'title': 'Error!',
'template': 'Error importing project. ' + err
});
});
});
}
});
});
}
function initializeDownload() {
vm.popover.hide().then(function () {
downloadErrors = false;
var downloadConfirmText = '';
if (_.isEmpty(vm.activeDatasets)) {
downloadConfirmText = 'No active datasets to download! Only the project properties will be downloaded and will ' +
'<span style="color:red">OVERWRITE</span> the properties for the current open project. Continue?'
}
else {
var names = _.pluck(vm.activeDatasets, 'name');
downloadConfirmText = 'Project properties and datasets <b>' + names.join(', ') + '</b> will be downloaded' +
' and will <span style="color:red">OVERWRITE</span> the current open project properties and selected' +
' datasets. Continue?';
}
var confirmPopup = $ionicPopup.confirm({
'title': 'Download Warning!',
'template': downloadConfirmText,
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) {
downloadProject().then(function () {
notifyMessages.splice(0, 1);
if (!downloadErrors) outputMessage('<br>Project Updated Successfully!');
else outputMessage('<br>Errors Updating Project!');
initializeProject();
}, function (err) {
notifyMessages.splice(0, 1);
outputMessage('<br>Error Updating Project! Error: ' + err);
}).finally(function () {
$ionicLoading.show({
scope: $scope, template: notifyMessages.join('<br>') + '<br><br>' +
'<a class="button button-clear button-outline button-light" ng-click="vm.hideLoading()">OK</a>'
});
});
}
});
});
}
function initializeUpload() {
vm.popover.hide().then(function () {
var deferred = $q.defer(); // init promise
uploadErrors = false;
var uploadConfirmText = '';
if (_.isEmpty(vm.activeDatasets)) {
uploadConfirmText = 'No active datasets to upload! Only the project properties will be uploaded and will ' +
'<span style="color:red">OVERWRITE</span> the properties for this project on the server. Continue?';
}
else {
var names = _.pluck(vm.activeDatasets, 'name');
uploadConfirmText = 'Project properties and the active datasets <b>' + names.join(', ') + '</b> will be' +
' uploaded and will <span style="color:red">OVERWRITE</span> the project properties and selected' +
' datasets on the server. Continue?'
}
var confirmPopup = $ionicPopup.confirm({
'title': 'Upload Warning!',
'template': uploadConfirmText,
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) {
notifyMessages = [];
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Uploading...'});
upload().then(function () {
notifyMessages.splice(0, 1); // Remove spinner
if (uploadErrors) outputMessage('<br>Project Finished Uploading but with Errors!');
else outputMessage('<br>Project Uploaded Successfully!');
deferred.resolve();
}, function (err) {
notifyMessages.splice(0, 1); // Remove spinner
outputMessage('<br>Error Uploading Project!');
if (err) outputMessage('Server Error: ' + err);
deferred.reject();
}).finally(function () {
$ionicLoading.show({
scope: $scope, template: notifyMessages.join('<br>') + '<br><br>' +
'<a class="button button-clear button-outline button-light" ng-click="vm.hideLoading()">OK</a>'
});
});
}
else deferred.resolve();
});
return deferred.promise;
});
}
function isDatasetOn(dataset) {
return _.find(vm.activeDatasets, function (datasetOn) {
return datasetOn.id === dataset.id;
});
}
function isSyncReady() {
return ProjectFactory.isSyncReady();
}
function newDataset() {
var myPopup = $ionicPopup.show({
'template': '<input type="text" ng-model="vm.newDatasetName">',
'title': 'Enter a name for this Dataset',
'scope': $scope,
'buttons': [{
'text': 'Cancel'
}, {
'text': '<b>Save</b>',
'type': 'button-positive',
'onTap': function (e) {
if (!vm.newDatasetName) {
// Don't allow the user to close unless a name is entered
e.preventDefault();
}
else return vm.newDatasetName;
}
}]
});
myPopup.then(function (res) {
if (res) {
ProjectFactory.createNewDataset(vm.newDatasetName);
vm.newDatasetName = '';
vm.datasets = ProjectFactory.getCurrentDatasets();
}
});
}
function newProject() {
if (_.isEmpty(vm.data.project_name)) {
var formCtrl = angular.element(document.getElementById('straboFormCtrlId')).scope();
var ele = $document[0].getElementById("project_name");
ele.html = "Unnamed Project";
var formEle = formCtrl.straboForm[ele.id];
formEle.$valid = true;
vm.data.project_name = "Unnamed Project";
}
var valid = FormFactory.validate(vm.data);
if (valid) doCreateNewProject();
}
function selectProject(project) {
$log.log('Selected:', project);
if (_.isEmpty(vm.project)) loadProjectRemote(project);
else {
var confirmPopup = $ionicPopup.confirm({
'title': 'Delete Local Project Warning!',
'template': 'Switching projects will <span style="color:red">DELETE</span> the local copy of the' +
' current project <b>' + vm.project.description.project_name + '</b> including all datasets and Spots' +
' contained within this project. Make sure you have already uploaded the project to the server if you' +
' wish to preserve the data. Continue?',
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) loadProjectRemote(project);
});
}
}
function setSpotsDataset() {
// Check if the dataset for spots is still in the datasets that are on
var found = _.find(vm.activeDatasets, function (datasetOn) {
return vm.spotsDataset.id === datasetOn.id;
});
// If not set the dataset for spots as the Default Dataset
if (!found) vm.spotsDataset = vm.activeDatasets[0];
ProjectFactory.saveSpotsDataset(vm.spotsDataset);
}
function startNewProject() {
vm.popover.hide().then(function () {
vm.data = {};
vm.showExitProjectModal = false;
if (_.isEmpty(vm.project) || !_.has(vm.project.description, 'project_name')) vm.newProjectModal.show();
else {
vm.showExitProjectModal = true;
var confirmText = 'Creating a new project will <span style="color:red">DELETE</span> the local copy of the' +
' current project <b>' + vm.project.description.project_name + '</b> including all datasets and Spots' +
' contained within this project.';
if (ProjectFactory.isSyncReady()) {
confirmText += ' Make sure you have already uploaded the project to the server if you wish to preserve the' +
' data. Continue?';
}
else {
confirmText += ' Create an account and log in to upload the project to the server if you wish preserve' +
' the data. Continue';
}
var confirmPopup = $ionicPopup.confirm({
'title': 'Delete Local Project Warning!',
'template': confirmText,
'cssClass': 'warning-popup'
});
confirmPopup.then(function (res) {
if (res) vm.newProjectModal.show();
});
}
});
}
function switchProject() {
vm.popover.hide().then(function () {
$ionicLoading.show({'template': '<ion-spinner></ion-spinner><br>Getting Projects from Server ...'});
ProjectFactory.loadProjectsRemote().then(function (projects) {
vm.projects = projects;
vm.switchProjectModal.show();
}, function (err) {
$ionicPopup.alert({
'title': 'Error communicating with server!',
'template': err
});
}).finally(function () {
$ionicLoading.hide();
});
});
}
function syncDataset(i) {
if (vm.datasets[i].sync) {
$log.log('Turn ON dataset sync for:', vm.datasets[i]);
}
else {
$log.log('Turn OFF dataset sync for:', vm.datasets[i]);
}
}
function toggleDataset(datasetToggled) {
// Toggled Off - remove dataset from the list of active datasets
var found = _.find(vm.activeDatasets, function (datasetOn) {
return datasetOn.id === datasetToggled.id;
});
if (found) {
vm.activeDatasets = _.reject(vm.activeDatasets, function (datasetOn) {
return datasetOn.id === datasetToggled.id;
});
setSpotsDataset();
}
// Toggled On - add dataset to the list of active datasets
else {
vm.activeDatasets.push(datasetToggled);
if (_.isEmpty(ProjectFactory.getSpotIds()[datasetToggled.id]) &&
!_.isEmpty(UserFactory.getUser()) && navigator.onLine) {
initializeDownloadDataset(datasetToggled);
}
else if (_.isEmpty(ProjectFactory.getSpotIds()[datasetToggled.id]) &&
!_.isEmpty(UserFactory.getUser()) && !navigator.onLine) {
$ionicPopup.alert({
'title': 'Cannot Update Dataset!',
'template': 'Unable to reach the server to check if there are already Spots in this dataset to download.'
});
}
}
ProjectFactory.saveActiveDatasets(vm.activeDatasets);
}
}
}());
| {
"content_hash": "bda5796ac49b28b390e767d401d9e89b",
"timestamp": "",
"source": "github",
"line_count": 1468,
"max_line_length": 150,
"avg_line_length": 38.55722070844686,
"alnum_prop": 0.5720645913571959,
"repo_name": "StraboSpot/strabo-mobile",
"id": "7f57088838d069c95bfea4f7dbcbc61b93807ec3",
"size": "56602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/app/project/manage/manage-project.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "285781"
},
{
"name": "HTML",
"bytes": "276810"
},
{
"name": "JavaScript",
"bytes": "4437713"
}
],
"symlink_target": ""
} |
package com.pratamawijaya.example_gson;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | {
"content_hash": "b91ea46f2a4626dd2593199c3d6ac9a6",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 93,
"avg_line_length": 27.76923076923077,
"alnum_prop": 0.7534626038781164,
"repo_name": "pratamawijaya/example",
"id": "cfa362672b25b40b06dc77bbbc1727d70ad2669c",
"size": "361",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Example_Gson/app/src/androidTest/java/com/pratamawijaya/example_gson/ApplicationTest.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "636411"
},
{
"name": "Kotlin",
"bytes": "10131"
}
],
"symlink_target": ""
} |
using System.Xml.Serialization;
namespace MusicBeePlugin.Ampache
{
[XmlRoot("song")]
public class Song
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("art")]
public string ArtworkUrl { get; set; }
[XmlElement("artist")]
public ArtistReference Artist { get; set; }
[XmlElement("album")]
public AlbumReference Album { get; set; }
[XmlElement("composer")]
public string Composer { get; set; }
[XmlElement("comment")]
public string Comment { get; set; }
[XmlElement("publisher")]
public string Publisher { get; set; }
[XmlElement("language")]
public string Language { get; set; }
[XmlElement("filename")]
public string FilePath { get; set; }
[XmlElement("tag")]
TagReference[] Tags { get; set; }
[XmlElement("track")]
public int Track { get; set; }
[XmlElement("time")]
public int TimeSeconds { get; set; }
[XmlElement("size")]
public int SizeBytes { get; set; }
[XmlElement("year")]
public int? Year { get; set; }
[XmlElement("bitrate")]
public int BitRate { get; set; }
[XmlElement("rate")]
public int SampleRate { get; set; }
[XmlElement("mode")]
public string EncodingMode { get; set; }
[XmlElement("mime")]
public string MimeType { get; set; }
[XmlElement("channels")]
public string Channels { get; set; }
[XmlElement("mbid")]
public string MBID { get; set; }
[XmlElement("album_mbid")]
public string AlbumMBID { get; set; }
[XmlElement("artist_mbid")]
public string ArtistMBID { get; set; }
[XmlElement("albumartist_mbid")]
public string AlbumArtistMBID { get; set; }
[XmlElement("preciserating")]
public decimal PreciseRating { get; set; }
[XmlElement("rating")]
public decimal Rating { get; set; }
[XmlElement("averagerating")]
public decimal AverageRating { get; set; }
[XmlElement("replaygain_album_gain")]
public decimal ReplayGainAlbumGain { get; set; }
[XmlElement("replaygain_album_peak")]
public decimal ReplayGainAlbumPeak { get; set; }
[XmlElement("replaygain_track_gain")]
public decimal ReplayGainTrackGain { get; set; }
[XmlElement("replaygain_track_peak")]
public decimal ReplayGainTrackPeak { get; set; }
}
[XmlRoot("root")]
public class SongsResponse : AmpacheResponse
{
[XmlElement("total_count")]
public int TotalCount { get; set; }
[XmlElement("song")]
public Song[] Songs { get; set; }
}
}
| {
"content_hash": "6bf51a2fe74d02e3733322aef42b2dd3",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 56,
"avg_line_length": 29.626262626262626,
"alnum_prop": 0.568019093078759,
"repo_name": "PlaidPhantom/MB_Ampache",
"id": "40cb77108d908cad5c57d9d0199441f08ce142c3",
"size": "2935",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MB_AmpacheDLL/Ampache/Song.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "94696"
}
],
"symlink_target": ""
} |
package com.navercorp.pinpoint.web.mapper.stat;
import com.navercorp.pinpoint.common.buffer.Buffer;
import com.navercorp.pinpoint.common.buffer.OffsetFixedBuffer;
import com.navercorp.pinpoint.common.hbase.HbaseColumnFamily;
import com.navercorp.pinpoint.common.hbase.RowMapper;
import com.navercorp.pinpoint.common.server.bo.codec.stat.ApplicationStatDecoder;
import com.navercorp.pinpoint.common.server.bo.serializer.stat.ApplicationStatDecodingContext;
import com.navercorp.pinpoint.common.server.bo.serializer.stat.ApplicationStatHbaseOperationFactory;
import com.navercorp.pinpoint.common.server.bo.stat.join.JoinStatBo;
import com.navercorp.pinpoint.web.mapper.TimestampFilter;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author minwoo.jung
*/
public class ApplicationStatMapper implements RowMapper<List<JoinStatBo>> {
public final static Comparator<JoinStatBo> REVERSE_TIMESTAMP_COMPARATOR = new Comparator<JoinStatBo>() {
@Override
public int compare(JoinStatBo o1, JoinStatBo o2) {
long x = o2.getTimestamp();
long y = o1.getTimestamp();
return Long.compare(x, y);
}
};
private final ApplicationStatHbaseOperationFactory hbaseOperationFactory;
private final ApplicationStatDecoder decoder;
private final TimestampFilter filter;
public ApplicationStatMapper(ApplicationStatHbaseOperationFactory hbaseOperationFactory, ApplicationStatDecoder decoder, TimestampFilter filter) {
this.hbaseOperationFactory = hbaseOperationFactory;
this.decoder = decoder;
this.filter = filter;
}
@Override
public List<JoinStatBo> mapRow(Result result, int rowNum) throws Exception {
if (result.isEmpty()) {
return Collections.emptyList();
}
final byte[] distributedRowKey = result.getRow();
final String applicationId = this.hbaseOperationFactory.getApplicationId(distributedRowKey);
final long baseTimestamp = this.hbaseOperationFactory.getBaseTimestamp(distributedRowKey);
List<JoinStatBo> dataPoints = new ArrayList<>();
for (Cell cell : result.rawCells()) {
if (CellUtil.matchingFamily(cell, HbaseColumnFamily.APPLICATION_STAT_STATISTICS.getName())) {
Buffer qualifierBuffer = new OffsetFixedBuffer(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
Buffer valueBuffer = new OffsetFixedBuffer(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
long timestampDelta = this.decoder.decodeQualifier(qualifierBuffer);
ApplicationStatDecodingContext decodingContext = new ApplicationStatDecodingContext();
decodingContext.setApplicationId(applicationId);
decodingContext.setBaseTimestamp(baseTimestamp);
decodingContext.setTimestampDelta(timestampDelta);
List<JoinStatBo> candidates = this.decoder.decodeValue(valueBuffer, decodingContext);
for (JoinStatBo candidate : candidates) {
long timestamp = candidate.getTimestamp();
if (this.filter.filter(timestamp)) {
continue;
}
dataPoints.add(candidate);
}
}
}
// Reverse sort as timestamp is stored in a reversed order.
dataPoints.sort(REVERSE_TIMESTAMP_COMPARATOR);
return dataPoints;
}
}
| {
"content_hash": "e35fabe7da3f356f13c4db77284c48df",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 150,
"avg_line_length": 44.023809523809526,
"alnum_prop": 0.7101135749053542,
"repo_name": "barneykim/pinpoint",
"id": "664bdbf19a22a105d69aa0a9f88b7494c882087d",
"size": "4292",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "web/src/main/java/com/navercorp/pinpoint/web/mapper/stat/ApplicationStatMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "23110"
},
{
"name": "CSS",
"bytes": "534460"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "783305"
},
{
"name": "Java",
"bytes": "16344627"
},
{
"name": "JavaScript",
"bytes": "4821525"
},
{
"name": "Makefile",
"bytes": "5246"
},
{
"name": "PLSQL",
"bytes": "4156"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Ruby",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "31363"
},
{
"name": "TSQL",
"bytes": "4316"
},
{
"name": "Thrift",
"bytes": "15284"
},
{
"name": "TypeScript",
"bytes": "1384337"
}
],
"symlink_target": ""
} |
using DvachBrowser3.Posts;
namespace DvachBrowser3.ViewModels
{
/// <summary>
/// Ìåäèà ôàéë áåç ïðåäâàðèòåëüíîãî ïðîñìîòðà.
/// </summary>
public sealed class ImageMediaFileWithThumbnailViewModel : ImageMediaFileViewModelBase<PostImageWithThumbnail>
{
/// <summary>
/// Êîíñòðóêòîð.
/// </summary>
/// <param name="parent">Ðîäèòåëüñêàÿ ìîäåëü.</param>
/// <param name="mediaData">Äàííûå ìåäèà.</param>
public ImageMediaFileWithThumbnailViewModel(IPostViewModel parent, PostImageWithThumbnail mediaData) : base(parent, mediaData)
{
ThumbnailImage = MediaData.Thumbnail != null ? new ThumbnailImageSourceViewModel(MediaData.Thumbnail) : null;
ThumbnailImage?.SetImageCache(StaticImageCache.Thumbnails);
}
/// <summary>
/// Èçîáðàæåíèå ïðåäâàðèòåëüíîãî ïðîñìîòðà.
/// </summary>
public override IImageSourceViewModelWithSize ThumbnailImage { get; }
}
} | {
"content_hash": "0a7eb52b4ff28129bfcc6e2910a8503b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 134,
"avg_line_length": 38.30769230769231,
"alnum_prop": 0.6726907630522089,
"repo_name": "Opiumtm/DvachBrowser3",
"id": "102cbc50b6d60e94cc3b455a8883aaaf7f8483a5",
"size": "996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DvachBrowser3/ViewModels/Post/Implementation/Media/ImageMediaFileWithThumbnailViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "63"
},
{
"name": "C#",
"bytes": "2332080"
},
{
"name": "C++",
"bytes": "12677"
},
{
"name": "HTML",
"bytes": "272"
}
],
"symlink_target": ""
} |
require 'helper'
require 'tempfile'
require 'pathname'
module SQLite3
class TestDatabase < SQLite3::TestCase
attr_reader :db
def setup
@db = SQLite3::Database.new(':memory:')
super
end
def test_segv
assert_raises { SQLite3::Database.new 1 }
end
def test_db_filename
tf = nil
assert_equal '', @db.filename('main')
tf = Tempfile.new 'thing'
@db = SQLite3::Database.new tf.path
assert_equal File.expand_path(tf.path), File.expand_path(@db.filename('main'))
ensure
tf.unlink if tf
end
def test_filename
tf = nil
assert_equal '', @db.filename
tf = Tempfile.new 'thing'
@db = SQLite3::Database.new tf.path
assert_equal File.expand_path(tf.path), File.expand_path(@db.filename)
ensure
tf.unlink if tf
end
def test_filename_with_attachment
tf = nil
assert_equal '', @db.filename
tf = Tempfile.new 'thing'
@db.execute "ATTACH DATABASE '#{tf.path}' AS 'testing'"
assert_equal File.expand_path(tf.path), File.expand_path(@db.filename('testing'))
ensure
tf.unlink if tf
end
def test_error_code
begin
db.execute 'SELECT'
rescue SQLite3::SQLException => e
end
assert_equal 1, e.code
end
def test_extended_error_code
db.extended_result_codes = true
db.execute 'CREATE TABLE "employees" ("token" integer NOT NULL)'
begin
db.execute 'INSERT INTO employees (token) VALUES (NULL)'
rescue SQLite3::ConstraintException => e
end
assert_equal 1299, e.code
end
def test_bignum
num = 4907021672125087844
db.execute 'CREATE TABLE "employees" ("token" integer(8), "name" varchar(20) NOT NULL)'
db.execute "INSERT INTO employees(name, token) VALUES('employee-1', ?)", [num]
rows = db.execute 'select token from employees'
assert_equal num, rows.first.first
end
def test_blob
@db.execute("CREATE TABLE blobs ( id INTEGER, hash BLOB(10) )")
blob = Blob.new("foo\0bar")
@db.execute("INSERT INTO blobs VALUES (0, ?)", [blob])
assert_equal [[0, blob, blob.length, blob.length*2]], @db.execute("SELECT id, hash, length(hash), length(hex(hash)) FROM blobs")
end
def test_get_first_row
assert_equal [1], @db.get_first_row('SELECT 1')
end
def test_get_first_row_with_type_translation_and_hash_results
@db.results_as_hash = true
@db.type_translation = true
assert_equal({"1"=>1}, @db.get_first_row('SELECT 1'))
end
def test_execute_with_type_translation_and_hash
@db.results_as_hash = true
@db.type_translation = true
rows = []
@db.execute('SELECT 1') { |row| rows << row }
assert_equal({"1"=>1}, rows.first)
end
def test_encoding
assert @db.encoding, 'database has encoding'
end
def test_changes
@db.execute("CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT, number integer)")
assert_equal 0, @db.changes
@db.execute("INSERT INTO items (number) VALUES (10)")
assert_equal 1, @db.changes
@db.execute_batch(
"UPDATE items SET number = (number + :nn) WHERE (number = :n)",
{"nn" => 20, "n" => 10})
assert_equal 1, @db.changes
assert_equal [[30]], @db.execute("select number from items")
end
def test_batch_last_comment_is_processed
# FIXME: nil as a successful return value is kinda dumb
assert_nil @db.execute_batch <<-eosql
CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT);
-- omg
eosql
end
def test_execute_batch2
@db.results_as_hash = true
return_value = @db.execute_batch2 <<-eosql
CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT, name string);
INSERT INTO items (name) VALUES ("foo");
INSERT INTO items (name) VALUES ("bar");
SELECT * FROM items;
eosql
assert_equal return_value, [{"id"=>"1","name"=>"foo"}, {"id"=>"2", "name"=>"bar"}]
return_value = @db.execute_batch2('SELECT * FROM items;') do |result|
result["id"] = result["id"].to_i
result
end
assert_equal return_value, [{"id"=>1,"name"=>"foo"}, {"id"=>2, "name"=>"bar"}]
return_value = @db.execute_batch2('INSERT INTO items (name) VALUES ("oof")')
assert_equal return_value, []
return_value = @db.execute_batch2(
'CREATE TABLE employees (id integer PRIMARY KEY AUTOINCREMENT, name string, age integer(3));
INSERT INTO employees (age) VALUES (30);
INSERT INTO employees (age) VALUES (40);
INSERT INTO employees (age) VALUES (20);
SELECT age FROM employees;') do |result|
result["age"] = result["age"].to_i
result
end
assert_equal return_value, [{"age"=>30}, {"age"=>40}, {"age"=>20}]
return_value = @db.execute_batch2('SELECT name FROM employees');
assert_equal return_value, [{"name"=>nil}, {"name"=>nil}, {"name"=>nil}]
@db.results_as_hash = false
return_value = @db.execute_batch2(
'CREATE TABLE managers (id integer PRIMARY KEY AUTOINCREMENT, age integer(3));
INSERT INTO managers (age) VALUES (50);
INSERT INTO managers (age) VALUES (60);
SELECT id, age from managers;') do |result|
result = result.map do |res|
res.to_i
end
result
end
assert_equal return_value, [[1, 50], [2, 60]]
assert_raises (RuntimeError) do
# "names" is not a valid column
@db.execute_batch2 'INSERT INTO items (names) VALUES ("bazz")'
end
end
def test_new
db = SQLite3::Database.new(':memory:')
assert db
end
def test_new_yields_self
thing = nil
SQLite3::Database.new(':memory:') do |db|
thing = db
end
assert_instance_of(SQLite3::Database, thing)
end
def test_new_with_options
# determine if Ruby is running on Big Endian platform
utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE"
if RUBY_VERSION >= "1.9"
db = SQLite3::Database.new(':memory:'.encode(utf16), :utf16 => true)
else
db = SQLite3::Database.new(Iconv.conv(utf16, 'UTF-8', ':memory:'),
:utf16 => true)
end
assert db
end
def test_close
db = SQLite3::Database.new(':memory:')
db.close
assert db.closed?
end
def test_block_closes_self
thing = nil
SQLite3::Database.new(':memory:') do |db|
thing = db
assert !thing.closed?
end
assert thing.closed?
end
def test_block_closes_self_even_raised
thing = nil
begin
SQLite3::Database.new(':memory:') do |db|
thing = db
raise
end
rescue
end
assert thing.closed?
end
def test_prepare
db = SQLite3::Database.new(':memory:')
stmt = db.prepare('select "hello world"')
assert_instance_of(SQLite3::Statement, stmt)
end
def test_block_prepare_does_not_double_close
db = SQLite3::Database.new(':memory:')
r = db.prepare('select "hello world"') do |stmt|
stmt.close
:foo
end
assert_equal :foo, r
end
def test_total_changes
db = SQLite3::Database.new(':memory:')
db.execute("create table foo ( a integer primary key, b text )")
db.execute("insert into foo (b) values ('hello')")
assert_equal 1, db.total_changes
end
def test_execute_returns_list_of_hash
db = SQLite3::Database.new(':memory:', :results_as_hash => true)
db.execute("create table foo ( a integer primary key, b text )")
db.execute("insert into foo (b) values ('hello')")
rows = db.execute("select * from foo")
assert_equal [{"a"=>1, "b"=>"hello"}], rows
end
def test_execute_yields_hash
db = SQLite3::Database.new(':memory:', :results_as_hash => true)
db.execute("create table foo ( a integer primary key, b text )")
db.execute("insert into foo (b) values ('hello')")
db.execute("select * from foo") do |row|
assert_equal({"a"=>1, "b"=>"hello"}, row)
end
end
def test_table_info
db = SQLite3::Database.new(':memory:', :results_as_hash => true)
db.execute("create table foo ( a integer primary key, b text )")
info = [{
"name" => "a",
"pk" => 1,
"notnull" => 0,
"type" => "integer",
"dflt_value" => nil,
"cid" => 0
},
{
"name" => "b",
"pk" => 0,
"notnull" => 0,
"type" => "text",
"dflt_value" => nil,
"cid" => 1
}]
assert_equal info, db.table_info('foo')
end
def test_total_changes_closed
db = SQLite3::Database.new(':memory:')
db.close
assert_raise(SQLite3::Exception) do
db.total_changes
end
end
def test_trace_requires_opendb
@db.close
assert_raise(SQLite3::Exception) do
@db.trace { |x| }
end
end
def test_trace_with_block
result = nil
@db.trace { |sql| result = sql }
@db.execute "select 'foo'"
assert_equal "select 'foo'", result
end
def test_trace_with_object
obj = Class.new {
attr_accessor :result
def call sql; @result = sql end
}.new
@db.trace(obj)
@db.execute "select 'foo'"
assert_equal "select 'foo'", obj.result
end
def test_trace_takes_nil
@db.trace(nil)
@db.execute "select 'foo'"
end
def test_last_insert_row_id_closed
@db.close
assert_raise(SQLite3::Exception) do
@db.last_insert_row_id
end
end
def test_define_function
called_with = nil
@db.define_function("hello") do |value|
called_with = value
end
@db.execute("select hello(10)")
assert_equal 10, called_with
end
def test_call_func_arg_type
called_with = nil
@db.define_function("hello") do |b, c, d|
called_with = [b, c, d]
nil
end
@db.execute("select hello(2.2, 'foo', NULL)")
assert_equal [2.2, 'foo', nil], called_with
end
def test_define_varargs
called_with = nil
@db.define_function("hello") do |*args|
called_with = args
nil
end
@db.execute("select hello(2.2, 'foo', NULL)")
assert_equal [2.2, 'foo', nil], called_with
end
def test_call_func_blob
called_with = nil
@db.define_function("hello") do |a, b|
called_with = [a, b, a.length]
nil
end
blob = Blob.new("a\0fine\0kettle\0of\0fish")
@db.execute("select hello(?, length(?))", [blob, blob])
assert_equal [blob, blob.length, 21], called_with
end
def test_function_return
@db.define_function("hello") { |a| 10 }
assert_equal [10], @db.execute("select hello('world')").first
end
def test_function_return_types
[10, 2.2, nil, "foo", Blob.new("foo\0bar")].each do |thing|
@db.define_function("hello") { |a| thing }
assert_equal [thing], @db.execute("select hello('world')").first
end
end
def test_function_gc_segfault
@db.create_function("bug", -1) { |func, *values| func.result = values.join }
# With a lot of data and a lot of threads, try to induce a GC segfault.
params = Array.new(127, "?" * 28000)
proc = Proc.new {
db.execute("select bug(#{Array.new(params.length, "?").join(",")})", params)
}
m = Mutex.new
30.times.map { Thread.new { m.synchronize { proc.call } } }.each(&:join)
end
def test_function_return_type_round_trip
[10, 2.2, nil, "foo", Blob.new("foo\0bar")].each do |thing|
@db.define_function("hello") { |a| a }
assert_equal [thing], @db.execute("select hello(hello(?))", [thing]).first
end
end
def test_define_function_closed
@db.close
assert_raise(SQLite3::Exception) do
@db.define_function('foo') { }
end
end
def test_inerrupt_closed
@db.close
assert_raise(SQLite3::Exception) do
@db.interrupt
end
end
def test_define_aggregate
@db.execute "create table foo ( a integer primary key, b text )"
@db.execute "insert into foo ( b ) values ( 'foo' )"
@db.execute "insert into foo ( b ) values ( 'bar' )"
@db.execute "insert into foo ( b ) values ( 'baz' )"
acc = Class.new {
attr_reader :sum
alias :finalize :sum
def initialize
@sum = 0
end
def step a
@sum += a
end
}.new
@db.define_aggregator("accumulate", acc)
value = @db.get_first_value( "select accumulate(a) from foo" )
assert_equal 6, value
end
def test_authorizer_ok
@db.authorizer = Class.new {
def call action, a, b, c, d; true end
}.new
@db.prepare("select 'fooooo'")
@db.authorizer = Class.new {
def call action, a, b, c, d; 0 end
}.new
@db.prepare("select 'fooooo'")
end
def test_authorizer_ignore
@db.authorizer = Class.new {
def call action, a, b, c, d; nil end
}.new
stmt = @db.prepare("select 'fooooo'")
assert_nil stmt.step
end
def test_authorizer_fail
@db.authorizer = Class.new {
def call action, a, b, c, d; false end
}.new
assert_raises(SQLite3::AuthorizationException) do
@db.prepare("select 'fooooo'")
end
end
def test_remove_auth
@db.authorizer = Class.new {
def call action, a, b, c, d; false end
}.new
assert_raises(SQLite3::AuthorizationException) do
@db.prepare("select 'fooooo'")
end
@db.authorizer = nil
@db.prepare("select 'fooooo'")
end
def test_close_with_open_statements
@db.prepare("select 'foo'")
assert_raises(SQLite3::BusyException) do
@db.close
end
end
def test_execute_with_empty_bind_params
assert_equal [['foo']], @db.execute("select 'foo'", [])
end
def test_query_with_named_bind_params
assert_equal [['foo']], @db.query("select :n", {'n' => 'foo'}).to_a
end
def test_execute_with_named_bind_params
assert_equal [['foo']], @db.execute("select :n", {'n' => 'foo'})
end
end
end
| {
"content_hash": "4d22566465c050ed3da7685de7237c08",
"timestamp": "",
"source": "github",
"line_count": 503,
"max_line_length": 134,
"avg_line_length": 28.870775347912524,
"alnum_prop": 0.57134003580774,
"repo_name": "Celyagd/celyagd.github.io",
"id": "c255ed8537660e75da53818de66ae4c1978152dd",
"size": "14522",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "stakes-jekyll/gems/sqlite3-1.4.0/test/test_database.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1375233"
},
{
"name": "C++",
"bytes": "71485"
},
{
"name": "CMake",
"bytes": "314"
},
{
"name": "CSS",
"bytes": "168680"
},
{
"name": "HTML",
"bytes": "7735250"
},
{
"name": "Java",
"bytes": "134091"
},
{
"name": "JavaScript",
"bytes": "196815"
},
{
"name": "PowerShell",
"bytes": "238"
},
{
"name": "REXX",
"bytes": "1941"
},
{
"name": "Ragel",
"bytes": "56865"
},
{
"name": "Roff",
"bytes": "3725"
},
{
"name": "Ruby",
"bytes": "2708464"
},
{
"name": "Shell",
"bytes": "842"
},
{
"name": "Yacc",
"bytes": "7664"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Phoma pleosporoides Sacc.
### Remarks
null | {
"content_hash": "c7eb9fb8cf3bdfb4a61970e1d6b655e3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 25,
"avg_line_length": 10,
"alnum_prop": 0.7076923076923077,
"repo_name": "mdoering/backbone",
"id": "c995230ebf660444bb2eda1cbefcb9b51f086b40",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phoma/Phoma pleosporoides/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from bson import DBRef, SON
from base import (
BaseDict, BaseList, EmbeddedDocumentList,
TopLevelDocumentMetaclass, get_document
)
from fields import (ReferenceField, ListField, DictField, MapField)
from connection import get_db
from queryset import QuerySet
from document import Document, EmbeddedDocument
class DeReference(object):
def __call__(self, items, max_depth=1, instance=None, name=None):
"""
Cheaply dereferences the items to a set depth.
Also handles the conversion of complex data types.
:param items: The iterable (dict, list, queryset) to be dereferenced.
:param max_depth: The maximum depth to recurse to
:param instance: The owning instance used for tracking changes by
:class:`~mongoengine.base.ComplexBaseField`
:param name: The name of the field, used for tracking changes by
:class:`~mongoengine.base.ComplexBaseField`
:param get: A boolean determining if being called by __get__
"""
if items is None or isinstance(items, basestring):
return items
# cheapest way to convert a queryset to a list
# list(queryset) uses a count() query to determine length
if isinstance(items, QuerySet):
items = [i for i in items]
self.max_depth = max_depth
doc_type = None
if instance and isinstance(instance, (Document, EmbeddedDocument,
TopLevelDocumentMetaclass)):
doc_type = instance._fields.get(name)
while hasattr(doc_type, 'field'):
doc_type = doc_type.field
if isinstance(doc_type, ReferenceField):
field = doc_type
doc_type = doc_type.document_type
is_list = not hasattr(items, 'items')
if is_list and all([i.__class__ == doc_type for i in items]):
return items
elif not is_list and all([i.__class__ == doc_type
for i in items.values()]):
return items
elif not field.dbref:
if not hasattr(items, 'items'):
def _get_items(items):
new_items = []
for v in items:
if isinstance(v, list):
new_items.append(_get_items(v))
elif not isinstance(v, (DBRef, Document)):
new_items.append(field.to_python(v))
else:
new_items.append(v)
return new_items
items = _get_items(items)
else:
items = dict([
(k, field.to_python(v))
if not isinstance(v, (DBRef, Document)) else (k, v)
for k, v in items.iteritems()]
)
self.reference_map = self._find_references(items)
self.object_map = self._fetch_objects(doc_type=doc_type)
return self._attach_objects(items, 0, instance, name)
def _find_references(self, items, depth=0):
"""
Recursively finds all db references to be dereferenced
:param items: The iterable (dict, list, queryset)
:param depth: The current depth of recursion
"""
reference_map = {}
if not items or depth >= self.max_depth:
return reference_map
# Determine the iterator to use
if not hasattr(items, 'items'):
iterator = enumerate(items)
else:
iterator = items.iteritems()
# Recursively find dbreferences
depth += 1
for k, item in iterator:
if isinstance(item, (Document, EmbeddedDocument)):
for field_name, field in item._fields.iteritems():
v = item._data.get(field_name, None)
if isinstance(v, (DBRef)):
reference_map.setdefault(field.document_type, set()).add(v.id)
elif isinstance(v, (dict, SON)) and '_ref' in v:
reference_map.setdefault(get_document(v['_cls']), set()).add(v['_ref'].id)
elif isinstance(v, (dict, list, tuple)) and depth <= self.max_depth:
field_cls = getattr(getattr(field, 'field', None), 'document_type', None)
references = self._find_references(v, depth)
for key, refs in references.iteritems():
if isinstance(field_cls, (Document, TopLevelDocumentMetaclass)):
key = field_cls
reference_map.setdefault(key, set()).update(refs)
elif isinstance(item, (DBRef)):
reference_map.setdefault(item.collection, set()).add(item.id)
elif isinstance(item, (dict, SON)) and '_ref' in item:
reference_map.setdefault(get_document(item['_cls']), set()).add(item['_ref'].id)
elif isinstance(item, (dict, list, tuple)) and depth - 1 <= self.max_depth:
references = self._find_references(item, depth - 1)
for key, refs in references.iteritems():
reference_map.setdefault(key, set()).update(refs)
return reference_map
def _fetch_objects(self, doc_type=None):
"""Fetch all references and convert to their document objects
"""
object_map = {}
for collection, dbrefs in self.reference_map.iteritems():
refs = [dbref for dbref in dbrefs
if unicode(dbref).encode('utf-8') not in object_map]
if hasattr(collection, 'objects'): # We have a document class for the refs
references = collection.objects.in_bulk(refs)
for key, doc in references.iteritems():
object_map[key] = doc
else: # Generic reference: use the refs data to convert to document
if isinstance(doc_type, (ListField, DictField, MapField,)):
continue
if doc_type:
references = doc_type._get_db()[collection].find({'_id': {'$in': refs}})
for ref in references:
doc = doc_type._from_son(ref)
object_map[doc.id] = doc
else:
references = get_db()[collection].find({'_id': {'$in': refs}})
for ref in references:
if '_cls' in ref:
doc = get_document(ref["_cls"])._from_son(ref)
elif doc_type is None:
doc = get_document(
''.join(x.capitalize()
for x in collection.split('_')))._from_son(ref)
else:
doc = doc_type._from_son(ref)
object_map[doc.id] = doc
return object_map
def _attach_objects(self, items, depth=0, instance=None, name=None):
"""
Recursively finds all db references to be dereferenced
:param items: The iterable (dict, list, queryset)
:param depth: The current depth of recursion
:param instance: The owning instance used for tracking changes by
:class:`~mongoengine.base.ComplexBaseField`
:param name: The name of the field, used for tracking changes by
:class:`~mongoengine.base.ComplexBaseField`
"""
if not items:
if isinstance(items, (BaseDict, BaseList)):
return items
if instance:
if isinstance(items, dict):
return BaseDict(items, instance, name)
else:
return BaseList(items, instance, name)
if isinstance(items, (dict, SON)):
if '_ref' in items:
return self.object_map.get(items['_ref'].id, items)
elif '_cls' in items:
doc = get_document(items['_cls'])._from_son(items)
_cls = doc._data.pop('_cls', None)
del items['_cls']
doc._data = self._attach_objects(doc._data, depth, doc, None)
if _cls is not None:
doc._data['_cls'] = _cls
return doc
if not hasattr(items, 'items'):
is_list = True
list_type = BaseList
if isinstance(items, EmbeddedDocumentList):
list_type = EmbeddedDocumentList
as_tuple = isinstance(items, tuple)
iterator = enumerate(items)
data = []
else:
is_list = False
iterator = items.iteritems()
data = {}
depth += 1
for k, v in iterator:
if is_list:
data.append(v)
else:
data[k] = v
if k in self.object_map and not is_list:
data[k] = self.object_map[k]
elif isinstance(v, (Document, EmbeddedDocument)):
for field_name, field in v._fields.iteritems():
v = data[k]._data.get(field_name, None)
if isinstance(v, (DBRef)):
data[k]._data[field_name] = self.object_map.get(v.id, v)
elif isinstance(v, (dict, SON)) and '_ref' in v:
data[k]._data[field_name] = self.object_map.get(v['_ref'].id, v)
elif isinstance(v, dict) and depth <= self.max_depth:
data[k]._data[field_name] = self._attach_objects(v, depth, instance=instance, name=name)
elif isinstance(v, (list, tuple)) and depth <= self.max_depth:
data[k]._data[field_name] = self._attach_objects(v, depth, instance=instance, name=name)
elif isinstance(v, (dict, list, tuple)) and depth <= self.max_depth:
item_name = '%s.%s' % (name, k) if name else name
data[k] = self._attach_objects(v, depth - 1, instance=instance, name=item_name)
elif hasattr(v, 'id'):
data[k] = self.object_map.get(v.id, v)
if instance and name:
if is_list:
return tuple(data) if as_tuple else list_type(data, instance, name)
return BaseDict(data, instance, name)
depth += 1
return data
| {
"content_hash": "22f2fe192dcbf83fb1dd6297948eb9f5",
"timestamp": "",
"source": "github",
"line_count": 237,
"max_line_length": 112,
"avg_line_length": 45.08860759493671,
"alnum_prop": 0.512446191278308,
"repo_name": "noirbizarre/mongoengine",
"id": "453ba14f95bb0eb30f79df5db0fe1e8aa2b507f9",
"size": "10686",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mongoengine/dereference.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "970388"
}
],
"symlink_target": ""
} |
package com.rdms.cli.example;
import com.rdms.cli.CLIRuntimeException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
import org.junit.contrib.java.lang.system.SystemErrRule;
import org.junit.contrib.java.lang.system.SystemOutRule;
public class ExampleAppTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Rule
public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
public ExampleAppTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test(expected = NullPointerException.class)
public void testMain_nullArgs() {
String[] args = null;
ExampleApp.main(args);
}
@Test
public void testMain_emptyArgs() {
String[] args = new String[]{};
exit.expectSystemExitWithStatus(1);
ExampleApp.main(args);
}
@Test
public void testMain_badArgs() {
String[] args = new String[]{"wtf"};
exit.expectSystemExitWithStatus(1);
ExampleApp.main(args);
}
@Test(expected = CLIRuntimeException.class)
public void testMain_shortArgWrong() {
String[] args = new String[]{"-f"};
ExampleApp.main(args);
}
@Test
public void testMain_shortArg() {
String[] args = new String[]{"-e"};
ExampleApp.main(args);
assertEquals("Doing example things now\n", systemOutRule.getLog());
}
@Test
public void testMain_shortArgWithFlag() {
String[] args = new String[]{"-e", "-d"};
ExampleApp.main(args);
assertEquals("Doing example things now - flag on\n", systemOutRule.getLog());
}
@Test(expected = CLIRuntimeException.class)
public void testMain_longArgWrong() {
String[] args = new String[]{"--fake"};
ExampleApp.main(args);
}
@Test
public void testMain_longArg() {
String[] args = new String[]{"--example"};
ExampleApp.main(args);
assertEquals("Doing example things now\n", systemOutRule.getLog());
}
@Test
public void testMain_longArgWithFlag() {
String[] args = new String[]{"--example", "-d"};
ExampleApp.main(args);
assertEquals("Doing example things now - flag on\n", systemOutRule.getLog());
}
}
| {
"content_hash": "0ca69c65d201939e385aa2eb425887b0",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 85,
"avg_line_length": 25.914285714285715,
"alnum_prop": 0.6409408305769938,
"repo_name": "reasonedmetrics/reasoned-cli",
"id": "3f4d829a3f051d1c0657d9e0adbbd74efc35e7ba",
"size": "2721",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "reasoned-cli-example/src/test/java/com/rdms/cli/example/ExampleAppTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "16156"
}
],
"symlink_target": ""
} |
<?php
require_once dirname(__FILE__) . '/Controller/TestController.php';
class ServiceContainer
{
static protected $instances = array();
public function getTestController()
{
if (!isset(self::$instances['TestController'])) {
self::$instances['TestController'] = new TestController($this);
}
return self::$instances['TestController'];
}
public function getApp()
{
if (!isset(self::$instances['app'])) {
self::$instances['app'] = new Slim(array(
'http.version' => '1.0',
'log.enable' => true,
'log.path' => './logs'
));
}
return self::$instances['app'];
}
}
| {
"content_hash": "956b0c23d14300a839f6030a9e5fafe8",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 77,
"avg_line_length": 32.55555555555556,
"alnum_prop": 0.4300341296928328,
"repo_name": "polad/slim",
"id": "5164379e36cd4d98d43536f1ad35ef7b4fe5b4fa",
"size": "879",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/ServiceContainer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "2873"
}
],
"symlink_target": ""
} |
/**
* Redobj constructor
*
* @param {Redis.Client} Redis connection
* @param {String} name Name to be used in redis keys
* @api public
*/
Redobj = function(client, name, keys) {
this.client = client;
this.name = name;
this.keys = keys;
};
/**
* Retrieves a single object given its id. Callbacks with null if the object does not exists.
* The id is assigned to the `_id` property of the object returned.
*
* @param {Number} Object id.
* @param {Array[String]} (optional) Keys that should be retrieved. By default retrieves all the keys.
* @param {Function} Callback function.
* @see exports.Redobj#mget
* @api public
*/
Redobj.prototype.get = function() {
this._keysCb(arguments, function(id, keys, callback) {
if (isNaN(id)) {
callback(new Error('id is not a number'), null);
} else {
this._get(id, keys, callback);
}
});
};
/**
* Saves a single object. Assignes the `_id` property to the object passsed in.
*
* @param {Object} obj Object to store.
* @param {Array[String]} (optional) Keys that should be stored. By default stores all the keys.
* @param {Function} Callabck function.
* @see exports.Redobj#mset
* @api public
*/
Redobj.prototype.set = function() {
this._keysCb(arguments, function(obj, keys, callback) {
if (!(obj instanceof Object)) {
callback(new Error('can only set Object instances'));
} else {
this._set(obj, keys, callback);
}
});
};
/**
* Deletes a single object from the storage.
* On success deletes the `_id` property of the object passsed in.
*
* @param {Object|Number} Expects the `_id` property to be set on the object.
* @param {Function} Callabck function.
* @see exports.Redobj#mdel
* @api public
*/
Redobj.prototype.del = function(obj, callback) {
if (!(obj instanceof Object) && isNaN(obj)) {
callback(new Error('can only del Object and instances or specific Number ids'));
} else {
var arg = isNaN(obj) ? obj : { _id: obj };
this._del(arg, callback);
}
};
/**
* Retrieves multiple objects given their ids.
* The id is assigned to the `_id` property of each object returned.
*
* @param {Array[Number]} Object id.
* @param {Array[String]} (optional) Keys that should be retrieved. By default retrieves all the keys.
* @param {Function} Callback function.
* @see exports.Redobj#get
* @api public
*/
Redobj.prototype.mget = function() {
this._chain(arguments, this.get, true);
};
/**
* Saves multiple objects. Assignes the `_id` property on each saved object.
*
* @param {Array[Object]} Objects array to store.
* @param {Array[String]} (optional) Keys that should be stored. By default stores all the keys.
* @param {Function} Callabck function.
* @see exports.Redobj#set
* @api public
*/
Redobj.prototype.mset = function() {
this._chain(arguments, this.set, true);
};
/**
* Deletes multiple objects from the storage.
* On success deletes the `_id` property of each object passsed in.
*
* @param {Array[Object|Number]} Expects the `_id` property to be set on each object.
* @param {Function} Callabck function.
* @see exports.Redobj#del
* @api public
*/
Redobj.prototype.mdel = function() {
this._chain(arguments, this.del, false);
};
/**
* Gets all object with the given key value.
*
* @param {Object} key-value pair to look up.
* @param {Array[String]} (optional) Keys that should be retrieved. By default retrieves all the keys.
* @param {Function} Callabck function.
* @see Redobj#get
* @see Redobj#mget
* @api public
*/
Redobj.prototype.mfind = function() {
var that = this;
this._keysCb(arguments, function(query, keys, callback) {
this._findIds(query, function(err, ids) {
if (err) {
callback(err);
} else {
that.mget(ids, keys, callback);
}
});
});
};
/**
* Gets one object with the given key value.
*
* @param {Object} key-value pair to look up.
* @param {Array[String]} (optional) Keys that should be retrieved. By default retrieves all the keys.
* @param {Function} Callabck function.
* @see Redobj#get
* @see Redobj#mget
* @api public
*/
Redobj.prototype.find = function() {
var that = this;
this._keysCb(arguments, function(query, keys, callback) {
this._findIds(query, function(err, ids) {
if (err) {
callback(err);
} else if (ids.length < 1) {
callback(null, null);
} else {
that.get(ids[0], keys, callback);
}
});
});
}
/**
* @api private
*/
Redobj.prototype._findIds = function(query, callback) {
var ids = null;
var multi = this.client.multi();
for (var key in query) {
var val = query[key];
var type = this.keys[key];
if (type && type['backref']) {
var key_str = 'backrefs:' + this.name + ':' + key + ':' + val;
multi.smembers(key_str, function(err, _ids) {
if (ids === null) {
ids = _ids;
} else {
ids = ids.filter(function(id) {
return _ids.indexOf(id) != -1;
});
}
});
}
}
multi.exec(function(err) {
callback(err, ids);
});
}
Redobj.prototype._delKeyBackref = function(id, key, type, callback) {
var that = this;
this.get(id, [key], function(err, res) {
if (err || res === null || res[key] === undefined) {
callback.call(that, err);
} else {
var value = res[key];
var key_str = 'backrefs:' + that.name + ':' + key + ':';
var multi = that.client.multi();
switch (type.name) {
case VALUE_TYPE:
multi.srem(key_str + value, id);
break;
case LIST_TYPE:
case SET_TYPE:
for (var i = 0; i < value.length; i++) {
multi.srem(key_str + value[i], id);
}
break;
default:
throw new Error('unhandled key type');
}
multi.exec(function(err, res) {
callback.call(that, err);
});
}
});
};
Redobj.prototype._addKeyBackref = function(id, key, value, type, callback) {
var key_str = 'backrefs:' + this.name + ':' + key + ':';
var multi = this.client.multi();
switch (type.name) {
case VALUE_TYPE:
multi.sadd(key_str + value, id);
break;
case LIST_TYPE:
case SET_TYPE:
for (var i = 0; i < value.length; i++) {
multi.sadd(key_str + value[i], id);
}
break;
default:
throw new Error('unhandled key type');
}
multi.exec(function(err, res) {
callback.call(this, err);
});
};
Redobj.prototype._setKeyBackref = function(id, key, value, type, callback) {
this._delKeyBackref(id, key, type, function(err) {
if (err) {
callback(err);
} else {
this._addKeyBackref(id, key, value, type, callback);
}
});
}
Redobj.prototype._setBackrefs = function(id) {
this._keysCb(__slice.call(arguments, 1), function(obj, keys, callback) {
var args = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = obj[key];
var type = this.keys[key];
if (key !== undefined && val !== undefined && type !== undefined && type.backref) {
args.push([id, key, val, type]);
}
}
_chain(this, args, this._setKeyBackref, callback);
});
};
Redobj.prototype._delBackrefs = function(id) {
var that = this;
this._keysCb(__slice.call(arguments, 1), function(obj, keys, callback) {
var args = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var type = this.keys[key];
if (key !== undefined && type !== undefined && type.backref) {
args.push([id, key, type]);
}
}
_chain(that, args, this._delKeyBackref, callback);
});
};
Redobj.prototype._get = function(id, keys, callback) {
var obj = new Object();
var multi = this.client.multi();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var type = this.keys[key];
if (key && type) {
this._getKey(multi, id, key, type, function(key, val) {
if (obj) obj[key] = val;
});
}
}
multi.exec(function(err, res) {
if (_isEmpty(obj)) obj = null;
if (!err && obj) obj._id = id;
callback(err, obj);
});
};
Redobj.prototype._getKey = function(multi, id, key, type, callback) {
var obj_str = this.name + ":" + id;
var key_str = obj_str + ":" + key;
var f = function(err, res) {
if (!err && res) {
callback(key, res);
}
}
switch (type.name) {
case VALUE_TYPE:
multi.hget(obj_str, key, f);
break;
case LIST_TYPE:
multi.lrange(key_str, 0, -1, f);
break;
case SET_TYPE:
multi.smembers(key_str, f);
break;
default:
throw new Error('unhandled key type');
}
};
Redobj.prototype._set = function(obj, keys, callback) {
this._objId(obj, function(err, id) {
if (err) {
callback(err);
} else {
this._setBackrefs(id, obj, keys, function(err) {
if (err) {
callback(err);
} else {
var multi = this.client.multi();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var type = this.keys[key];
var val = obj[key];
if (key && val != undefined && type) {
this._setKey(multi, id, key, type, val);
}
}
multi.exec(function(err, res) {
if (!err) obj._id = id;
callback.call(this, err, obj);
});
}
});
}
});
};
Redobj.prototype._setKey = function(multi, id, key, type, val) {
var obj_str = this.name + ":" + id;
var key_str = obj_str + ":" + key;
switch (type.name) {
case VALUE_TYPE:
multi.hset(obj_str, key, val);
break;
case LIST_TYPE:
multi.del(key_str);
for (var i = 0; i < val.length; i++) {
multi.rpush(key_str, val[i]);
}
break;
case SET_TYPE:
multi.del(key_str);
for (var i = 0; i < val.length; i++) {
multi.sadd(key_str, val[i]);
}
break;
default:
throw new Error('unhandled key type: ' + type.name);
}
};
Redobj.prototype._del = function(obj, callback) {
this._delBackrefs(obj._id, obj, function(err) {
if (err) {
callback(err);
} else {
var multi = this.client.multi();
for (var key in this.keys) {
type = this.keys[key];
if (key && type) {
this._delKey(multi, obj._id, key, type);
}
}
multi.exec(function(err, res) {
if (!err) delete obj._id;
callback.call(this, err, obj);
});
}
});
};
Redobj.prototype._delKey = function(multi, id, key, type) {
var obj_str = this.name + ":" + id;
var key_str = obj_str + ":" + key;
switch (type.name) {
case VALUE_TYPE:
multi.hdel(obj_str, key);
break;
case LIST_TYPE:
case SET_TYPE:
multi.del(key_str);
break;
default:
throw new Error('unhandled key type: ' + type.name);
}
};
Redobj.prototype._objId = function(obj, callback) {
if (obj._id !== undefined) {
callback.call(this, null, obj._id);
} else {
var that = this;
this.client.incr("ids:" + this.name, function(err, id) {
callback.call(that, err, id);
});
}
};
Redobj.prototype._chain = function(args, fn, withKeys) {
this._keysCb(args, function(objs, keys, callback) {
var a = [];
for (var i = 0; i < objs.length; i++) {
if (withKeys) {
a.push([objs[i], keys]);
} else {
a.push([objs[i]]);
}
}
_chain(this, a, fn, callback);
});
};
__slice = Array.prototype.slice;
Redobj.prototype._keysCb = function(args, callback) {
var cb = args[args.length - 1];
var keys = Object.keys(this.keys);
var first = args[args.length - 2];
if (args.length > 2) {
keys = args[args.length - 2];
first = args[args.length - 3];
}
callback.call(this, first, keys, cb);
};
/**
* Constants
* @api private
*/
VALUE_TYPE = 'type_value';
LIST_TYPE = 'type_list';
SET_TYPE = 'type_set';
function _isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
function _chain(that, args, fn, callback) {
var objs = [];
var f = function(i) {
if (i >= args.length) {
callback.call(that, null, objs);
} else {
var arg = args[i];
arg.push(function(err, res) {
if (err) {
callback.call(that, err);
} else {
objs.push(res);
f(i + 1);
}
});
fn.apply(that, arg);
}
};
f(0);
}
function _typeFactory(name, opts) {
var type = { name: name };
for (var i = 0; i < opts.length; i++) {
type[opts[i]] = true;
}
return type;
}
function _typeFactoryValue() {
return _typeFactory(VALUE_TYPE, arguments);
}
function _typeFactoryList() {
return _typeFactory(LIST_TYPE, arguments);
}
function _typeFactorySet() {
return _typeFactory(SET_TYPE, arguments);
}
module.exports.Redobj = Redobj;
module.exports.value = _typeFactoryValue;
module.exports.list = _typeFactoryList;
module.exports.set = _typeFactorySet;
| {
"content_hash": "15a3be70bcbab8813d538f144ae1fde5",
"timestamp": "",
"source": "github",
"line_count": 523,
"max_line_length": 102,
"avg_line_length": 24.82409177820268,
"alnum_prop": 0.5767542170530694,
"repo_name": "akhodakivskiy/redobj",
"id": "70eab6e42051e11b5a658d694888a0c710f104c7",
"size": "13066",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/redobj.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "23504"
}
],
"symlink_target": ""
} |
package studenthack.bmql.services;
import java.util.List;
import com.bloomberglp.blpapi.*;
import studenthack.bmql.core.*;
import java.util.regex.*;
public class QueryEngine {
public Object getResults(Message msg, Query query)
{
Element msgElement = msg.asElement();
return getObject(msgElement, query.getElements());
}
private Object getObject(Element element, List<String> elements)
{
if(elements.size() == 0)
return element;
else
{
//AM > If element in query has an index then treat the element under consideration as array
if( elements.get(0).endsWith("]"))
{
Pattern p = Pattern.compile("\\[(\\d+)\\]");
Matcher m = p.matcher(elements.get(0));
if (m.find()) {
element = element.getValueAsElement(Integer.parseInt(m.group(1)));
elements.remove(0);
return getObject(element, elements);
}
}
else if(element.hasElement(elements.get(0)))
{
element = element.getElement(elements.get(0));
elements.remove(0);
return getObject(element, elements);
}
}
return null;
}
}
| {
"content_hash": "699ebfbc5b3118a60ec69792b4201f39",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 93,
"avg_line_length": 23.217391304347824,
"alnum_prop": 0.6685393258426966,
"repo_name": "AmarEkanO/studenthack2014-bmql",
"id": "bc4980077d5aa48a8f50d1a8a9d0f487d098f2ea",
"size": "1068",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/studenthack/bmql/services/QueryEngine.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "5608"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using DotVVM.Framework.Compilation.Parser.Dothtml.Parser;
using System.Linq;
namespace DotVVM.Framework.Compilation.ControlTree.Resolved
{
public class ResolvedTreeRoot : ResolvedContentNode, IAbstractTreeRoot
{
public Dictionary<string, List<IAbstractDirective>> Directives { get; set; } = new Dictionary<string, List<IAbstractDirective>>(StringComparer.OrdinalIgnoreCase);
public ResolvedTreeRoot(ControlResolverMetadata metadata, DothtmlNode node, DataContextStack dataContext, IReadOnlyDictionary<string, IReadOnlyList<IAbstractDirective>> directives)
: base(metadata, node, dataContext)
{
Directives = directives.ToDictionary(d => d.Key, d => d.Value.ToList());
directives.SelectMany(d => d.Value).ToList().ForEach(d => { ((ResolvedDirective)d).Parent = this; });
}
public override void AcceptChildren(IResolvedControlTreeVisitor visitor)
{
foreach (var dir in Directives.Values)
{
dir.ForEach(d => (d as ResolvedDirective)?.Accept(visitor));
}
base.AcceptChildren(visitor);
}
public override void Accept(IResolvedControlTreeVisitor visitor)
{
visitor.VisitView(this);
}
}
}
| {
"content_hash": "3845938451e6b6e65a74a3c3accb5aec",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 188,
"avg_line_length": 39.35294117647059,
"alnum_prop": 0.6763826606875935,
"repo_name": "kiraacorsac/dotvvm",
"id": "820af4fdce57cf96891b8ccb86f8f0812cb8c4db",
"size": "1340",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/DotVVM.Framework/Compilation/ControlTree/Resolved/ResolvedTreeRoot.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3088"
},
{
"name": "C#",
"bytes": "2212903"
},
{
"name": "CSS",
"bytes": "944"
},
{
"name": "JavaScript",
"bytes": "778699"
},
{
"name": "PowerShell",
"bytes": "3588"
},
{
"name": "TypeScript",
"bytes": "102108"
}
],
"symlink_target": ""
} |
package lab.s2jh.auth.dao.test;
import lab.s2jh.auth.dao.UserR2RoleDao;
import lab.s2jh.core.test.SpringTransactionalTestCase;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = { "classpath:/context/spring*.xml" })
public class UserR2RoleDaoTest extends SpringTransactionalTestCase {
@Autowired
private UserR2RoleDao userR2RoleDao;
@Test
public void findByUser_Id() {
userR2RoleDao.findByUser_Id("MOCKID");
}
}
| {
"content_hash": "6b50601918fb7002791cbf0b6bce7b16",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 71,
"avg_line_length": 30.263157894736842,
"alnum_prop": 0.7808695652173913,
"repo_name": "smilesman/s2jh",
"id": "90921a9890c5033c7e923a7a811e9cef8ab452b0",
"size": "575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common-service/src/test/java/lab/s2jh/auth/dao/test/UserR2RoleDaoTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
{{}}
{{ if (isset .Params "description") }}
<meta name="description" content="{{ .Site.Params.description }}"/>
{{ end }}
<link rel="image_src" type="image/png" href="{{ .Site.Params.seoImageMd }}" />
<meta name="twitter:title" content="{{ .Params.title }}">
<meta name="twitter:description" content="{{ .Params.description }}">
<meta name="twitter:image" content="{{ .Site.Params.seoImageMd | absURL }}">
<meta name="twitter:card" content="summary_large_image">
<meta itemprop="name" content="{{ .Params.title }}">
<meta itemprop="description" content="{{ .Params.description }}">
<meta itemprop="image" content="{{ .Site.Params.seoImageMd | absURL }}">
<meta property="og:title" content="{{ .Params.title }}">
<meta property="og:description" content="{{ .Params.description }}">
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:site_name" content="{{ .Site.Title }}">
<meta property="og:type" content="{{- if .IsPage -}}article{{- else -}}website{{- end -}}">
{{- with .Params.locale -}}
<meta property="og:locale" content="{{ .Site.Params.locale }}">
{{- end -}}
<meta property="og:image" content="{{ .Site.Params.seoImageLg | absURL }}" />
| {
"content_hash": "4979aefb00138ddb965c175441de7ff6",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 91,
"avg_line_length": 43.666666666666664,
"alnum_prop": 0.648854961832061,
"repo_name": "transparency-dev/binary-transparency-website",
"id": "16fc0423e41fc468fa3aefcf363a1ddf2fa86a1c",
"size": "1754",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "themes/binary/layouts/partials/document/seo.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "38259"
},
{
"name": "JavaScript",
"bytes": "40169"
},
{
"name": "SCSS",
"bytes": "103778"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<objectAnimator android:duration="1"
android:propertyName="elevation"
android:valueTo="4dp"
android:valueType="floatType"/>
</item>
</selector> | {
"content_hash": "4057dce392ae8be5a58ff6ae7f68c972",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 69,
"avg_line_length": 38.55555555555556,
"alnum_prop": 0.5590778097982709,
"repo_name": "TR4Android/AppCompat-Extension-Library",
"id": "be91e880d1a5d1240151a32e64b473767ae87a55",
"size": "347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/animator-v21/appbar_elevation.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "671433"
}
],
"symlink_target": ""
} |
using Aromato.Domain;
namespace Aromato.Infrastructure.Events
{
/// <summary>
/// Raises domain events.
/// </summary>
public class DomainEvent
{
/// <summary>
/// The domain event dispatcher.
/// </summary>
public static IEventDispatcher Dispatcher { get; set; }
/// <summary>
/// Raises a domain event.
/// </summary>
/// <param name="event">The event to raise.</param>
/// <typeparam name="TEvent">Domain event type.</typeparam>
public static void Raise<TEvent>(TEvent @event) where TEvent : IDomainEvent
{
Dispatcher?.Dispatch(@event);
}
}
}
| {
"content_hash": "bd8a75f98e6efeb02f054e7c2e5e3a00",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 83,
"avg_line_length": 28.333333333333332,
"alnum_prop": 0.5632352941176471,
"repo_name": "ferrerojosh/Aromato",
"id": "1612b52d3df7ca4b4b9ee9e6a34dfb8c1a1b988a",
"size": "682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Aromato/Infrastructure/Events/DomainEvent.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "102"
},
{
"name": "C#",
"bytes": "110244"
},
{
"name": "CSS",
"bytes": "9976"
},
{
"name": "HTML",
"bytes": "6723"
},
{
"name": "JavaScript",
"bytes": "12047"
},
{
"name": "TypeScript",
"bytes": "50659"
}
],
"symlink_target": ""
} |
/**
* @ignore
* 数据延迟加载组件
*/
KISSY.add('datalazyload', function (S, DOM, Event, Base, undefined) {
var win = S.Env.host,
doc = win.document,
IMG_SRC_DATA = 'data-ks-lazyload',
AREA_DATA_CLS = 'ks-datalazyload',
CUSTOM = '-custom',
DEFAULT = 'default',
NONE = 'none',
SCROLL = 'scroll',
TOUCH_MOVE = "touchmove",
RESIZE = 'resize',
DURATION = 100,
webpSupportMeta = {
detected: false,
supported: false
};
// 加载图片 src
var loadImgSrc = function (img, flag, webpFilter) {
flag = flag || IMG_SRC_DATA;
var dataSrc = img.getAttribute(flag),
realSrc = '';
if (dataSrc && img.src != dataSrc) {
if (webpFilter && webpSupportMeta.supported) {
if (S.isFunction(webpFilter)) {
realSrc = webpFilter(dataSrc, img);
} else if (S.isArray(webpFilter)) {
var i,
len = webpFilter.length,
rule;
for (i = 0; i < len; i++) {
rule = webpFilter[i];
if (dataSrc.match(rule[0])) {
realSrc = dataSrc.replace(rule[0], rule[1]);
break;
}
}
}
} else {
realSrc = dataSrc;
}
if (!realSrc) {
realSrc = dataSrc;
}
img.src = realSrc;
img.removeAttribute(flag);
}
};
// 从 textarea 中加载数据
function loadAreaData(textarea, execScript) {
// 采用隐藏 textarea 但不去除方式,去除会引发 Chrome 下错乱
textarea.style.display = NONE;
textarea.className = ''; // clear hook
var content = DOM.create('<div>');
// textarea 直接是 container 的儿子
textarea.parentNode.insertBefore(content, textarea);
DOM.html(content, textarea.value, execScript);
}
function getCallbackKey(el, fn) {
var id, fid;
if (!(id = el.id)) {
id = el.id = S.guid('ks-lazyload');
}
if (!(fid = fn.ksLazyloadId)) {
fid = fn.ksLazyloadId = S.guid('ks-lazyload');
}
return id + fid;
}
function cacheWidth(el) {
if (el._ks_lazy_width) {
return el._ks_lazy_width;
}
return el._ks_lazy_width = DOM.outerWidth(el);
}
function cacheHeight(el) {
if (el._ks_lazy_height) {
return el._ks_lazy_height;
}
return el._ks_lazy_height = DOM.outerHeight(el);
}
/**
* whether part of elem can be seen by user.
* note: it will not handle display none.
* @ignore
*/
function elementInViewport(elem, windowRegion, containerRegion) {
// it's better to removeElements,
// but if user want to append it later?
// use addElements instead
// if (!inDocument(elem)) {
// return false;
// }
// display none or inside display none
if (!elem.offsetWidth) {
return false;
}
var elemOffset = DOM.offset(elem),
inContainer = true,
inWin,
left = elemOffset.left,
top = elemOffset.top,
elemRegion = {
left: left,
top: top,
right: left + cacheWidth(elem),
bottom: top + cacheHeight(elem)
};
inWin = isCross(windowRegion, elemRegion);
if (inWin && containerRegion) {
inContainer = isCross(containerRegion, elemRegion);
}
// 确保在容器内出现
// 并且在视窗内也出现
return inContainer && inWin;
}
/**
* LazyLoad elements which are out of current viewPort.
* @class KISSY.DataLazyload
* @extends KISSY.Base
*/
function DataLazyload(container, config) {
var self = this;
// factory or constructor
if (!(self instanceof DataLazyload)) {
return new DataLazyload(container, config);
}
var newConfig = container;
if (!S.isPlainObject(newConfig)) {
newConfig = config || {};
if (container) {
newConfig.container = container;
}
}
DataLazyload.superclass.constructor.call(self, newConfig);
// 需要延迟下载的图片
// self._images
// 需要延迟处理的 textarea
// self._textareas
// 和延迟项绑定的回调函数
self._callbacks = {};
self._containerIsNotDocument = self.get('container').nodeType != 9;
self['_initLoadEvent']();
}
DataLazyload.ATTRS = {
/**
* Distance outside viewport or specified container to pre load.
* default: pre load one screen height and width.
* @cfg {Number|Object} diff
*
* for example:
*
* diff : 50 // pre load 50px outside viewport or specified container
* // or more detailed :
* diff: {
* left:20, // pre load 50px outside left edge of viewport or specified container
* right:30, // pre load 50px outside right edge of viewport or specified container
* top:50, // pre load 50px outside top edge of viewport or specified container
* bottom:60 // pre load 50px outside bottom edge of viewport or specified container
* }
*/
/**
* @ignore
*/
diff: {
value: DEFAULT
},
// TODO: add containerDiff for container is not document
/**
* Placeholder img url for lazy loaded _images if image 's src is empty.
* must be not empty!
*
* Defaults to: http://a.tbcdn.cn/kissy/1.0.0/build/imglazyload/spaceball.gif
* @cfg {String} placeholder
*/
/**
* @ignore
*/
placeholder: {
value: 'http://a.tbcdn.cn/kissy/1.0.0/build/imglazyload/spaceball.gif'
},
/**
* Whether execute script in lazy loaded textarea.
* default: true
* @cfg {Boolean} execScript
*/
/**
* @ignore
*/
execScript: {
value: true
},
/**
* Container which will be monitor scroll event to lazy load elements within it.
* default: document
* @cfg {HTMLElement} container
*/
/**
* @ignore
*/
container: {
setter: function (el) {
el = el || doc;
if (S.isWindow(el)) {
el = el.document;
} else {
el = DOM.get(el);
if (DOM.nodeName(el) == 'body') {
el = el.ownerDocument;
}
}
return el;
},
valueFn: function () {
return doc;
}
},
/**
* Whether destroy this component when all lazy loaded elements are loaded.
* default: true
* @cfg {Boolean} autoDestroy
*/
/**
* @ignore
*/
autoDestroy: {
value: true
},
/**
* Check whether current browser support webp and process each lazyload image.
* Defaults to: null.
* @cfg {Array|Function} webpFilter
*/
webpFilter: {
value: null
}
};
// 两块区域是否相交
function isCross(r1, r2) {
var r = {};
r.top = Math.max(r1.top, r2.top);
r.bottom = Math.min(r1.bottom, r2.bottom);
r.left = Math.max(r1.left, r2.left);
r.right = Math.min(r1.right, r2.right);
return r.bottom >= r.top && r.right >= r.left;
}
S.extend(DataLazyload, Base, {
/**
* get _images and _textareas which will lazyload.
* @private
*/
'_filterItems': function () {
var self = this,
userConfig = self.userConfig,
container = self.get("container"),
_images = [],
_textareas = [],
containers = [container];
// 兼容 1.2 传入数组,进入兼容模式,不检测 container 区域
if (S.isArray(userConfig.container)) {
self._backCompact = 1;
containers = userConfig.container;
}
S.each(containers, function (container) {
_images = _images.concat(S.filter(DOM.query('img', container), self['_filterImg'], self));
_textareas = _textareas.concat(DOM.query('textarea.' + AREA_DATA_CLS, container));
});
self._images = _images;
self._textareas = _textareas;
},
/**
* filter for lazyload image
* @private
*/
'_filterImg': function (img) {
var self = this,
placeholder = self.get("placeholder");
if (img.getAttribute(IMG_SRC_DATA)) {
if (!img.src) {
img.src = placeholder;
}
return true;
}
return undefined;
},
/**
* attach scroll/resize event
* @private
*/
'_initLoadEvent': function () {
var self = this,
img = new Image(),
placeholder = self.get("placeholder"),
autoDestroy = self.get("autoDestroy"),
// 加载延迟项
_loadItems = function () {
self['_loadItems']();
if (autoDestroy && self['_isLoadAllLazyElements']()) {
self.destroy();
}
},
loadItems = function () {
if (self.get('webpFilter')) {
checkWebpSupport(function () {
_loadItems()
});
} else {
_loadItems()
}
};
// 加载函数
self._loadFn = S.buffer(loadItems, DURATION, self);
img.src = placeholder;
function firstLoad() {
self['_filterItems']();
// 需要立即加载一次,以保证第一屏的延迟项可见
if (!self['_isLoadAllLazyElements']()) {
S.ready(loadItems);
}
self.resume();
}
if (img.complete) {
firstLoad()
} else {
img.onload = firstLoad;
}
},
/**
* force datalazyload to recheck constraints and load lazyload
*
*/
refresh: function () {
this._loadFn();
},
/**
* lazyload all items
* @private
*/
'_loadItems': function () {
var self = this,
containerRegion,
container = self.get('container'),
windowRegion;
// container is display none
if (self._containerIsNotDocument && !container.offsetWidth) {
return;
}
windowRegion = self['_getBoundingRect']();
// 兼容,不检测 container
if (!self._backCompact && self._containerIsNotDocument) {
containerRegion = self['_getBoundingRect'](self.get('container'));
}
self['_loadImgs'](windowRegion, containerRegion);
self['_loadTextAreas'](windowRegion, containerRegion);
self['_fireCallbacks'](windowRegion, containerRegion);
},
/**
* lazyload images
* @private
*/
'_loadImgs': function (windowRegion, containerRegion) {
var self = this;
self._images = S.filter(self._images, function (img) {
if (elementInViewport(img, windowRegion, containerRegion)) {
return loadImgSrc(img, undefined, self.get('webpFilter'));
} else {
return true;
}
}, self);
},
/**
* lazyload textareas
* @private
*/
'_loadTextAreas': function (windowRegion, containerRegion) {
var self = this, execScript = self.get('execScript');
self._textareas = S.filter(self._textareas, function (textarea) {
if (elementInViewport(textarea, windowRegion, containerRegion)) {
return loadAreaData(textarea, execScript);
} else {
return true;
}
}, self);
},
/**
* fire callbacks
* @private
*/
'_fireCallbacks': function (windowRegion, containerRegion) {
var self = this,
callbacks = self._callbacks;
// may call addCallback/removeCallback
S.each(callbacks, function (callback, key) {
var el = callback.el,
remove = false,
fn = callback.fn;
if (elementInViewport(el, windowRegion, containerRegion)) {
remove = fn.call(el);
}
if (remove !== false) {
delete callbacks[key];
}
});
},
/**
* Register callback function. When el is in viewport, then fn is called.
* @param {HTMLElement|String} el html element to be monitored.
* @param {function(this: HTMLElement): boolean} fn
* Callback function to be called when el is in viewport.
* return false to indicate el is actually not in viewport( for example display none element ).
*/
'addCallback': function (el, fn) {
var self = this,
callbacks = self._callbacks;
el = DOM.get(el);
callbacks[getCallbackKey(el, fn)] = {
el: DOM.get(el),
fn: fn
};
// add 立即检测,防止首屏元素问题
self._loadFn();
},
/**
* Remove a callback function. See {@link KISSY.DataLazyload#addCallback}
* @param {HTMLElement|String} el html element to be monitored.
* @param {Function} [fn] Callback function to be called when el is in viewport.
* If not specified, remove all callbacks associated with el.
*/
'removeCallback': function (el, fn) {
var callbacks = this._callbacks;
el = DOM.get(el);
delete callbacks[getCallbackKey(el, fn)];
},
/**
* get to be lazy loaded elements
* @return {Object} eg: {images:,textareas:}
*/
'getElements': function () {
return {
images: this._images,
textareas: this._textareas
};
},
/**
* Add a array of imgs or textareas to be lazy loaded to monitor list.
* @param {HTMLElement[]|String} els Array of imgs or textareas to be lazy loaded or selector
*/
'addElements': function (els) {
if (typeof els == 'string') {
els = DOM.query(els);
} else if (!S.isArray(els)) {
els = [els];
}
var self = this,
imgs = self._images || [],
textareas = self._textareas || [];
S.each(els, function (el) {
var nodeName = el.nodeName.toLowerCase();
if (nodeName == "img") {
if (!S.inArray(el, imgs)) {
imgs.push(el);
}
} else if (nodeName == "textarea") {
if (!S.inArray(el, textareas)) {
textareas.push(el);
}
}
});
self._images = imgs;
self._textareas = textareas;
},
/**
* Remove a array of element from monitor list. See {@link KISSY.DataLazyload#addElements}.
* @param {HTMLElement[]|String} els Array of imgs or textareas to be lazy loaded
*/
'removeElements': function (els) {
if (typeof els == 'string') {
els = DOM.query(els);
} else if (!S.isArray(els)) {
els = [els];
}
var self = this,
imgs = [],
textareas = [];
S.each(self._images, function (img) {
if (!S.inArray(img, els)) {
imgs.push(img);
}
});
S.each(self._textareas, function (textarea) {
if (!S.inArray(textarea, els)) {
textareas.push(textarea);
}
});
self._images = imgs;
self._textareas = textareas;
},
/**
* get c's bounding textarea.
* @param {window|HTMLElement} [c]
* @private
*/
'_getBoundingRect': function (c) {
var vh, vw, left, top;
if (c !== undefined) {
vh = DOM.outerHeight(c);
vw = DOM.outerWidth(c);
var offset = DOM.offset(c);
left = offset.left;
top = offset.top;
} else {
vh = DOM.viewportHeight();
vw = DOM.viewportWidth();
left = DOM.scrollLeft();
top = DOM.scrollTop();
}
var diff = this.get("diff"),
diffX = diff === DEFAULT ? vw : diff,
diffX0 = 0,
diffX1 = diffX,
diffY = diff === DEFAULT ? vh : diff,
// 兼容,默认只向下预读
diffY0 = 0,
diffY1 = diffY,
right = left + vw,
bottom = top + vh;
if (S.isObject(diff)) {
diffX0 = diff.left || 0;
diffX1 = diff.right || 0;
diffY0 = diff.top || 0;
diffY1 = diff.bottom || 0;
}
left -= diffX0;
right += diffX1;
top -= diffY0;
bottom += diffY1;
return {
left: left,
top: top,
right: right,
bottom: bottom
};
},
/**
* get num of items waiting to lazyload
* @private
*/
'_isLoadAllLazyElements': function () {
var self = this;
return (self._images.length +
self._textareas.length +
(S.isEmptyObject(self._callbacks) ? 0 : 1)) == 0;
},
/**
* pause lazyload
*/
pause: function () {
var self = this,
load = self._loadFn;
if (self._destroyed) {
return;
}
Event.remove(win, SCROLL, load);
Event.remove(win, TOUCH_MOVE, load);
Event.remove(win, RESIZE, load);
load.stop();
if (self._containerIsNotDocument) {
var c = self.get('container');
Event.remove(c, SCROLL, load);
Event.remove(c, TOUCH_MOVE, load);
}
},
/**
* resume lazyload
*/
resume: function () {
var self = this,
load = self._loadFn;
if (self._destroyed) {
return;
}
// scroll 和 resize 时,加载图片
Event.on(win, SCROLL, load);
Event.on(win, TOUCH_MOVE, load);
Event.on(win, RESIZE, load);
if (self._containerIsNotDocument) {
var c = self.get('container');
Event.on(c, SCROLL, load);
Event.on(c, TOUCH_MOVE, load);
}
},
/**
* Destroy this component.Will fire destroy event.
*/
destroy: function () {
var self = this;
self.pause();
self._callbacks = {};
self._images = [];
self._textareas = [];
S.log("datalazyload is destroyed!");
self.fire("destroy");
self._destroyed = 1;
}
});
/**
* Load lazyload textarea and imgs manually.
* @ignore
* @method
* @param {HTMLElement[]} containers Containers with in which lazy loaded elements are loaded.
* @param {String} type Type of lazy loaded element. "img" or "textarea"
* @param {String} [flag] flag which will be searched to find lazy loaded elements from containers.
* @param {Array|Function} [webpFilter] img src transformer when browser support webp image format
* Default "data-ks-lazyload-custom" for img attribute and "ks-lazyload-custom" for textarea css class.
*/
function loadCustomLazyData(containers, type, flag, webpFilter) {
if (webpFilter) {
checkWebpSupport(load);
} else {
load();
}
function load() {
if (type === 'img-src') {
type = 'img';
}
// 支持数组
if (!S.isArray(containers)) {
containers = [DOM.get(containers)];
}
var imgFlag = flag || (IMG_SRC_DATA + CUSTOM),
areaFlag = flag || (AREA_DATA_CLS + CUSTOM);
S.each(containers, function (container) {
var containerNodeName = DOM.nodeName(container);
// 遍历处理
if (type == 'img') {
if (containerNodeName == 'img') {
loadImgSrc(container, imgFlag, webpFilter);
} else {
DOM.query('img', container).each(function (img) {
loadImgSrc(img, imgFlag, webpFilter);
});
}
} else {
if (containerNodeName == 'textarea') {
if (DOM.hasClass(container, areaFlag)) {
loadAreaData(container, true);
}
} else {
DOM.query('textarea.' + areaFlag, container).each(function (textarea) {
loadAreaData(textarea, true);
});
}
}
});
}
}
DataLazyload.loadCustomLazyData = loadCustomLazyData;
/**
* check browser webp format support
* @ignore
* @method
* @param {Function} callback with first param{Boolean} telling whether webp is supported
*/
function checkWebpSupport(callback) {
if (webpSupportMeta.detected) {
callback(webpSupportMeta.supported);
} else {
var imgElem,
webpSrc = "data:image/webp;base64,UklGRjgAAABXRUJQVlA4ICwAAAAQAgCdASoEAAQAAAcIhYWIhYSIgIIADA1gAAUAAAEAAAEAAP7%2F2fIAAAAA";
imgElem = DOM.create('<img>');
Event.on(imgElem, 'load error', function (evt) {
var type = String(evt.type);
if (type == 'load') {
// 图片大小检测
webpSupportMeta.supported = Number(this.width) === 4;
} else if (type == 'error') {
webpSupportMeta.supported = false;
}
webpSupportMeta.detected = true;
callback(webpSupportMeta.supported);
});
DOM.attr(imgElem, "src", webpSrc);
}
}
DataLazyload.checkWebpSupport = checkWebpSupport;
S.DataLazyload = DataLazyload;
return DataLazyload;
}, { requires: ['dom', 'event', 'base'] });
/**
* @ignore
*
* NOTES:
*
* 模式为 auto 时:
* 1. 在 Firefox 下非常完美。脚本运行时,还没有任何图片开始下载,能真正做到延迟加载。
* 2. 在 IE 下不尽完美。脚本运行时,有部分图片已经与服务器建立链接,这部分 abort 掉,
* 再在滚动时延迟加载,反而增加了链接数。
* 3. 在 Safari 和 Chrome 下,因为 webkit 内核 bug,导致无法 abort 掉下载。该
* 脚本完全无用。
* 4. 在 Opera 下,和 Firefox 一致,完美。
* 5. 2010-07-12: 发现在 Firefox 下,也有导致部分 Aborted 链接。
*
* 模式为 manual 时:(要延迟加载的图片,src 属性替换为 data-lazyload-src, 并将 src 的值赋为 placeholder )
* 1. 在任何浏览器下都可以完美实现。
* 2. 缺点是不渐进增强,无 JS 时,图片不能展示。
*
* 缺点:
* 1. 对于大部分情况下,需要拖动查看内容的页面(比如搜索结果页),快速滚动时加载有损用
* 户体验(用户期望所滚即所得),特别是网速不好时。
* 2. auto 模式不支持 Webkit 内核浏览器;IE 下,有可能导致 HTTP 链接数的增加。
*
* 优点:
* 1. 可以很好的提高页面初始加载速度。
* 2. 第一屏就跳转,延迟加载图片可以减少流量。
*
* 参考资料:
* 1. http://davidwalsh.name/lazyload MooTools 的图片延迟插件
* 2. http://vip.qq.com/ 模板输出时,就替换掉图片的 src
* 3. http://www.appelsiini.net/projects/lazyload jQuery Lazyload
* 4. http://www.dynamixlabs.com/2008/01/17/a-quick-look-add-a-loading-icon-to-your-larger-_images/
* 5. http://www.nczonline.net/blog/2009/11/30/empty-image-src-can-destroy-your-site/
*
* 特别要注意的测试用例:
* 1. 初始窗口很小,拉大窗口时,图片加载正常
* 2. 页面有滚动位置时,刷新页面,图片加载正常
* 3. 手动模式,第一屏有延迟图片时,加载正常
*
* 2009-12-17 补充:
* 1. textarea 延迟加载约定:页面中需要延迟的 dom 节点,放在
* <textarea class='ks-datalazysrc invisible'>dom code</textarea>
* 里。可以添加 hidden 等 class, 但建议用 invisible, 并设定 height = '实际高度',这样可以保证
* 滚动时,diff 更真实有效。
* 注意:textarea 加载后,会替换掉父容器中的所有内容。
* 2. 延迟 callback 约定:dataLazyload.addCallback(el, fn) 表示当 el 即将出现时,触发 fn.
* 3. 所有操作都是最多触发一次,比如 callback. 来回拖动滚动条时,只有 el 第一次出现时会触发 fn 回调。
*
* xTODO:
* - [取消] 背景图片的延迟加载(对于 css 里的背景图片和 sprite 很难处理)
* - [取消] 加载时的 loading 图(对于未设定大小的图片,很难完美处理[参考资料 4])
*
* UPDATE LOG:
* - 2013-03-28 myhere.2009@gmail.com add support for webp
* - 2013-01-07 yiminghe@gmail.com optimize for performance
* - 2012-04-27 yiminghe@gmail.com refactor to extend base, add removeCallback/addElements ...
* - 2012-04-27 yiminghe@gmail.com 检查是否在视窗内改做判断区域相交,textarea 可设置高度,宽度
* - 2012-04-25 yiminghe@gmail.com refactor, 监控容器内滚动,包括横轴滚动
* - 2012-04-12 yiminghe@gmail.com monitor touchmove in ios
* - 2011-12-21 yiminghe@gmail.com 增加 removeElements 与 destroy 接口
* - 2010-07-31 yubo IMG_SRC_DATA 由 data-lazyload-src 更名为 data-ks-lazyload + 支持 touch 设备
* - 2010-07-10 yiminghe@gmail.com 重构,使用正则表达式识别 html 中的脚本,使用 EventTarget 自定义事件机制来处理回调
* - 2010-05-10 yubo ie6 下,在 dom ready 后执行,会导致 placeholder 重复加载,为比避免此问题,默认为 none, 去掉占位图
* - 2010-04-05 yubo 重构,使得对 YUI 的依赖仅限于 YDOM
* - 2009-12-17 yubo 将 imglazyload 升级为 datalazyload, 支持 textarea 方式延迟和特定元素即将出现时的回调函数
*/
| {
"content_hash": "9dcc6babfac61a34dfb7332ad42bf441",
"timestamp": "",
"source": "github",
"line_count": 842,
"max_line_length": 138,
"avg_line_length": 31.68764845605701,
"alnum_prop": 0.4796671788913459,
"repo_name": "007slm/kissy",
"id": "bdfc0bf4b6c3d43a46cef647ec8dcc6dc8b5e9c9",
"size": "28603",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/datalazyload/src/datalazyload.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
echo off
cd build\codegen
mvn clean install -Drelease
cd ..\..\..\
exit
| {
"content_hash": "d03e0fc04df8dca94e3b57bf7605aaf7",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 27,
"avg_line_length": 8.555555555555555,
"alnum_prop": 0.6493506493506493,
"repo_name": "gillesgagniard/wso2-wsf-cpp-gg",
"id": "797ecfc78d514c253e2370c2aa0ea727190d775e",
"size": "77",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "build_codegen.bat",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "29861"
},
{
"name": "C",
"bytes": "16839491"
},
{
"name": "C++",
"bytes": "2857127"
},
{
"name": "CSS",
"bytes": "19031"
},
{
"name": "Elixir",
"bytes": "10915"
},
{
"name": "Emacs Lisp",
"bytes": "1171"
},
{
"name": "Groff",
"bytes": "1776"
},
{
"name": "HTML",
"bytes": "629915"
},
{
"name": "Java",
"bytes": "1599729"
},
{
"name": "JavaScript",
"bytes": "13420"
},
{
"name": "Makefile",
"bytes": "177656"
},
{
"name": "Objective-C",
"bytes": "8687"
},
{
"name": "Perl",
"bytes": "398"
},
{
"name": "Shell",
"bytes": "114626"
},
{
"name": "XSLT",
"bytes": "2004578"
}
],
"symlink_target": ""
} |
namespace engine {
IonGunWeaponSubSystem::IonGunWeaponSubSystem()
: SubSystemHolder()
, mScene( Scene::Get() )
, mWeaponItemSubSystem( WeaponItemSubSystem::Get() )
, mActorFactory( ActorFactory::Get() )
, mShotId( AutoId( "ion_gun_projectile" ) )
, mAltShotId( AutoId( "ion_gun_alt_projectile" ) )
{
}
void IonGunWeaponSubSystem::Init()
{
SubSystemHolder::Init();
}
void IonGunWeaponSubSystem::Update( Actor& actor, double DeltaTime )
{
Opt<IInventoryComponent> inventoryC = actor.Get<IInventoryComponent>();
Opt<Weapon> weapon = inventoryC->GetSelectedWeapon();
if ( weapon->GetCooldown() > 0 )
{
return;
}
if ( weapon->IsShooting() )
{
WeaponItemSubSystem::Projectiles_t projectiles;
std::auto_ptr<Actor> ps = mActorFactory( mShotId );
projectiles.push_back( Opt<Actor>( ps.release() ) );
mWeaponItemSubSystem->AddProjectiles( actor, projectiles, weapon->GetScatter(), false );
}
else if ( weapon->IsShootingAlt() )
{
WeaponItemSubSystem::Projectiles_t projectiles;
std::auto_ptr<Actor> ps = mActorFactory( mAltShotId );
projectiles.push_back( Opt<Actor>( ps.release() ) );
mWeaponItemSubSystem->AddProjectiles( actor, projectiles, weapon->GetScatter(), true );
}
}
} // namespace engine
| {
"content_hash": "0b099ddc38b841b543daf386fa412402",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 96,
"avg_line_length": 28,
"alnum_prop": 0.6569940476190477,
"repo_name": "ishtoo/Reaping2",
"id": "3d2a95d36cd511c92aea7d46758e3e0cb0ea0d20",
"size": "1397",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/engine/items/ion_gun_weapon_sub_system.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "186"
},
{
"name": "C",
"bytes": "2129"
},
{
"name": "C++",
"bytes": "1815531"
},
{
"name": "CMake",
"bytes": "30910"
},
{
"name": "GLSL",
"bytes": "5930"
}
],
"symlink_target": ""
} |
CREATE USER 'blackuser'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
GRANT SELECT ,
INSERT ,
UPDATE ,
DELETE ,
USAGE ,
LOCK TABLES ON `rbl` . * TO 'blackuser'@'localhost';
ALTER USER 'blackuser'@'localhost' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
| {
"content_hash": "93afefd6b97f433ff1ab392a698f474b",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 137,
"avg_line_length": 33.3,
"alnum_prop": 0.7447447447447447,
"repo_name": "falon/RBL",
"id": "c3d29400f51fbef09824e90955c2d99b1ecf581a",
"size": "333",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/grant.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1330"
},
{
"name": "JavaScript",
"bytes": "3445"
},
{
"name": "PHP",
"bytes": "113614"
},
{
"name": "Shell",
"bytes": "243"
}
],
"symlink_target": ""
} |
from collections import namedtuple
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
print(tokyo)
print(tokyo.population)
print(tokyo.coordinates)
print(tokyo[1])
print(City._fields)
LatLong = namedtuple('LatLong', 'lat long')
delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
delhi = City._make(delhi_data)
print(delhi._asdict())
for key, val in delhi._asdict().items():
print(key + ':', val)
| {
"content_hash": "c5741cc91bec9b5f364a009142ec3d3f",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 71,
"avg_line_length": 27.77777777777778,
"alnum_prop": 0.7,
"repo_name": "eroicaleo/LearningPython",
"id": "416b82eeeed3cf02d4c01c48cd9ba4913b5d667e",
"size": "523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FluentPython/ch02/namedtuple.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18342"
},
{
"name": "HTML",
"bytes": "95429"
},
{
"name": "Java",
"bytes": "5182"
},
{
"name": "JavaScript",
"bytes": "31062"
},
{
"name": "Jupyter Notebook",
"bytes": "439846"
},
{
"name": "Makefile",
"bytes": "39"
},
{
"name": "Python",
"bytes": "1489221"
},
{
"name": "TeX",
"bytes": "795"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $tPluginTriggerStates</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 19:15:14 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('tPluginTriggerStates');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#tPluginTriggerStates">$tPluginTriggerStates</a></h2>
<b>Defined at:</b><ul>
<li><a href="../bonfire/libraries/CSSMin.php.html">/bonfire/libraries/CSSMin.php</A> -> <a href="../bonfire/libraries/CSSMin.php.source.html#l1616"> line 1616</A></li>
</ul>
<br><b>Referenced 3 times:</b><ul>
<li><a href="../bonfire/libraries/CSSMin.php.html">/bonfire/libraries/CSSMin.php</a> -> <a href="../bonfire/libraries/CSSMin.php.source.html#l1616"> line 1616</a></li>
<li><a href="../bonfire/libraries/CSSMin.php.html">/bonfire/libraries/CSSMin.php</a> -> <a href="../bonfire/libraries/CSSMin.php.source.html#l1617"> line 1617</a></li>
<li><a href="../bonfire/libraries/CSSMin.php.html">/bonfire/libraries/CSSMin.php</a> -> <a href="../bonfire/libraries/CSSMin.php.source.html#l1617"> line 1617</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 19:15:14 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "7a044995b5609b7c33f32920795e872f",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 253,
"avg_line_length": 52.173469387755105,
"alnum_prop": 0.6720125171132407,
"repo_name": "inputx/code-ref-doc",
"id": "66615ad81c5939500754bae12dc0aa113296ce12",
"size": "5113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rebbit/_variables/tPluginTriggerStates.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
Stevedore.Collections.Documents = Backbone.Collection.extend({
model: Stevedore.Models.Document,
});
| {
"content_hash": "edfea6b16fba9f256c3a049ae9dbcf8c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 62,
"avg_line_length": 34.333333333333336,
"alnum_prop": 0.7864077669902912,
"repo_name": "newsdev/stevedore",
"id": "dba2d6bc5a6a318015182ff3d58526deb1992f00",
"size": "103",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/collections/DocumentCollection.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10390"
},
{
"name": "CSS",
"bytes": "225189"
},
{
"name": "HTML",
"bytes": "46776"
},
{
"name": "JavaScript",
"bytes": "243538"
},
{
"name": "Ruby",
"bytes": "34380"
},
{
"name": "Shell",
"bytes": "12807"
}
],
"symlink_target": ""
} |
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
# This protects against multiple targets copying the same framework dependency at the same time. The solution
# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html
RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????")
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# Use filter instead of exclude so missing patterns don't throw errors.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Copies the dSYM of a vendored framework
install_dsym() {
local source="$1"
if [ -r "$source" ]; then
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}"
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'"
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
code_sign_cmd="$code_sign_cmd &"
fi
echo "$code_sign_cmd"
eval "$code_sign_cmd"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MBProgressHUD/MBProgressHUD.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MPColorTools/MPColorTools.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MZAppearance/MZAppearance.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MZFormSheetPresentationController/MZFormSheetPresentationController.framework"
install_framework "${BUILT_PRODUCTS_DIR}/NVHTarGzip/NVHTarGzip.framework"
install_framework "${BUILT_PRODUCTS_DIR}/SAMKeychain/SAMKeychain.framework"
install_framework "${BUILT_PRODUCTS_DIR}/SSZipArchive/SSZipArchive.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Socket.IO-Client-Swift/SocketIO.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework"
install_framework "${BUILT_PRODUCTS_DIR}/TMLKit/TMLKit.framework"
install_framework "${BUILT_PRODUCTS_DIR}/ViewDeck/ViewDeck.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MBProgressHUD/MBProgressHUD.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MPColorTools/MPColorTools.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MZAppearance/MZAppearance.framework"
install_framework "${BUILT_PRODUCTS_DIR}/MZFormSheetPresentationController/MZFormSheetPresentationController.framework"
install_framework "${BUILT_PRODUCTS_DIR}/NVHTarGzip/NVHTarGzip.framework"
install_framework "${BUILT_PRODUCTS_DIR}/SAMKeychain/SAMKeychain.framework"
install_framework "${BUILT_PRODUCTS_DIR}/SSZipArchive/SSZipArchive.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Socket.IO-Client-Swift/SocketIO.framework"
install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework"
install_framework "${BUILT_PRODUCTS_DIR}/TMLKit/TMLKit.framework"
install_framework "${BUILT_PRODUCTS_DIR}/ViewDeck/ViewDeck.framework"
fi
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
wait
fi
| {
"content_hash": "9a7c96e8a16e1960b3fcfa2404e36267",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 263,
"avg_line_length": 48.63157894736842,
"alnum_prop": 0.6808905380333952,
"repo_name": "translationexchange/tml-objc",
"id": "33e15a0c7954ede6743cc7214732adff02ebda5c",
"size": "6478",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Demo/Pods/Target Support Files/Pods-Demo/Pods-Demo-frameworks.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "343086"
},
{
"name": "C++",
"bytes": "19355"
},
{
"name": "Objective-C",
"bytes": "1703946"
},
{
"name": "Ruby",
"bytes": "10372"
},
{
"name": "Shell",
"bytes": "11954"
}
],
"symlink_target": ""
} |
/// <reference path="../../observable.ts" />
/// <reference path="../../concurrency/scheduler.ts" />
module Rx {
export interface Observable<T> {
/**
* Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds
*
* @param {Number} dueTime Relative or absolute time shift of the subscription.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
delaySubscription(dueTime: number, scheduler?: IScheduler): Observable<T>;
}
}
(function () {
var o: Rx.Observable<string>;
o.delaySubscription(1000);
o.delaySubscription(1000, Rx.Scheduler.timeout);
});
| {
"content_hash": "cd09d1e849ad45497f4e56f65da44f10",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 163,
"avg_line_length": 43.125,
"alnum_prop": 0.6502415458937199,
"repo_name": "docit/core",
"id": "236b80f494e9bf2aa379119c27f7bb7b7d001155",
"size": "1035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/assets/bower_components/rxjs/ts/core/linq/observable/delaysubscription.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "256140"
},
{
"name": "JavaScript",
"bytes": "1243869"
},
{
"name": "PHP",
"bytes": "96861"
}
],
"symlink_target": ""
} |
typedef char sh_name[64];
typedef struct st_EShaderList{
int count;
sh_name Names[1024];
}EShaderList;
#endif | {
"content_hash": "874b575a49f2615d9e1610c08af5d4bb",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 30,
"avg_line_length": 14.5,
"alnum_prop": 0.7241379310344828,
"repo_name": "Im-dex/xray-162",
"id": "db07bff743e3b594a5711bf09ee8e2235a888b99",
"size": "214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/plugins/lw/Shader/LW_Shader.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1642482"
},
{
"name": "C++",
"bytes": "22541957"
},
{
"name": "CMake",
"bytes": "636522"
},
{
"name": "Objective-C",
"bytes": "40174"
},
{
"name": "Pascal",
"bytes": "19058"
},
{
"name": "xBase",
"bytes": "151706"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.registry.metadata.parse;
import org.gbif.api.vocabulary.Language;
import org.gbif.registry.metadata.parse.converter.GreedyUriConverter;
import org.gbif.registry.metadata.parse.converter.LanguageTypeConverter;
import java.net.URI;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.RuleSetBase;
/**
* Digester rules to parse Dublin Core metadata documents together with a DatasetDelegator digester
* model.
*/
public class DublinCoreRuleSet extends RuleSetBase {
public DublinCoreRuleSet() {
super("http://purl.org/dc/terms/");
}
private void setupTypeConverters() {
GreedyUriConverter uriConverter = new GreedyUriConverter();
ConvertUtils.register(uriConverter, URI.class);
LanguageTypeConverter langConverter = new LanguageTypeConverter();
ConvertUtils.register(langConverter, Language.class);
}
@Override
public void addRuleInstances(Digester digester) {
setupTypeConverters();
// add the rules
digester.addCallMethod("*/protocol", "throwIllegalArgumentException");
digester.addBeanPropertySetter("*/title", "title");
digester.addCallMethod("*/abstract", "addAbstract", 0);
digester.addBeanPropertySetter("*/description", "description");
digester.addCallMethod("*/subject", "addSubjects", 0);
digester.addBeanPropertySetter("*/language", "dataLanguage");
digester.addBeanPropertySetter("*/source", "homepage");
digester.addCallMethod("*/isFormatOf", "addDataUrl", 0, new Class[] {URI.class});
digester.addCallMethod("*/creator", "addCreator", 0);
digester.addCallMethod("*/created", "setPubDateAsString", 0);
// License parsed from rights?
digester.addCallMethod("*/rights", "setLicense", 2);
digester.addCallParam("*/rights", 1);
// License parsed from license?
digester.addCallMethod("*/license", "setLicense", 2);
digester.addCallParam("*/license", 0);
digester.addCallMethod("*/bibliographicCitation", "addBibCitation", 0);
digester.addCallMethod("*/identifier", "addIdentifier", 0);
}
}
| {
"content_hash": "48f8cf60fbfef563a3270f11962bbe9f",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 99,
"avg_line_length": 37.27777777777778,
"alnum_prop": 0.7384500745156483,
"repo_name": "gbif/registry",
"id": "8e9e27ddf2d7d50702a0b83f03eb915c57d8b81b",
"size": "2684",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "registry-metadata/src/main/java/org/gbif/registry/metadata/parse/DublinCoreRuleSet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "192231"
},
{
"name": "Java",
"bytes": "3445231"
},
{
"name": "PLpgSQL",
"bytes": "30939"
},
{
"name": "Shell",
"bytes": "10935"
},
{
"name": "XSLT",
"bytes": "534"
}
],
"symlink_target": ""
} |
var gulp = require('gulp');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var notify = require('gulp-notify');
var cleanCSS = require('gulp-clean-css');
var minifyJS = require('gulp-minify');
var rename = require('gulp-rename');
var webserver = require('gulp-webserver');
gulp.task('scss', function () {
gulp.src('./src/scss/countrySelect.scss')
.pipe(sass({ errLogToConsole: true }))
.pipe(prefix())
.pipe(cleanCSS({compatibility: 'ie8', format: {
breaks: {
afterAtRule: true,
afterBlockBegins: true,
afterBlockEnds: true,
afterComment: true,
afterProperty: true,
afterRuleBegins: true,
afterRuleEnds: true,
beforeBlockEnds: true,
betweenSelectors: true
},
indentBy: 1,
indentWith: 'tab' }, level: 0}))
.pipe(gulp.dest('./build/css'))
.pipe(notify("styles compiled"));
});
gulp.task('js', function () {
gulp.src('./src/js/countrySelect.js')
.pipe(gulp.dest('./build/js'))
.pipe(notify("javascript updated"));
});
gulp.task('handle-sources', ['scss', 'js']);
gulp.task('minify-scss', function () {
gulp.src('./build/css/countrySelect.css')
.pipe(cleanCSS({level: 2, inline: ['all']}))
.pipe(rename({extname: '.min.css'}))
.pipe(gulp.dest('./build/css'))
.pipe(notify("styles minified"));
});
gulp.task('minify-js', function () {
gulp.src('./build/js/countrySelect.js')
.pipe(minifyJS({ext:{min:'.min.js'}}))
.pipe(gulp.dest('./build/js'))
.pipe(notify("javascript minified"));
});
gulp.task('minify-sources', ['minify-scss', 'minify-js']);
gulp.task('webserver', function() {
gulp.src('.')
.pipe(webserver({
livereload: true,
directoryListing: true,
open: './demo.html'
}));
gulp.watch('./src/scss/**/*.scss', ['scss']);
gulp.watch('./src/js/**/*.js', ['js']);
});
gulp.task('default', ['handle-sources', 'webserver']);
gulp.task('build', ['handle-sources', 'minify-sources']);
| {
"content_hash": "40df61f8ebe264e319d05d887731a94f",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 58,
"avg_line_length": 27.72463768115942,
"alnum_prop": 0.6351280710925248,
"repo_name": "AlpenDesignStudio/twex",
"id": "73884f9816692fc9f331cb6656fe68e67c04f7be",
"size": "1913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/country-select-js/gulpfile.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "868093"
},
{
"name": "HTML",
"bytes": "1343073"
},
{
"name": "JavaScript",
"bytes": "781497"
},
{
"name": "PHP",
"bytes": "2925470"
},
{
"name": "Python",
"bytes": "32324"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>abp: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.2 / abp - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
abp
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-24 11:01:54 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-24 11:01:54 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/abp"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ABP"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [
"keyword:alternating bit protocol"
"keyword:process calculi"
"keyword:reactive systems"
"keyword:co-inductive types"
"keyword:co-induction"
"category:Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols"
]
authors: [ "Eduardo Giménez <>" ]
bug-reports: "https://github.com/coq-contribs/abp/issues"
dev-repo: "git+https://github.com/coq-contribs/abp.git"
synopsis: "A verification of the alternating bit protocol expressed in CBS"
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/abp/archive/v8.5.0.tar.gz"
checksum: "md5=9df2a01467f74d04c7eaeec6ebf6d2d9"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-abp.8.5.0 coq.8.13.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.2).
The following dependencies couldn't be met:
- coq-abp -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-abp.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "36759f0230210622b61fd9a8168d9e80",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 159,
"avg_line_length": 40.916666666666664,
"alnum_prop": 0.5394239162059936,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "45641983803e1cba7176d5191429073c2216315e",
"size": "6900",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.13.2/abp/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.elasticsearch.xpack.ml.job;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.persistent.PersistentTasksCustomMetadata;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.core.ml.MlTasks;
import org.elasticsearch.xpack.core.ml.action.StartDataFrameAnalyticsAction;
import org.elasticsearch.xpack.core.ml.action.StartDataFrameAnalyticsAction.TaskParams;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsState;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsTaskState;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.job.config.JobState;
import org.elasticsearch.xpack.ml.MachineLearning;
import org.elasticsearch.xpack.ml.autoscaling.NativeMemoryCapacity;
import org.elasticsearch.xpack.ml.job.task.OpenJobPersistentTasksExecutorTests;
import org.elasticsearch.xpack.ml.action.TransportStartDataFrameAnalyticsAction;
import org.elasticsearch.xpack.ml.process.MlMemoryTracker;
import org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase;
import org.junit.Before;
import java.net.InetAddress;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import static org.elasticsearch.xpack.core.ml.job.config.JobTests.buildJobBuilder;
import static org.elasticsearch.xpack.ml.job.task.OpenJobPersistentTasksExecutor.nodeFilter;
import static org.elasticsearch.xpack.ml.job.task.OpenJobPersistentTasksExecutorTests.jobWithRules;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
// TODO: in 8.0.0 remove all instances of MAX_OPEN_JOBS_NODE_ATTR from this file
public class JobNodeSelectorTests extends ESTestCase {
// To simplify the logic in this class all jobs have the same memory requirement
private static final long MAX_JOB_BYTES = ByteSizeValue.ofGb(1).getBytes();
private static final ByteSizeValue JOB_MEMORY_REQUIREMENT = ByteSizeValue.ofMb(10);
private MlMemoryTracker memoryTracker;
private boolean isMemoryTrackerRecentlyRefreshed;
@Before
public void setup() {
memoryTracker = mock(MlMemoryTracker.class);
isMemoryTrackerRecentlyRefreshed = true;
when(memoryTracker.isRecentlyRefreshed()).thenReturn(isMemoryTrackerRecentlyRefreshed, false);
when(memoryTracker.getAnomalyDetectorJobMemoryRequirement(anyString())).thenReturn(JOB_MEMORY_REQUIREMENT.getBytes());
when(memoryTracker.getDataFrameAnalyticsJobMemoryRequirement(anyString())).thenReturn(JOB_MEMORY_REQUIREMENT.getBytes());
when(memoryTracker.getJobMemoryRequirement(anyString(), anyString())).thenReturn(JOB_MEMORY_REQUIREMENT.getBytes());
}
public void testNodeNameAndVersion() {
TransportAddress ta = new TransportAddress(InetAddress.getLoopbackAddress(), 9300);
Map<String, String> attributes = new HashMap<>();
attributes.put("unrelated", "attribute");
DiscoveryNode node = new DiscoveryNode("_node_name1", "_node_id1", ta, attributes, Collections.emptySet(), Version.CURRENT);
assertEquals("{_node_name1}{version=" + node.getVersion() + "}", JobNodeSelector.nodeNameAndVersion(node));
}
public void testNodeNameAndMlAttributes() {
TransportAddress ta = new TransportAddress(InetAddress.getLoopbackAddress(), 9300);
SortedMap<String, String> attributes = new TreeMap<>();
attributes.put("unrelated", "attribute");
DiscoveryNode node = new DiscoveryNode("_node_name1", "_node_id1", ta, attributes, Collections.emptySet(), Version.CURRENT);
assertEquals("{_node_name1}", JobNodeSelector.nodeNameAndMlAttributes(node));
attributes.put("ml.machine_memory", "5");
node = new DiscoveryNode("_node_name1", "_node_id1", ta, attributes, Collections.emptySet(), Version.CURRENT);
assertEquals("{_node_name1}{ml.machine_memory=5}", JobNodeSelector.nodeNameAndMlAttributes(node));
node = new DiscoveryNode(null, "_node_id1", ta, attributes, Collections.emptySet(), Version.CURRENT);
assertEquals("{_node_id1}{ml.machine_memory=5}", JobNodeSelector.nodeNameAndMlAttributes(node));
}
public void testSelectLeastLoadedMlNode_byCount() {
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10");
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, "-1");
// MachineLearning.MACHINE_MEMORY_NODE_ATTR negative, so this will fall back to allocating by count
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name3", "_node_id3", new TransportAddress(InetAddress.getLoopbackAddress(), 9302),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("job_id1", "_node_id1", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id2", "_node_id1", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id3", "_node_id2", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
cs.nodes(nodes);
Metadata.Builder metadata = Metadata.builder();
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
cs.metadata(metadata);
Job.Builder jobBuilder = buildJobBuilder("job_id4");
jobBuilder.setJobVersion(Version.CURRENT);
Job job = jobBuilder.build();
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(10,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertEquals("", result.getExplanation());
assertEquals("_node_id3", result.getExecutorNode());
}
public void testSelectLeastLoadedMlNodeForAnomalyDetectorJob_maxCapacityCountLimiting() {
int numNodes = randomIntBetween(1, 10);
int maxRunningJobsPerNode = randomIntBetween(1, 100);
int maxMachineMemoryPercent = 30;
long machineMemory = (maxRunningJobsPerNode + 1) * JOB_MEMORY_REQUIREMENT.getBytes() * 100 / maxMachineMemoryPercent;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(machineMemory));
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, maxRunningJobsPerNode);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id1000", JOB_MEMORY_REQUIREMENT).build(new Date());
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull(result.getExecutorNode());
assertThat(result.getExplanation(), containsString("because this node is full. Number of opened jobs ["
+ maxRunningJobsPerNode + "], xpack.ml.max_open_jobs [" + maxRunningJobsPerNode + "]"));
}
public void testSelectLeastLoadedMlNodeForDataFrameAnalyticsJob_maxCapacityCountLimiting() {
int numNodes = randomIntBetween(1, 10);
int maxRunningJobsPerNode = randomIntBetween(1, 100);
int maxMachineMemoryPercent = 30;
long machineMemory = (maxRunningJobsPerNode + 1) * JOB_MEMORY_REQUIREMENT.getBytes() * 100 / maxMachineMemoryPercent;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(machineMemory));
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, maxRunningJobsPerNode);
String dataFrameAnalyticsId = "data_frame_analytics_id1000";
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), dataFrameAnalyticsId,
MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME, memoryTracker, 0,
node -> TransportStartDataFrameAnalyticsAction.TaskExecutor.nodeFilter(node, createTaskParams(dataFrameAnalyticsId)));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull(result.getExecutorNode());
assertThat(result.getExplanation(), containsString("because this node is full. Number of opened jobs ["
+ maxRunningJobsPerNode + "], xpack.ml.max_open_jobs [" + maxRunningJobsPerNode + "]"));
}
public void testSelectLeastLoadedMlNodeForAnomalyDetectorJob_maxCapacityMemoryLimiting() {
int numNodes = randomIntBetween(1, 10);
int currentlyRunningJobsPerNode = randomIntBetween(1, 100);
int maxRunningJobsPerNode = currentlyRunningJobsPerNode + 1;
// Be careful if changing this - in order for the error message to be exactly as expected
// the value here must divide exactly into both (JOB_MEMORY_REQUIREMENT.getBytes() * 100) and
// MachineLearning.NATIVE_EXECUTABLE_CODE_OVERHEAD.getBytes()
int maxMachineMemoryPercent = 20;
long currentlyRunningJobMemory = MachineLearning.NATIVE_EXECUTABLE_CODE_OVERHEAD.getBytes() +
currentlyRunningJobsPerNode * JOB_MEMORY_REQUIREMENT.getBytes();
long machineMemory = currentlyRunningJobMemory * 100 / maxMachineMemoryPercent;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(machineMemory));
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, currentlyRunningJobsPerNode);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id1000", JOB_MEMORY_REQUIREMENT).build(new Date());
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull(result.getExecutorNode());
assertThat(result.getExplanation(), containsString("because this node has insufficient available memory. "
+ "Available memory for ML [" + currentlyRunningJobMemory + "], memory required by existing jobs ["
+ currentlyRunningJobMemory + "], estimated memory required for this job [" + JOB_MEMORY_REQUIREMENT.getBytes() + "]"));
}
public void testSelectLeastLoadedMlNodeForDataFrameAnalyticsJob_givenTaskHasNullState() {
int numNodes = randomIntBetween(1, 10);
int maxRunningJobsPerNode = 10;
int maxMachineMemoryPercent = 30;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, "-1");
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, 1, JobState.OPENED, null);
String dataFrameAnalyticsId = "data_frame_analytics_id_new";
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), dataFrameAnalyticsId,
MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME, memoryTracker, 0,
node -> TransportStartDataFrameAnalyticsAction.TaskExecutor.nodeFilter(node, createTaskParams(dataFrameAnalyticsId)));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNotNull(result.getExecutorNode());
}
public void testSelectLeastLoadedMlNodeForAnomalyDetectorJob_firstJobTooBigMemoryLimiting() {
int numNodes = randomIntBetween(1, 10);
int maxRunningJobsPerNode = randomIntBetween(1, 100);
int maxMachineMemoryPercent = 20;
long firstJobTotalMemory = MachineLearning.NATIVE_EXECUTABLE_CODE_OVERHEAD.getBytes() + JOB_MEMORY_REQUIREMENT.getBytes();
long machineMemory = (firstJobTotalMemory - 1) * 100 / maxMachineMemoryPercent;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(machineMemory));
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, 0);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id1000", JOB_MEMORY_REQUIREMENT).build(new Date());
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker,
0, node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull(result.getExecutorNode());
assertThat(result.getExplanation(), containsString("because this node has insufficient available memory. "
+ "Available memory for ML [" + (firstJobTotalMemory - 1)
+ "], memory required by existing jobs [0], estimated memory required for this job [" + firstJobTotalMemory + "]"));
}
public void testSelectLeastLoadedMlNodeForDataFrameAnalyticsJob_maxCapacityMemoryLimiting() {
int numNodes = randomIntBetween(1, 10);
int currentlyRunningJobsPerNode = randomIntBetween(1, 100);
int maxRunningJobsPerNode = currentlyRunningJobsPerNode + 1;
// Be careful if changing this - in order for the error message to be exactly as expected
// the value here must divide exactly into both (JOB_MEMORY_REQUIREMENT.getBytes() * 100) and
// MachineLearning.NATIVE_EXECUTABLE_CODE_OVERHEAD.getBytes()
int maxMachineMemoryPercent = 20;
long currentlyRunningJobMemory = MachineLearning.NATIVE_EXECUTABLE_CODE_OVERHEAD.getBytes() +
currentlyRunningJobsPerNode * JOB_MEMORY_REQUIREMENT.getBytes();
long machineMemory = currentlyRunningJobMemory * 100 / maxMachineMemoryPercent;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(machineMemory));
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, currentlyRunningJobsPerNode);
String dataFrameAnalyticsId = "data_frame_analytics_id1000";
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), dataFrameAnalyticsId,
MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME, memoryTracker, 0,
node -> TransportStartDataFrameAnalyticsAction.TaskExecutor.nodeFilter(node, createTaskParams(dataFrameAnalyticsId)));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(
maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull(result.getExecutorNode());
assertThat(result.getExplanation(), containsString("because this node has insufficient available memory. "
+ "Available memory for ML [" + currentlyRunningJobMemory + "], memory required by existing jobs ["
+ currentlyRunningJobMemory + "], estimated memory required for this job [" + JOB_MEMORY_REQUIREMENT.getBytes() + "]"));
}
public void testSelectLeastLoadedMlNodeForDataFrameAnalyticsJob_firstJobTooBigMemoryLimiting() {
int numNodes = randomIntBetween(1, 10);
int maxRunningJobsPerNode = randomIntBetween(1, 100);
int maxMachineMemoryPercent = 20;
long firstJobTotalMemory = MachineLearning.NATIVE_EXECUTABLE_CODE_OVERHEAD.getBytes() + JOB_MEMORY_REQUIREMENT.getBytes();
long machineMemory = (firstJobTotalMemory - 1) * 100 / maxMachineMemoryPercent;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(machineMemory));
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, 0);
String dataFrameAnalyticsId = "data_frame_analytics_id1000";
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), dataFrameAnalyticsId,
MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME, memoryTracker, 0,
node -> TransportStartDataFrameAnalyticsAction.TaskExecutor.nodeFilter(node, createTaskParams(dataFrameAnalyticsId)));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(
maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull(result.getExecutorNode());
assertThat(result.getExplanation(), containsString("because this node has insufficient available memory. "
+ "Available memory for ML [" + (firstJobTotalMemory - 1)
+ "], memory required by existing jobs [0], estimated memory required for this job [" + firstJobTotalMemory + "]"));
}
public void testSelectLeastLoadedMlNode_noMlNodes() {
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
Collections.emptyMap(), Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
Collections.emptyMap(), Collections.emptySet(), Version.CURRENT))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("job_id1", "_node_id1", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
Metadata.Builder metadata = Metadata.builder();
cs.nodes(nodes);
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
cs.metadata(metadata);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id2", JOB_MEMORY_REQUIREMENT).build(new Date());
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(
20,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertTrue(result.getExplanation().contains("because this node isn't a ml node"));
assertNull(result.getExecutorNode());
}
public void testSelectLeastLoadedMlNode_maxConcurrentOpeningJobs() {
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10");
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, "1000000000");
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name3", "_node_id3", new TransportAddress(InetAddress.getLoopbackAddress(), 9302),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("job_id1", "_node_id1", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id2", "_node_id1", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id3", "_node_id2", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id4", "_node_id2", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id5", "_node_id3", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder csBuilder = ClusterState.builder(new ClusterName("_name"));
csBuilder.nodes(nodes);
Metadata.Builder metadata = Metadata.builder();
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
csBuilder.metadata(metadata);
Job job6 = BaseMlIntegTestCase.createFareQuoteJob("job_id6", JOB_MEMORY_REQUIREMENT).build(new Date());
ClusterState cs = csBuilder.build();
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs, job6.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job6));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(
10,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertEquals("_node_id3", result.getExecutorNode());
tasksBuilder = PersistentTasksCustomMetadata.builder(tasks);
OpenJobPersistentTasksExecutorTests.addJobTask(job6.getId(), "_node_id3", null, tasksBuilder);
tasks = tasksBuilder.build();
csBuilder = ClusterState.builder(cs);
csBuilder.metadata(Metadata.builder(cs.metadata()).putCustom(PersistentTasksCustomMetadata.TYPE, tasks));
cs = csBuilder.build();
Job job7 = BaseMlIntegTestCase.createFareQuoteJob("job_id7", JOB_MEMORY_REQUIREMENT).build(new Date());
jobNodeSelector = new JobNodeSelector(cs, job7.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job7));
result = jobNodeSelector.selectNode(10,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull("no node selected, because OPENING state", result.getExecutorNode());
assertTrue(result.getExplanation().contains("because node exceeds [2] the maximum number of jobs [2] in opening state"));
tasksBuilder = PersistentTasksCustomMetadata.builder(tasks);
tasksBuilder.reassignTask(MlTasks.jobTaskId(job6.getId()),
new PersistentTasksCustomMetadata.Assignment("_node_id3", "test assignment"));
tasks = tasksBuilder.build();
csBuilder = ClusterState.builder(cs);
csBuilder.metadata(Metadata.builder(cs.metadata()).putCustom(PersistentTasksCustomMetadata.TYPE, tasks));
cs = csBuilder.build();
jobNodeSelector = new JobNodeSelector(cs, job7.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job7));
result = jobNodeSelector.selectNode(10, 2, 30, MAX_JOB_BYTES, isMemoryTrackerRecentlyRefreshed, false);
assertNull("no node selected, because stale task", result.getExecutorNode());
assertTrue(result.getExplanation().contains("because node exceeds [2] the maximum number of jobs [2] in opening state"));
tasksBuilder = PersistentTasksCustomMetadata.builder(tasks);
tasksBuilder.updateTaskState(MlTasks.jobTaskId(job6.getId()), null);
tasks = tasksBuilder.build();
csBuilder = ClusterState.builder(cs);
csBuilder.metadata(Metadata.builder(cs.metadata()).putCustom(PersistentTasksCustomMetadata.TYPE, tasks));
cs = csBuilder.build();
jobNodeSelector = new JobNodeSelector(cs, job7.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job7));
result = jobNodeSelector.selectNode(10, 2, 30, MAX_JOB_BYTES, isMemoryTrackerRecentlyRefreshed, false);
assertNull("no node selected, because null state", result.getExecutorNode());
assertTrue(result.getExplanation().contains("because node exceeds [2] the maximum number of jobs [2] in opening state"));
}
public void testSelectLeastLoadedMlNode_concurrentOpeningJobsAndStaleFailedJob() {
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10");
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, "1000000000");
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name3", "_node_id3", new TransportAddress(InetAddress.getLoopbackAddress(), 9302),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("job_id1", "_node_id1", JobState.fromString("failed"), tasksBuilder);
// This will make the allocation stale for job_id1
tasksBuilder.reassignTask(MlTasks.jobTaskId("job_id1"),
new PersistentTasksCustomMetadata.Assignment("_node_id1", "test assignment"));
OpenJobPersistentTasksExecutorTests.addJobTask("job_id2", "_node_id1", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id3", "_node_id2", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id4", "_node_id2", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id5", "_node_id3", null, tasksBuilder);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id6", "_node_id3", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder csBuilder = ClusterState.builder(new ClusterName("_name"));
csBuilder.nodes(nodes);
Metadata.Builder metadata = Metadata.builder();
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
csBuilder.metadata(metadata);
ClusterState cs = csBuilder.build();
Job job7 = BaseMlIntegTestCase.createFareQuoteJob("job_id7", JOB_MEMORY_REQUIREMENT).build(new Date());
// Allocation won't be possible if the stale failed job is treated as opening
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs, job7.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job7));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(10,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertEquals("_node_id1", result.getExecutorNode());
tasksBuilder = PersistentTasksCustomMetadata.builder(tasks);
OpenJobPersistentTasksExecutorTests.addJobTask("job_id7", "_node_id1", null, tasksBuilder);
tasks = tasksBuilder.build();
csBuilder = ClusterState.builder(cs);
csBuilder.metadata(Metadata.builder(cs.metadata()).putCustom(PersistentTasksCustomMetadata.TYPE, tasks));
cs = csBuilder.build();
Job job8 = BaseMlIntegTestCase.createFareQuoteJob("job_id8", JOB_MEMORY_REQUIREMENT).build(new Date());
jobNodeSelector = new JobNodeSelector(cs, job8.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job8));
result = jobNodeSelector.selectNode(10, 2, 30, MAX_JOB_BYTES, isMemoryTrackerRecentlyRefreshed, false);
assertNull("no node selected, because OPENING state", result.getExecutorNode());
assertTrue(result.getExplanation().contains("because node exceeds [2] the maximum number of jobs [2] in opening state"));
}
public void testSelectLeastLoadedMlNode_noCompatibleJobTypeNodes() {
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10");
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, "1000000000");
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
nodeAttr, Collections.emptySet(), Version.CURRENT))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("incompatible_type_job", "_node_id1", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
Metadata.Builder metadata = Metadata.builder();
Job job = mock(Job.class);
when(job.getId()).thenReturn("incompatible_type_job");
when(job.getJobVersion()).thenReturn(Version.CURRENT);
when(job.getJobType()).thenReturn("incompatible_type");
when(job.getInitialResultsIndexName()).thenReturn("shared");
cs.nodes(nodes);
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
cs.metadata(metadata);
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(10,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertThat(result.getExplanation(), containsString("because this node does not support jobs of type [incompatible_type]"));
assertNull(result.getExecutorNode());
}
public void testSelectLeastLoadedMlNode_noNodesMatchingModelSnapshotMinVersion() {
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10");
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, "1000000000");
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
nodeAttr, Collections.emptySet(), Version.fromString("6.2.0")))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
nodeAttr, Collections.emptySet(), Version.fromString("6.1.0")))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("job_with_incompatible_model_snapshot", "_node_id1", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
Metadata.Builder metadata = Metadata.builder();
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_with_incompatible_model_snapshot")
.setModelSnapshotId("incompatible_snapshot")
.setModelSnapshotMinVersion(Version.fromString("6.3.0"))
.build(new Date());
cs.nodes(nodes);
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
cs.metadata(metadata);
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(),
MlTasks.JOB_TASK_NAME, memoryTracker, 0, node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(10,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertThat(result.getExplanation(), containsString(
"because the job's model snapshot requires a node of version [6.3.0] or higher"));
assertNull(result.getExecutorNode());
}
public void testSelectLeastLoadedMlNode_jobWithRules() {
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10");
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, "1000000000");
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
nodeAttr, Collections.emptySet(), Version.fromString("6.2.0")))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
nodeAttr, Collections.emptySet(), Version.fromString("6.4.0")))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("job_with_rules", "_node_id1", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
Metadata.Builder metadata = Metadata.builder();
cs.nodes(nodes);
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
cs.metadata(metadata);
Job job = jobWithRules("job_with_rules");
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(10,
2,
30,
MAX_JOB_BYTES,
isMemoryTrackerRecentlyRefreshed,
false);
assertNotNull(result.getExecutorNode());
}
public void testConsiderLazyAssignmentWithNoLazyNodes() {
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
Collections.emptyMap(), Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
Collections.emptyMap(), Collections.emptySet(), Version.CURRENT))
.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
cs.nodes(nodes);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id1000", JOB_MEMORY_REQUIREMENT).build(new Date());
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result =
jobNodeSelector.considerLazyAssignment(new PersistentTasksCustomMetadata.Assignment(null, "foo"));
assertEquals("foo", result.getExplanation());
assertNull(result.getExecutorNode());
}
public void testConsiderLazyAssignmentWithLazyNodes() {
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("_node_name1", "_node_id1", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
Collections.emptyMap(), Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode("_node_name2", "_node_id2", new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
Collections.emptyMap(), Collections.emptySet(), Version.CURRENT))
.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
cs.nodes(nodes);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id1000", JOB_MEMORY_REQUIREMENT).build(new Date());
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker,
randomIntBetween(1, 3), node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result =
jobNodeSelector.considerLazyAssignment(new PersistentTasksCustomMetadata.Assignment(null, "foo"));
assertEquals(JobNodeSelector.AWAITING_LAZY_ASSIGNMENT.getExplanation(), result.getExplanation());
assertNull(result.getExecutorNode());
}
public void testMaximumPossibleNodeMemoryTooSmall() {
int numNodes = randomIntBetween(1, 10);
int maxRunningJobsPerNode = randomIntBetween(1, 100);
int maxMachineMemoryPercent = 30;
long machineMemory = (maxRunningJobsPerNode + 1) * JOB_MEMORY_REQUIREMENT.getBytes() * 100 / maxMachineMemoryPercent;
Map<String, String> nodeAttr = new HashMap<>();
nodeAttr.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, Integer.toString(maxRunningJobsPerNode));
nodeAttr.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(machineMemory));
ClusterState.Builder cs = fillNodesWithRunningJobs(nodeAttr, numNodes, maxRunningJobsPerNode);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id1000", ByteSizeValue.ofMb(10)).build(new Date());
when(memoryTracker.getJobMemoryRequirement(anyString(), eq("job_id1000"))).thenReturn(1000L);
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker,
randomIntBetween(1, 3),
node -> nodeFilter(node, job));
PersistentTasksCustomMetadata.Assignment result = jobNodeSelector.selectNode(maxRunningJobsPerNode,
2,
maxMachineMemoryPercent,
10L,
isMemoryTrackerRecentlyRefreshed,
false);
assertNull(result.getExecutorNode());
assertThat(result.getExplanation(),
containsString("[job_id1000] not waiting for node assignment as estimated job size " +
"[31458280] is greater than largest possible job size [3]"));
}
public void testPerceivedCapacityAndMaxFreeMemory() {
DiscoveryNodes nodes = DiscoveryNodes.builder()
.add(new DiscoveryNode("not_ml_node_name", "_node_id", new TransportAddress(InetAddress.getLoopbackAddress(), 9300),
Collections.emptyMap(), Collections.emptySet(), Version.CURRENT))
.add(new DiscoveryNode(
"filled_ml_node_name",
"filled_ml_node_id",
new TransportAddress(InetAddress.getLoopbackAddress(), 9301),
MapBuilder.<String, String>newMapBuilder()
.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "1")
.put(MachineLearning.MAX_JVM_SIZE_NODE_ATTR, "10")
.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(ByteSizeValue.ofGb(30).getBytes()))
.map(),
Collections.emptySet(),
Version.CURRENT))
.add(new DiscoveryNode("not_filled_ml_node",
"not_filled_ml_node_id",
new TransportAddress(InetAddress.getLoopbackAddress(), 9302),
MapBuilder.<String, String>newMapBuilder()
.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10")
.put(MachineLearning.MAX_JVM_SIZE_NODE_ATTR, "10")
.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(ByteSizeValue.ofGb(30).getBytes()))
.map(),
Collections.emptySet(),
Version.CURRENT))
.add(new DiscoveryNode("not_filled_smaller_ml_node",
"not_filled_smaller_ml_node_id",
new TransportAddress(InetAddress.getLoopbackAddress(), 9303),
MapBuilder.<String, String>newMapBuilder()
.put(MachineLearning.MAX_OPEN_JOBS_NODE_ATTR, "10")
.put(MachineLearning.MAX_JVM_SIZE_NODE_ATTR, "10")
.put(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(ByteSizeValue.ofGb(10).getBytes()))
.map(),
Collections.emptySet(),
Version.CURRENT))
.build();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
OpenJobPersistentTasksExecutorTests.addJobTask("one_job", "filled_ml_node_id", null, tasksBuilder);
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
Metadata.Builder metadata = Metadata.builder();
cs.nodes(nodes);
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
cs.metadata(metadata);
Job job = BaseMlIntegTestCase.createFareQuoteJob("job_id2", JOB_MEMORY_REQUIREMENT).build(new Date());
JobNodeSelector jobNodeSelector = new JobNodeSelector(cs.build(), job.getId(), MlTasks.JOB_TASK_NAME, memoryTracker, 0,
node -> nodeFilter(node, job));
Tuple<NativeMemoryCapacity, Long> capacityAndFreeMemory = jobNodeSelector.perceivedCapacityAndMaxFreeMemory(
10,
false,
1,
true);
assertThat(capacityAndFreeMemory.v2(), equalTo(ByteSizeValue.ofGb(3).getBytes()));
assertThat(capacityAndFreeMemory.v1(),
equalTo(new NativeMemoryCapacity(ByteSizeValue.ofGb(7).getBytes(), ByteSizeValue.ofGb(3).getBytes(), 10L)));
}
private ClusterState.Builder fillNodesWithRunningJobs(Map<String, String> nodeAttr, int numNodes, int numRunningJobsPerNode) {
return fillNodesWithRunningJobs(nodeAttr, numNodes, numRunningJobsPerNode, JobState.OPENED, DataFrameAnalyticsState.STARTED);
}
private ClusterState.Builder fillNodesWithRunningJobs(Map<String, String> nodeAttr, int numNodes, int numRunningJobsPerNode,
JobState anomalyDetectionJobState, DataFrameAnalyticsState dfAnalyticsJobState) {
DiscoveryNodes.Builder nodes = DiscoveryNodes.builder();
PersistentTasksCustomMetadata.Builder tasksBuilder = PersistentTasksCustomMetadata.builder();
String[] jobIds = new String[numNodes * numRunningJobsPerNode];
for (int i = 0; i < numNodes; i++) {
String nodeId = "_node_id" + i;
TransportAddress address = new TransportAddress(InetAddress.getLoopbackAddress(), 9300 + i);
nodes.add(new DiscoveryNode("_node_name" + i, nodeId, address, nodeAttr, Collections.emptySet(), Version.CURRENT));
for (int j = 0; j < numRunningJobsPerNode; j++) {
int id = j + (numRunningJobsPerNode * i);
// Both anomaly detector jobs and data frame analytics jobs should count towards the limit
if (randomBoolean()) {
jobIds[id] = "job_id" + id;
OpenJobPersistentTasksExecutorTests.addJobTask(jobIds[id], nodeId, anomalyDetectionJobState, tasksBuilder);
} else {
jobIds[id] = "data_frame_analytics_id" + id;
addDataFrameAnalyticsJobTask(jobIds[id], nodeId, dfAnalyticsJobState, tasksBuilder);
}
}
}
PersistentTasksCustomMetadata tasks = tasksBuilder.build();
ClusterState.Builder cs = ClusterState.builder(new ClusterName("_name"));
Metadata.Builder metadata = Metadata.builder();
cs.nodes(nodes);
metadata.putCustom(PersistentTasksCustomMetadata.TYPE, tasks);
cs.metadata(metadata);
return cs;
}
static void addDataFrameAnalyticsJobTask(String id, String nodeId, DataFrameAnalyticsState state,
PersistentTasksCustomMetadata.Builder builder) {
addDataFrameAnalyticsJobTask(id, nodeId, state, builder, false, false);
}
static void addDataFrameAnalyticsJobTask(String id, String nodeId, DataFrameAnalyticsState state,
PersistentTasksCustomMetadata.Builder builder, boolean isStale, boolean allowLazyStart) {
builder.addTask(MlTasks.dataFrameAnalyticsTaskId(id), MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME,
new StartDataFrameAnalyticsAction.TaskParams(id, Version.CURRENT, Collections.emptyList(), allowLazyStart),
new PersistentTasksCustomMetadata.Assignment(nodeId, "test assignment"));
if (state != null) {
builder.updateTaskState(MlTasks.dataFrameAnalyticsTaskId(id),
new DataFrameAnalyticsTaskState(state, builder.getLastAllocationId() - (isStale ? 1 : 0), null));
}
}
private static TaskParams createTaskParams(String id) {
return new TaskParams(id, Version.CURRENT, Collections.emptyList(), false);
}
}
| {
"content_hash": "5027e1c228b924e895948f2dde7b39c2",
"timestamp": "",
"source": "github",
"line_count": 829,
"max_line_length": 139,
"avg_line_length": 57.658624849215926,
"alnum_prop": 0.6954120379087428,
"repo_name": "nknize/elasticsearch",
"id": "f5d82171289ce8738d4fd049b507f074754127d4",
"size": "48040",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/JobNodeSelectorTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "12298"
},
{
"name": "Batchfile",
"bytes": "16353"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "251795"
},
{
"name": "HTML",
"bytes": "5348"
},
{
"name": "Java",
"bytes": "36849935"
},
{
"name": "Perl",
"bytes": "7116"
},
{
"name": "Python",
"bytes": "76127"
},
{
"name": "Shell",
"bytes": "102829"
}
],
"symlink_target": ""
} |
NOTE: Code rewrite is currently in progress, things probably don't work as described!
OWL: OpenStreetMap Watch List
=============================
OWL is a service that allows monitoring and analyzing changes in OpenStreetMap data.
Wiki: http://wiki.openstreetmap.org/wiki/OWL
Installation: http://wiki.openstreetmap.org/wiki/OWL/Installation
API: http://wiki.openstreetmap.org/wiki/OWL/API
Contents:
---------
osmosis-plugin/
Git submodule containing a plugin for Osmosis that takes care of
populating the database.
See the `INSTALL.md` file for installation and usage instructions.
rails/
A Rails project which hosts the API which allows applications
to interface with OWL.
scripts/
Miscellaneous scripts to keep bits of the database up-to-date,
like the OWL changeset details scraper.
sql/
SQL scripts for setting up a database with OWL schema.
tiler/
A tool for creating geometry tiles that are served by the API.
| {
"content_hash": "7bc778d62c927b54ae490039a7678cce",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 85,
"avg_line_length": 29.12121212121212,
"alnum_prop": 0.7388137356919875,
"repo_name": "ppawel/openstreetmap-watch-list",
"id": "b870dfe701315bca3711a8e8df12165f51d9edd8",
"size": "961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1193"
},
{
"name": "CoffeeScript",
"bytes": "104"
},
{
"name": "JavaScript",
"bytes": "641"
},
{
"name": "Ruby",
"bytes": "82574"
},
{
"name": "Shell",
"bytes": "2320"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>pyparsing.pyparsing</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th bgcolor="#70b0f0" class="navbar-select"
> Home </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>pyparsing</th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
Package pyparsing ::
Module pyparsing
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="pyparsing.pyparsing-module.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== MODULE DESCRIPTION ==================== -->
<h1 class="epydoc">Module pyparsing</h1><p class="nomargin-top"><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html">source code</a></span></p>
<p>pyparsing module - Classes and methods to define and execute parsing
grammars</p>
<p>The pyparsing module is an alternative approach to creating and
executing simple grammars, vs. the traditional lex/yacc approach, or the
use of regular expressions. With pyparsing, you don't need to learn a
new syntax for defining grammars or matching expressions - the parsing
module provides a library of classes that you use to construct the
grammar directly in Python.</p>
<p>Here is a program to parse "Hello, World!" (or any greeting
of the form "<salutation>, <addressee>!"):</p>
<pre class="literalblock">
from pyparsing import Word, alphas
# define grammar of a greeting
greet = Word( alphas ) + "," + Word( alphas ) + "!"
hello = "Hello, World!"
print hello, "->", greet.parseString( hello )
</pre>
<p>The program outputs the following:</p>
<pre class="literalblock">
Hello, World! -> ['Hello', ',', 'World', '!']
</pre>
<p>The Python representation of the grammar is quite readable, owing to
the self-explanatory class names, and the use of '+', '|' and '^'
operators.</p>
<p>The parsed results returned from parseString() can be accessed as a
nested list, a dictionary, or an object with named attributes.</p>
<p>The pyparsing module handles some of the problems that are typically
vexing when writing text parsers:</p>
<ul>
<li>
extra or missing whitespace (the above program will also handle
"Hello,World!", "Hello , World !", etc.)
</li>
<li>
quoted strings
</li>
<li>
embedded comments
</li>
</ul>
<hr />
<div class="fields"> <p><strong>Version:</strong>
1.5.0
</p>
<p><strong>Author:</strong>
Paul McGuire <ptmcg@users.sourceforge.net>
</p>
</div><!-- ==================== CLASSES ==================== -->
<a name="section-Classes"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td align="left" colspan="2" class="table-header">
<span class="table-header">Classes</span></td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParseBaseException-class.html" class="summary-name">ParseBaseException</a><br />
base exception class for all parsing runtime exceptions
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParseException-class.html" class="summary-name">ParseException</a><br />
exception thrown when parse expressions don't match class;
supported attributes by name are:
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParseFatalException-class.html" class="summary-name">ParseFatalException</a><br />
user-throwable exception thrown when inconsistent parse content is
found; stops all parsing immediately
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParseSyntaxException-class.html" class="summary-name">ParseSyntaxException</a><br />
just like ParseFatalException, but thrown internally when an
ErrorStop indicates that parsing is to stop immediately because an
unbacktrackable syntax error has been found
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.RecursiveGrammarException-class.html" class="summary-name">RecursiveGrammarException</a><br />
exception thrown by validate() if the grammar could be improperly
recursive
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParseResults-class.html" class="summary-name">ParseResults</a><br />
Structured parse results, to provide multiple means of access to
the parsed data:
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParserElement-class.html" class="summary-name">ParserElement</a><br />
Abstract base level parser element class.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Token-class.html" class="summary-name">Token</a><br />
Abstract ParserElement subclass, for defining atomic matching
patterns.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Empty-class.html" class="summary-name">Empty</a><br />
An empty token, will always match.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.NoMatch-class.html" class="summary-name">NoMatch</a><br />
A token that will never match.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Literal-class.html" class="summary-name">Literal</a><br />
Token to exactly match a specified string.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Keyword-class.html" class="summary-name">Keyword</a><br />
Token to exactly match a specified string as a keyword, that is, it
must be immediately followed by a non-keyword character.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.CaselessLiteral-class.html" class="summary-name">CaselessLiteral</a><br />
Token to match a specified string, ignoring case of letters.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.CaselessKeyword-class.html" class="summary-name">CaselessKeyword</a>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Word-class.html" class="summary-name">Word</a><br />
Token for matching words composed of allowed character sets.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Regex-class.html" class="summary-name">Regex</a><br />
Token for matching strings that match a given regular expression.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.QuotedString-class.html" class="summary-name">QuotedString</a><br />
Token for matching strings that are delimited by quoting
characters.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.CharsNotIn-class.html" class="summary-name">CharsNotIn</a><br />
Token for matching words composed of characters *not* in a given
set.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.White-class.html" class="summary-name">White</a><br />
Special matching class for matching whitespace.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.GoToColumn-class.html" class="summary-name">GoToColumn</a><br />
Token to advance to a specific column of input text; useful for
tabular report scraping.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.LineStart-class.html" class="summary-name">LineStart</a><br />
Matches if current position is at the beginning of a line within
the parse string
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.LineEnd-class.html" class="summary-name">LineEnd</a><br />
Matches if current position is at the end of a line within the
parse string
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.StringStart-class.html" class="summary-name">StringStart</a><br />
Matches if current position is at the beginning of the parse string
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.StringEnd-class.html" class="summary-name">StringEnd</a><br />
Matches if current position is at the end of the parse string
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.WordStart-class.html" class="summary-name">WordStart</a><br />
Matches if the current position is at the beginning of a Word, and
is not preceded by any character in a given set of wordChars
(default=printables).
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.WordEnd-class.html" class="summary-name">WordEnd</a><br />
Matches if the current position is at the end of a Word, and is not
followed by any character in a given set of wordChars
(default=printables).
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParseExpression-class.html" class="summary-name">ParseExpression</a><br />
Abstract subclass of ParserElement, for combining and
post-processing parsed tokens.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.And-class.html" class="summary-name">And</a><br />
Requires all given ParseExpressions to be found in the given order.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Or-class.html" class="summary-name">Or</a><br />
Requires that at least one ParseExpression is found.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.MatchFirst-class.html" class="summary-name">MatchFirst</a><br />
Requires that at least one ParseExpression is found.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Each-class.html" class="summary-name">Each</a><br />
Requires all given ParseExpressions to be found, but in any order.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ParseElementEnhance-class.html" class="summary-name">ParseElementEnhance</a><br />
Abstract subclass of ParserElement, for combining and
post-processing parsed tokens.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.FollowedBy-class.html" class="summary-name">FollowedBy</a><br />
Lookahead matching of the given parse expression.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.NotAny-class.html" class="summary-name">NotAny</a><br />
Lookahead to disallow matching with the given parse expression.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.ZeroOrMore-class.html" class="summary-name">ZeroOrMore</a><br />
Optional repetition of zero or more of the given expression.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.OneOrMore-class.html" class="summary-name">OneOrMore</a><br />
Repetition of one or more of the given expression.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Optional-class.html" class="summary-name">Optional</a><br />
Optional matching of the given expression.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.SkipTo-class.html" class="summary-name">SkipTo</a><br />
Token for skipping over all undefined text until the matched
expression is found.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Forward-class.html" class="summary-name">Forward</a><br />
Forward declaration of an expression to be defined later - used for
recursive grammars, such as algebraic infix notation.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.TokenConverter-class.html" class="summary-name">TokenConverter</a><br />
Abstract subclass of ParseExpression, for converting parsed
results.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Upcase-class.html" class="summary-name">Upcase</a><br />
Converter to upper case all matching tokens.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Combine-class.html" class="summary-name">Combine</a><br />
Converter to concatenate all matching tokens to a single string.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Group-class.html" class="summary-name">Group</a><br />
Converter to return the matched tokens as a list - useful for
returning tokens of ZeroOrMore and OneOrMore expressions.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Dict-class.html" class="summary-name">Dict</a><br />
Converter to return a repetitive expression as a list, but also as
a dictionary.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.Suppress-class.html" class="summary-name">Suppress</a><br />
Converter for ignoring the results of a parsed expression.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing.OnlyOnce-class.html" class="summary-name">OnlyOnce</a><br />
Wrapper for parse actions, to ensure they are only called once.
</td>
</tr>
</table>
<!-- ==================== FUNCTIONS ==================== -->
<a name="section-Functions"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td align="left" colspan="2" class="table-header">
<span class="table-header">Functions</span></td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#col" class="summary-sig-name">col</a>(<span class="summary-sig-arg">loc</span>,
<span class="summary-sig-arg">strg</span>)</span><br />
Returns current column within a string, counting newlines as line
separators.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#col">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#lineno" class="summary-sig-name">lineno</a>(<span class="summary-sig-arg">loc</span>,
<span class="summary-sig-arg">strg</span>)</span><br />
Returns current line number within a string, counting newlines as
line separators.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#lineno">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="line"></a><span class="summary-sig-name">line</span>(<span class="summary-sig-arg">loc</span>,
<span class="summary-sig-arg">strg</span>)</span><br />
Returns the line of text containing loc within a string, counting
newlines as line separators.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#line">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="nullDebugAction"></a><span class="summary-sig-name">nullDebugAction</span>(<span class="summary-sig-arg">*args</span>)</span><br />
'Do-nothing' debug action, to suppress debugging output during
parsing.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#nullDebugAction">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="traceParseAction"></a><span class="summary-sig-name">traceParseAction</span>(<span class="summary-sig-arg">f</span>)</span><br />
Decorator for debugging parse actions.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#traceParseAction">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#delimitedList" class="summary-sig-name">delimitedList</a>(<span class="summary-sig-arg">expr</span>,
<span class="summary-sig-arg">delim</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">,</code><code class="variable-quote">'</code></span>,
<span class="summary-sig-arg">combine</span>=<span class="summary-sig-default">False</span>)</span><br />
Helper to define a delimited list of expressions - the delimiter
defaults to ','.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#delimitedList">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#countedArray" class="summary-sig-name">countedArray</a>(<span class="summary-sig-arg">expr</span>)</span><br />
Helper to define a counted list of expressions.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#countedArray">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#matchPreviousLiteral" class="summary-sig-name">matchPreviousLiteral</a>(<span class="summary-sig-arg">expr</span>)</span><br />
Helper to define an expression that is indirectly defined from the
tokens matched in a previous expression, that is, it looks for a
'repeat' of a previous expression.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#matchPreviousLiteral">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#matchPreviousExpr" class="summary-sig-name">matchPreviousExpr</a>(<span class="summary-sig-arg">expr</span>)</span><br />
Helper to define an expression that is indirectly defined from the
tokens matched in a previous expression, that is, it looks for a
'repeat' of a previous expression.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#matchPreviousExpr">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#oneOf" class="summary-sig-name">oneOf</a>(<span class="summary-sig-arg">strs</span>,
<span class="summary-sig-arg">caseless</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">useRegex</span>=<span class="summary-sig-default">True</span>)</span><br />
Helper to quickly define a set of alternative Literals, and makes
sure to do longest-first testing when there is a conflict, regardless
of the input order, but returns a MatchFirst for best performance.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#oneOf">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#dictOf" class="summary-sig-name">dictOf</a>(<span class="summary-sig-arg">key</span>,
<span class="summary-sig-arg">value</span>)</span><br />
Helper to easily and clearly define a dictionary by specifying the
respective patterns for the key and value.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#dictOf">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#srange" class="summary-sig-name">srange</a>(<span class="summary-sig-arg">s</span>)</span><br />
Helper to easily define string ranges for use in Word construction.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#srange">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="matchOnlyAtCol"></a><span class="summary-sig-name">matchOnlyAtCol</span>(<span class="summary-sig-arg">n</span>)</span><br />
Helper method for defining parse actions that require matching at a
specific column in the input text.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#matchOnlyAtCol">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#replaceWith" class="summary-sig-name">replaceWith</a>(<span class="summary-sig-arg">replStr</span>)</span><br />
Helper method for common parse actions that simply return a literal
value.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#replaceWith">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#removeQuotes" class="summary-sig-name">removeQuotes</a>(<span class="summary-sig-arg">s</span>,
<span class="summary-sig-arg">l</span>,
<span class="summary-sig-arg">t</span>)</span><br />
Helper parse action for removing quotation marks from parsed quoted
strings.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#removeQuotes">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="upcaseTokens"></a><span class="summary-sig-name">upcaseTokens</span>(<span class="summary-sig-arg">s</span>,
<span class="summary-sig-arg">l</span>,
<span class="summary-sig-arg">t</span>)</span><br />
Helper parse action to convert tokens to upper case.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#upcaseTokens">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="downcaseTokens"></a><span class="summary-sig-name">downcaseTokens</span>(<span class="summary-sig-arg">s</span>,
<span class="summary-sig-arg">l</span>,
<span class="summary-sig-arg">t</span>)</span><br />
Helper parse action to convert tokens to lower case.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#downcaseTokens">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="keepOriginalText"></a><span class="summary-sig-name">keepOriginalText</span>(<span class="summary-sig-arg">s</span>,
<span class="summary-sig-arg">startLoc</span>,
<span class="summary-sig-arg">t</span>)</span><br />
Helper parse action to preserve original parsed text, overriding any
nested parse actions.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#keepOriginalText">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="getTokensEndLoc"></a><span class="summary-sig-name">getTokensEndLoc</span>()</span><br />
Method to be called from within a parse action to determine the end
location of the parsed tokens.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#getTokensEndLoc">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="makeHTMLTags"></a><span class="summary-sig-name">makeHTMLTags</span>(<span class="summary-sig-arg">tagStr</span>)</span><br />
Helper to construct opening and closing tag expressions for HTML,
given a tag name</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#makeHTMLTags">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="makeXMLTags"></a><span class="summary-sig-name">makeXMLTags</span>(<span class="summary-sig-arg">tagStr</span>)</span><br />
Helper to construct opening and closing tag expressions for XML,
given a tag name</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#makeXMLTags">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#withAttribute" class="summary-sig-name">withAttribute</a>(<span class="summary-sig-arg">*args</span>,
<span class="summary-sig-arg">**attrDict</span>)</span><br />
Helper to create a validating parse action to be used with start tags
created with makeXMLTags or makeHTMLTags.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#withAttribute">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#operatorPrecedence" class="summary-sig-name">operatorPrecedence</a>(<span class="summary-sig-arg">baseExpr</span>,
<span class="summary-sig-arg">opList</span>)</span><br />
Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#operatorPrecedence">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#nestedExpr" class="summary-sig-name">nestedExpr</a>(<span class="summary-sig-arg">opener</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">(</code><code class="variable-quote">'</code></span>,
<span class="summary-sig-arg">closer</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">)</code><code class="variable-quote">'</code></span>,
<span class="summary-sig-arg">content</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">ignoreExpr</span>=<span class="summary-sig-default">quotedString using single or double quotes</span>)</span><br />
Helper method for defining nested lists enclosed in opening and
closing delimiters ("(" and ")" are the default).</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#nestedExpr">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pyparsing.pyparsing-module.html#indentedBlock" class="summary-sig-name">indentedBlock</a>(<span class="summary-sig-arg">blockStatementExpr</span>,
<span class="summary-sig-arg">indentStack</span>,
<span class="summary-sig-arg">indent</span>=<span class="summary-sig-default">True</span>)</span><br />
Helper method for defining space-delimited indentation blocks, such
as those used to define block statements in Python source code.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#indentedBlock">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="replaceHTMLEntity"></a><span class="summary-sig-name">replaceHTMLEntity</span>(<span class="summary-sig-arg">t</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#replaceHTMLEntity">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- ==================== VARIABLES ==================== -->
<a name="section-Variables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td align="left" colspan="2" class="table-header">
<span class="table-header">Variables</span></td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="alphas"></a><span class="summary-name">alphas</span> = <code title="'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'"><code class="variable-quote">'</code><code class="variable-string">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</code><code class="variable-quote">'</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="nums"></a><span class="summary-name">nums</span> = <code title="'0123456789'"><code class="variable-quote">'</code><code class="variable-string">0123456789</code><code class="variable-quote">'</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="hexnums"></a><span class="summary-name">hexnums</span> = <code title="'0123456789ABCDEFabcdef'"><code class="variable-quote">'</code><code class="variable-string">0123456789ABCDEFabcdef</code><code class="variable-quote">'</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing-module.html#alphanums" class="summary-name">alphanums</a> = <code title="'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'"><code class="variable-quote">'</code><code class="variable-string">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW</code><code class="variable-ellipsis">...</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing-module.html#printables" class="summary-name">printables</a> = <code title="'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\\
'()*+,-./:;<=>?@[\\]^_`{|}~'"><code class="variable-quote">'</code><code class="variable-string">0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL</code><code class="variable-ellipsis">...</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="empty"></a><span class="summary-name">empty</span> = <code title="empty">empty</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="lineStart"></a><span class="summary-name">lineStart</span> = <code title="lineStart">lineStart</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="lineEnd"></a><span class="summary-name">lineEnd</span> = <code title="lineEnd">lineEnd</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="stringStart"></a><span class="summary-name">stringStart</span> = <code title="stringStart">stringStart</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="stringEnd"></a><span class="summary-name">stringEnd</span> = <code title="stringEnd">stringEnd</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="opAssoc"></a><span class="summary-name">opAssoc</span> = <code title="_Constants()">_Constants()</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="dblQuotedString"></a><span class="summary-name">dblQuotedString</span> = <code title="string enclosed in double quotes">string enclosed in double quotes</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="sglQuotedString"></a><span class="summary-name">sglQuotedString</span> = <code title="string enclosed in single quotes">string enclosed in single quotes</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="quotedString"></a><span class="summary-name">quotedString</span> = <code title="quotedString using single or double quotes">quotedString using single or double quotes</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing-module.html#unicodeString" class="summary-name">unicodeString</a> = <code title="Combine:({"u" quotedString using single or double quotes})">Combine:({"u" quotedString using single or dou<code class="variable-ellipsis">...</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing-module.html#alphas8bit" class="summary-name">alphas8bit</a> = <code title="u'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'"><code class="variable-quote">u'</code><code class="variable-string">ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîï</code><code class="variable-ellipsis">...</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="punc8bit"></a><span class="summary-name">punc8bit</span> = <code title="u'¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿×÷'"><code class="variable-quote">u'</code><code class="variable-string">¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿×÷</code><code class="variable-quote">'</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="pyparsing.pyparsing-module.html#commonHTMLEntity" class="summary-name">commonHTMLEntity</a> = <code title="Combine:({{"&" Re:('gt|lt|amp|nbsp|quot')} ";"})">Combine:({{"&" Re:('gt|lt|amp|nbsp|quot')} <code class="variable-ellipsis">...</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="cStyleComment"></a><span class="summary-name">cStyleComment</span> = <code title="C style comment">C style comment</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="htmlComment"></a><span class="summary-name">htmlComment</span> = <code title="Re:('<!--[\\s\\S]*?-->')">Re:('<!--[\\s\\S]*?-->')</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="restOfLine"></a><span class="summary-name">restOfLine</span> = <code title="Re:('.*')">Re:('.*')</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="dblSlashComment"></a><span class="summary-name">dblSlashComment</span> = <code title="// comment">// comment</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="cppStyleComment"></a><span class="summary-name">cppStyleComment</span> = <code title="C++ style comment">C++ style comment</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="javaStyleComment"></a><span class="summary-name">javaStyleComment</span> = <code title="C++ style comment">C++ style comment</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="pythonStyleComment"></a><span class="summary-name">pythonStyleComment</span> = <code title="Python style comment">Python style comment</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="commaSeparatedList"></a><span class="summary-name">commaSeparatedList</span> = <code title="commaSeparatedList">commaSeparatedList</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="anyCloseTag"></a><span class="summary-name">anyCloseTag</span> = <code title="</W:(abcd...,abcd...)>"></W:(abcd...,abcd...)></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="anyOpenTag"></a><span class="summary-name">anyOpenTag</span> = <code title="<W:(abcd...,abcd...)>"><W:(abcd...,abcd...)></code>
</td>
</tr>
</table>
<!-- ==================== FUNCTION DETAILS ==================== -->
<a name="section-FunctionDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td align="left" colspan="2" class="table-header">
<span class="table-header">Function Details</span></td>
</tr>
</table>
<a name="col"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">col</span>(<span class="sig-arg">loc</span>,
<span class="sig-arg">strg</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#col">source code</a></span>
</td>
</tr></table>
<p>Returns current column within a string, counting newlines as line
separators. The first column is number 1.</p>
<p>Note: the default parsing behavior is to expand tabs in the input
string before starting the parsing process. See <a
href="pyparsing.pyparsing.ParserElement-class.html#parseString"
class="link"><i>ParserElement.parseString</i></a> for more information on
parsing strings containing <TAB>s, and suggested methods to
maintain a consistent view of the parsed string, the parse location, and
line and column positions within the parsed string.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="lineno"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">lineno</span>(<span class="sig-arg">loc</span>,
<span class="sig-arg">strg</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#lineno">source code</a></span>
</td>
</tr></table>
<p>Returns current line number within a string, counting newlines as line
separators. The first line is number 1.</p>
<p>Note: the default parsing behavior is to expand tabs in the input
string before starting the parsing process. See <a
href="pyparsing.pyparsing.ParserElement-class.html#parseString"
class="link"><i>ParserElement.parseString</i></a> for more information on
parsing strings containing <TAB>s, and suggested methods to
maintain a consistent view of the parsed string, the parse location, and
line and column positions within the parsed string.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="delimitedList"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">delimitedList</span>(<span class="sig-arg">expr</span>,
<span class="sig-arg">delim</span>=<span class="sig-default"><code class="variable-quote">'</code><code class="variable-string">,</code><code class="variable-quote">'</code></span>,
<span class="sig-arg">combine</span>=<span class="sig-default">False</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#delimitedList">source code</a></span>
</td>
</tr></table>
<p>Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can have
intervening whitespace, and comments, but this can be overridden by
passing 'combine=True' in the constructor. If combine is set to True, the
matching tokens are returned as a single token string, with the
delimiters included; otherwise, the matching tokens are returned as a
list of tokens, with the delimiters suppressed.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="countedArray"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">countedArray</span>(<span class="sig-arg">expr</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#countedArray">source code</a></span>
</td>
</tr></table>
<p>Helper to define a counted list of expressions. This helper defines a
pattern of the form:</p>
<pre class="literalblock">
integer expr expr expr...
</pre>
<p>where the leading integer tells how many expr expressions follow. The
matched tokens returns the array of expr tokens as a list - the leading
count token is suppressed.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="matchPreviousLiteral"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">matchPreviousLiteral</span>(<span class="sig-arg">expr</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#matchPreviousLiteral">source code</a></span>
</td>
</tr></table>
<p>Helper to define an expression that is indirectly defined from the
tokens matched in a previous expression, that is, it looks for a 'repeat'
of a previous expression. For example:</p>
<pre class="literalblock">
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
</pre>
<p>will match "1:1", but not "1:2". Because this
matches a previous literal, will also match the leading "1:1"
in "1:10". If this is not desired, use matchPreviousExpr. Do
*not* use with packrat parsing enabled.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="matchPreviousExpr"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">matchPreviousExpr</span>(<span class="sig-arg">expr</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#matchPreviousExpr">source code</a></span>
</td>
</tr></table>
<p>Helper to define an expression that is indirectly defined from the
tokens matched in a previous expression, that is, it looks for a 'repeat'
of a previous expression. For example:</p>
<pre class="literalblock">
first = Word(nums)
second = matchPreviousExpr(first)
matchExpr = first + ":" + second
</pre>
<p>will match "1:1", but not "1:2". Because this
matches by expressions, will *not* match the leading "1:1" in
"1:10"; the expressions are evaluated first, and then compared,
so "1" is compared with "10". Do *not* use with
packrat parsing enabled.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="oneOf"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">oneOf</span>(<span class="sig-arg">strs</span>,
<span class="sig-arg">caseless</span>=<span class="sig-default">False</span>,
<span class="sig-arg">useRegex</span>=<span class="sig-default">True</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#oneOf">source code</a></span>
</td>
</tr></table>
<p>Helper to quickly define a set of alternative Literals, and makes sure
to do longest-first testing when there is a conflict, regardless of the
input order, but returns a MatchFirst for best performance.</p>
<p>Parameters:</p>
<ul>
<li>
strs - a string of space-delimited literals, or a list of string
literals
</li>
<li>
caseless - (default=False) - treat all literals as caseless
</li>
<li>
useRegex - (default=True) - as an optimization, will generate a Regex
object; otherwise, will generate a MatchFirst object (if
caseless=True, or if creating a Regex raises an exception)
</li>
</ul>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="dictOf"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">dictOf</span>(<span class="sig-arg">key</span>,
<span class="sig-arg">value</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#dictOf">source code</a></span>
</td>
</tr></table>
<p>Helper to easily and clearly define a dictionary by specifying the
respective patterns for the key and value. Takes care of defining the
Dict, ZeroOrMore, and Group tokens in the proper order. The key pattern
can include delimiting markers or punctuation, as long as they are
suppressed, thereby leaving the significant key text. The value pattern
can include named results, so that the Dict results can include named
token fields.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="srange"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">srange</span>(<span class="sig-arg">s</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#srange">source code</a></span>
</td>
</tr></table>
<p>Helper to easily define string ranges for use in Word construction.
Borrows syntax from regexp '[]' string range definitions:</p>
<pre class="literalblock">
srange("[0-9]") -> "0123456789"
srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
</pre>
<p>The input string must be enclosed in []'s, and the returned string is
the expanded character set joined into a single string. The values
enclosed in the []'s may be:</p>
<pre class="literalblock">
a single character
an escaped character with a leading backslash (such as \- or \])
an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
an escaped octal character with a leading '\0' (\041, which is a '!' character)
a range of any of the above, separated by a dash ('a-z', etc.)
any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
</pre>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="replaceWith"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">replaceWith</span>(<span class="sig-arg">replStr</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#replaceWith">source code</a></span>
</td>
</tr></table>
<p>Helper method for common parse actions that simply return a literal
value. Especially useful when used with transformString().</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="removeQuotes"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">removeQuotes</span>(<span class="sig-arg">s</span>,
<span class="sig-arg">l</span>,
<span class="sig-arg">t</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#removeQuotes">source code</a></span>
</td>
</tr></table>
<p>Helper parse action for removing quotation marks from parsed quoted
strings. To use, add this parse action to quoted string using:</p>
<pre class="literalblock">
quotedString.setParseAction( removeQuotes )
</pre>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="withAttribute"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">withAttribute</span>(<span class="sig-arg">*args</span>,
<span class="sig-arg">**attrDict</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#withAttribute">source code</a></span>
</td>
</tr></table>
<p>Helper to create a validating parse action to be used with start tags
created with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a
starting tag with a required attribute value, to avoid false matches on
common tags such as <TD> or <DIV>.</p>
<p>Call withAttribute with a series of attribute names and values.
Specify the list of filter attributes names and values as:</p>
<ul>
<li>
keyword arguments, as in
(class="Customer",align="right"), or
</li>
<li>
a list of name-value tuples, as in ( ("ns1:class",
"Customer"), ("ns2:align","right") )
</li>
</ul>
<p>For attribute names with a namespace prefix, you must use the second
form. Attribute names are matched insensitive to upper/lower case.</p>
<p>To verify that the attribute exists, but without specifying a value,
pass withAttribute.ANY_VALUE as the value.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="operatorPrecedence"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">operatorPrecedence</span>(<span class="sig-arg">baseExpr</span>,
<span class="sig-arg">opList</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#operatorPrecedence">source code</a></span>
</td>
</tr></table>
<p>Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
binary, left- or right-associative. Parse actions can also be attached
to operator expressions.</p>
<p>Parameters:</p>
<ul>
<li>
baseExpr - expression representing the most basic element for the
nested
</li>
<li>
opList - list of tuples, one for each operator precedence level in
the expression grammar; each tuple is of the form (opExpr, numTerms,
rightLeftAssoc, parseAction), where:
<ul>
<li>
opExpr is the pyparsing expression for the operator; may also be
a string, which will be converted to a Literal; if numTerms is 3,
opExpr is a tuple of two expressions, for the two operators
separating the 3 terms
</li>
<li>
numTerms is the number of terms for this operator (must be 1, 2,
or 3)
</li>
<li>
rightLeftAssoc is the indicator whether the operator is right or
left associative, using the pyparsing-defined constants
opAssoc.RIGHT and opAssoc.LEFT.
</li>
<li>
parseAction is the parse action to be associated with expressions
matching this operator expression (the parse action tuple member
may be omitted)
</li>
</ul>
</li>
</ul>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="nestedExpr"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">nestedExpr</span>(<span class="sig-arg">opener</span>=<span class="sig-default"><code class="variable-quote">'</code><code class="variable-string">(</code><code class="variable-quote">'</code></span>,
<span class="sig-arg">closer</span>=<span class="sig-default"><code class="variable-quote">'</code><code class="variable-string">)</code><code class="variable-quote">'</code></span>,
<span class="sig-arg">content</span>=<span class="sig-default">None</span>,
<span class="sig-arg">ignoreExpr</span>=<span class="sig-default">quotedString using single or double quotes</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#nestedExpr">source code</a></span>
</td>
</tr></table>
<p>Helper method for defining nested lists enclosed in opening and
closing delimiters ("(" and ")" are the default).</p>
<p>Parameters:</p>
<ul>
<li>
opener - opening character for a nested list (default="(");
can also be a pyparsing expression
</li>
<li>
closer - closing character for a nested list (default=")");
can also be a pyparsing expression
</li>
<li>
content - expression for items within the nested lists (default=None)
</li>
<li>
ignoreExpr - expression for ignoring opening and closing delimiters
(default=quotedString)
</li>
</ul>
<p>If an expression is not provided for the content argument, the nested
expression will capture all whitespace-delimited content between
delimiters as a list of separate values.</p>
<p>Use the ignoreExpr argument to define expressions that may contain
opening or closing characters that should not be treated as opening or
closing characters for nesting, such as quotedString or a comment
expression. Specify multiple expressions using an Or or MatchFirst. The
default is quotedString, but if no expressions are to be ignored, then
pass None for this argument.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<a name="indentedBlock"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">indentedBlock</span>(<span class="sig-arg">blockStatementExpr</span>,
<span class="sig-arg">indentStack</span>,
<span class="sig-arg">indent</span>=<span class="sig-default">True</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pyparsing.pyparsing-pysrc.html#indentedBlock">source code</a></span>
</td>
</tr></table>
<p>Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.</p>
<p>Parameters:</p>
<ul>
<li>
blockStatementExpr - expression defining syntax of statement that is
repeated within the indented block
</li>
<li>
indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single
grammar should share a common indentStack)
</li>
<li>
indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=True)
</li>
</ul>
<p>A valid block must contain at least one blockStatement.</p>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== VARIABLES DETAILS ==================== -->
<a name="section-VariablesDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td align="left" colspan="2" class="table-header">
<span class="table-header">Variables Details</span></td>
</tr>
</table>
<a name="alphanums"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">alphanums</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
<code class="variable-quote">'</code><code class="variable-string">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</code><code class="variable-quote">'</code>
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<a name="printables"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">printables</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
<code class="variable-quote">'</code><code class="variable-string">0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\</code><span class="variable-linewrap"><img src="crarr.png" alt="\" /></span>
<code class="variable-string">'()*+,-./:;<=>?@[\\]^_`{|}~</code><code class="variable-quote">'</code>
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<a name="unicodeString"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">unicodeString</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
Combine:({"u" quotedString using single or double quotes})
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<a name="alphas8bit"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">alphas8bit</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
<code class="variable-quote">u'</code><code class="variable-string">ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ</code><code class="variable-quote">'</code>
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<a name="commonHTMLEntity"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">commonHTMLEntity</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
Combine:({{"&" Re:('gt|lt|amp|nbsp|quot')} ";"})
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th bgcolor="#70b0f0" class="navbar-select"
> Home </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>pyparsing</th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sat May 31 22:26:40 2008
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| {
"content_hash": "fb2b4927d8d8fae622d1223ea6d4a0fe",
"timestamp": "",
"source": "github",
"line_count": 1876,
"max_line_length": 895,
"avg_line_length": 42.74626865671642,
"alnum_prop": 0.620997106943336,
"repo_name": "chrisdew/pyparsing-autocomplete",
"id": "c3a95dd0c21e286f7dcedca91497a09bdaa3f247",
"size": "80192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "htmldoc/pyparsing.pyparsing-module.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "10874"
},
{
"name": "Python",
"bytes": "464692"
}
],
"symlink_target": ""
} |
<?php
namespace Czenker\Wichtlr\Recovery;
use Czenker\Wichtlr\Domain\Participant;
/**
* information given to $participant
*
* @package Czenker\Wichtlr\Recovery
*/
class RecoveryDataSet implements \IteratorAggregate {
/**
* @var Participant
*/
protected $participant;
/**
* @var array
*/
protected $recoveryData = array();
/**
* @param Participant $participant
*/
public function __construct(Participant $participant) {
$this->participant = $participant;
}
/**
* @return \Czenker\Wichtlr\Domain\Participant
*/
public function getParticipant() {
return $this->participant;
}
public function addRecoveryData(RecoveryData $recoveryData) {
$this->recoveryData[] = $recoveryData;
}
public function getRecoveryData() {
return $this->recoveryData;
}
public function getIterator() {
return new \ArrayObject($this->recoveryData);
}
} | {
"content_hash": "47f10336fb5cb3944c231e06da27966e",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 65,
"avg_line_length": 19.274509803921568,
"alnum_prop": 0.6286876907426246,
"repo_name": "czenker/wichtlr",
"id": "937950e56b5238cc5ef15486111af4bcd0c5b718",
"size": "2145",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Czenker/Wichtlr/Recovery/RecoveryDataSet.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "100064"
}
],
"symlink_target": ""
} |
<?php
namespace Spatie\SchemaOrg;
/**
* A short TV program or a segment/part of a TV program.
*
* @see http://schema.org/TVClip
*
* @mixin \Spatie\SchemaOrg\Clip
*/
class TVClip extends BaseType
{
/**
* The TV series to which this episode or season belongs.
*
* @param TVSeries|TVSeries[] $partOfTVSeries
*
* @return static
*
* @see http://schema.org/partOfTVSeries
*/
public function partOfTVSeries($partOfTVSeries)
{
return $this->setProperty('partOfTVSeries', $partOfTVSeries);
}
}
| {
"content_hash": "85473bb64c802380e40cac486db08d30",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 69,
"avg_line_length": 19.928571428571427,
"alnum_prop": 0.6308243727598566,
"repo_name": "castlegateit/cgit-static-site-template",
"id": "c819f6d840b456849cccf1b81062bd73dbcd1d40",
"size": "558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/spatie/schema-org/src/TVClip.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3033"
},
{
"name": "Hack",
"bytes": "582"
},
{
"name": "JavaScript",
"bytes": "87"
},
{
"name": "PHP",
"bytes": "17027"
}
],
"symlink_target": ""
} |
Please see [Microflow Timer](https://docs.mendix.com/appstore/widgets/microflow-timer) in the Mendix documentation for details.
## Raising problems/issues
- We encourage everyone to open a Support ticket on [Mendix Support](https://support.mendix.com) in case of problems with widgets or scaffolding tools (Pluggable Widgets Generator or Pluggable Widgets Tools)
| {
"content_hash": "c383beb8d52d3a7a55c2fc9075f6f0a5",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 209,
"avg_line_length": 91.5,
"alnum_prop": 0.8005464480874317,
"repo_name": "mendix/MicroflowTimer",
"id": "06dc8e3c9831854fddc3d3dd074dc4188783cb64",
"size": "366",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "144372"
},
{
"name": "HTML",
"bytes": "3870"
},
{
"name": "JavaScript",
"bytes": "13363"
},
{
"name": "Ruby",
"bytes": "176"
},
{
"name": "SCSS",
"bytes": "186332"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "40f5626e415123aaa74057bbf458d157",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "c2813b679391c5a304d1e1b044680bdc1a5df13e",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium maureri/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.sksamuel.avro4s.streams.input
class BasicInputStreamTest extends InputStreamTest {
case class BooleanTest(z: Boolean)
case class StringTest(z: String)
case class FloatTest(z: Float)
case class DoubleTest(z: Double)
case class IntTest(z: Int)
case class LongTest(z: Long)
test("read write out booleans") {
writeRead(BooleanTest(true))
}
test("read write out strings") {
writeRead(StringTest("Hello world"))
}
test("read write out longs") {
writeRead(LongTest(65653L))
}
test("read write out ints") {
writeRead(IntTest(44))
}
test("read write out doubles") {
writeRead(DoubleTest(3.235))
}
test("read write out floats") {
writeRead(FloatTest(3.4F))
}
} | {
"content_hash": "5cbc009baf19e4ef1d342a7f6907390a",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 52,
"avg_line_length": 20.857142857142858,
"alnum_prop": 0.684931506849315,
"repo_name": "51zero/avro4s",
"id": "fd2af259fad1717831b9395bd8aa117fb45a6e79",
"size": "730",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "avro4s-core/src/test/scala/com/sksamuel/avro4s/streams/input/BasicInputStreamTest.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "86"
},
{
"name": "Scala",
"bytes": "93821"
}
],
"symlink_target": ""
} |
import json
class InvalidNumberOfParamsException(Exception):
def __init__(self):
Exception.__init__(self, "Invalid number of input parameters")
class InvalidConnectionException(Exception):
def __init__(self, host="?"):
Exception.__init__(self, "CONNECTION ERROR: Couldn't connect to node " + host + ".")
class InvalidProviderException(Exception):
def __init__(self):
Exception.__init__(self, "Provider not set or invalid")
class InvalidResponseException(Exception):
def __init__(self, result):
if isinstance(result, dict) and result["error"] and result["error"]["message"]:
message = result["error"]["message"]
else:
message = "Invalid JSON RPC response: " + json.dumps(result)
Exception.__init__(self, message)
| {
"content_hash": "25faf5289f8d153ff76e86d071727dda",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 92,
"avg_line_length": 32.32,
"alnum_prop": 0.6448019801980198,
"repo_name": "shravan-shandilya/web3.py",
"id": "83e21fecf1c6e3497e6204cde762d2205e6bd6a1",
"size": "808",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web3/exceptions.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "926"
},
{
"name": "Python",
"bytes": "306962"
}
],
"symlink_target": ""
} |
<?php
/**
* Form password element
*
* @category Varien
* @package Varien_Data
* @author Magento Core Team <core@magentocommerce.com>
*/
class Varien_Data_Form_Element_Password extends Varien_Data_Form_Element_Abstract
{
public function __construct($attributes=array())
{
parent::__construct($attributes);
$this->setType('password');
$this->setExtType('textfield');
}
public function getHtml()
{
$this->addClass('input-text');
return parent::getHtml();
}
}
| {
"content_hash": "76c9bce6f655ee88397fec7921890da8",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 81,
"avg_line_length": 21.76,
"alnum_prop": 0.6102941176470589,
"repo_name": "JaroslawZielinski/magento-backendo",
"id": "d95a760137373f5e167da3f841c4086605d2f6ec",
"size": "1499",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "lib/Varien/Data/Form/Element/Password.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "20063"
},
{
"name": "ApacheConf",
"bytes": "8180"
},
{
"name": "Batchfile",
"bytes": "1036"
},
{
"name": "CSS",
"bytes": "1761201"
},
{
"name": "HTML",
"bytes": "5299746"
},
{
"name": "JavaScript",
"bytes": "1161636"
},
{
"name": "Makefile",
"bytes": "5568"
},
{
"name": "PHP",
"bytes": "50744865"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Python",
"bytes": "9156"
},
{
"name": "Ruby",
"bytes": "288"
},
{
"name": "Shell",
"bytes": "6243"
},
{
"name": "XSLT",
"bytes": "3070"
}
],
"symlink_target": ""
} |
module Simulation.Aivika.Experiment.Base.ExperimentWriter
(ExperimentWriter,
runExperimentWriter,
ExperimentFilePath(..),
experimentFilePath,
resolveFilePath,
expandFilePath,
mapFilePath) where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Control.Monad.State
import Control.Concurrent.MVar
import Control.Exception
import qualified Data.Map as M
import qualified Data.Set as S
import System.Directory
import System.FilePath
import Simulation.Aivika.Trans.Exception
import Simulation.Aivika.Experiment.Utils (replace)
-- | Specifies the file name, unique or writable, which can be appended with extension if required.
data ExperimentFilePath = WritableFilePath FilePath
-- ^ The file which is overwritten in
-- case if it existed before.
| UniqueFilePath FilePath
-- ^ The file which is always unique,
-- when an automatically generated suffix
-- is added to the name in case of need.
-- | The default experiment file path.
experimentFilePath :: ExperimentFilePath
experimentFilePath = UniqueFilePath "experiment"
-- | Resolve the file path relative to the specified directory passed in the first argument
-- and taking into account a possible requirement to have an unique file name.
resolveFilePath :: FilePath -> ExperimentFilePath -> ExperimentWriter FilePath
resolveFilePath dir (WritableFilePath path) =
return $ dir </> path
resolveFilePath dir (UniqueFilePath path) =
ExperimentWriter $ \r ->
let (name, ext) = splitExtension path
loop y i =
do let n = dir </> addExtension y ext
y' = name ++ "(" ++ show i ++ ")"
f1 <- doesFileExist n
f2 <- doesDirectoryExist n
if f1 || f2
then loop y' (i + 1)
else do n' <- liftIO $
modifyMVar r $ \s ->
if S.member n s
then return (s, Nothing)
else return (S.insert n s, Just n)
case n' of
Nothing -> loop y' (i + 1)
Just n' -> return n'
in loop name 2
-- | Expand the file path using the specified table of substitutions.
expandFilePath :: ExperimentFilePath -> M.Map String String -> ExperimentFilePath
expandFilePath (WritableFilePath path) map = WritableFilePath (expandTemplates path map)
expandFilePath (UniqueFilePath path) map = UniqueFilePath (expandTemplates path map)
-- | Expand the string templates using the specified table of substitutions.
expandTemplates :: String -> M.Map String String -> String
expandTemplates name map = name' where
((), name') = flip runState name $
forM_ (M.assocs map) $ \(k, v) ->
do a <- get
put $ replace k v a
-- | Transform the file path using the specified function.
mapFilePath :: (FilePath -> FilePath) -> ExperimentFilePath -> ExperimentFilePath
mapFilePath f (WritableFilePath path) = WritableFilePath (f path)
mapFilePath f (UniqueFilePath path) = UniqueFilePath (f path)
-- | Defines an 'IO' derived computation whithin which we can resolve the unique file paths.
newtype ExperimentWriter a = ExperimentWriter (MVar (S.Set String) -> IO a)
instance Functor ExperimentWriter where
{-# INLINE fmap #-}
fmap f (ExperimentWriter m) =
ExperimentWriter $ \r -> fmap f (m r)
instance Applicative ExperimentWriter where
{-# INLINE pure #-}
pure a =
ExperimentWriter $ \r -> return a
{-# INLINE (<*>) #-}
(ExperimentWriter f) <*> (ExperimentWriter m) =
ExperimentWriter $ \r -> f r <*> m r
instance Monad ExperimentWriter where
{-# INLINE return #-}
return a =
ExperimentWriter $ \r -> return a
{-# INLINE (>>=) #-}
(ExperimentWriter m) >>= k =
ExperimentWriter $ \r ->
do a <- m r
let ExperimentWriter b = k a
b r
instance MonadIO ExperimentWriter where
{-# INLINE liftIO #-}
liftIO m = ExperimentWriter $ \r -> liftIO m
instance MonadException ExperimentWriter where
{-# INLINE catchComp #-}
catchComp (ExperimentWriter m) h =
ExperimentWriter $ \r ->
catch (m r) $ \e ->
let ExperimentWriter m' = h e in m' r
{-# INLINE finallyComp #-}
finallyComp (ExperimentWriter m) (ExperimentWriter m') =
ExperimentWriter $ \r ->
finally (m r) (m' r)
{-# INLINE throwComp #-}
throwComp e =
ExperimentWriter $ \r ->
throw e
-- | Run the 'ExperimentWriter' computation.
runExperimentWriter :: ExperimentWriter a -> IO a
runExperimentWriter (ExperimentWriter m) =
do r <- newMVar S.empty
m r
| {
"content_hash": "61c3b3de09b4e86438a22f1b7ac16e6a",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 99,
"avg_line_length": 33.86619718309859,
"alnum_prop": 0.6371386982740694,
"repo_name": "dsorokin/aivika-experiment",
"id": "867637210c02877a5bc21e5b4cfd8275c3c970b0",
"size": "5207",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Simulation/Aivika/Experiment/Base/ExperimentWriter.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "144861"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Commas on Asterisk, and other worldly endeavours</title>
<link>http://blog.leifmadsen.com/tags/commas/index.xml</link>
<description>Recent content in Commas on Asterisk, and other worldly endeavours</description>
<generator>Hugo -- gohugo.io</generator>
<language>en-us</language>
<atom:link href="/tags/commas/index.xml" rel="self" type="application/rss+xml" />
<item>
<title>Grammar School!</title>
<link>http://blog.leifmadsen.com/blog/2010/02/10/grammar-school/</link>
<pubDate>Wed, 10 Feb 2010 20:35:27 +0000</pubDate>
<guid>http://blog.leifmadsen.com/blog/2010/02/10/grammar-school/</guid>
<description>I will admit that I&rsquo;m not the best at grammar (heck, I still have to make sure I type grammar instead of grammer, but that&rsquo;s just a spelling issue :)), and other times, there is just some stuff that happens when I get typing fast and I&rsquo;m on autopilot, thinking too far ahead of where I&rsquo;m actually at in terms of typing. It gets even worse when I&rsquo;m writing with good ol&rsquo; pen and paper!</description>
</item>
</channel>
</rss>
| {
"content_hash": "ba00afaac8eaaf2a203be8a2c9da24d7",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 477,
"avg_line_length": 62.476190476190474,
"alnum_prop": 0.6989329268292683,
"repo_name": "leifmadsen/blog",
"id": "fb1dccd9438cf4134d78b3a2a60f8977348f9e38",
"size": "1312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tags/commas/index.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "265010"
},
{
"name": "HTML",
"bytes": "4509657"
},
{
"name": "JavaScript",
"bytes": "5064"
},
{
"name": "Roff",
"bytes": "3343"
},
{
"name": "Shell",
"bytes": "629"
}
],
"symlink_target": ""
} |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var Hammer = require('hammerjs');
// var jsonfile = require('jsonfile');
var hammer_area = document.getElementById("hammer_time");
var hammer_time = new Hammer(hammer_area);
// var file = './data.json';
var data = JSON.parse(mydatas);
// var obj = {name: 'JP'}
// jsonfile.writeFile(file, obj, function (err) {
// console.error(err)
// })
document.getElementById("no").addEventListener("click", insertData);
document.getElementById("yes").addEventListener("click", insertData);
function insertData() {
var info;
if (data.length == 0) {
return;
}
else {
info = data.pop();
}
document.getElementById("image").src = info['image'];
var name = document.getElementById('name');
name.innerHTML = info['name'];
var gender = document.getElementById('gender');
gender.innerHTML = info['gender'];
var department = document.getElementById('department');
department.innerHTML = info['department'];
}
// detect swipe and call to a function
hammer_time.on('swiperight swipeleft', function(e) {
e.preventDefault();
insertData();
});
insertData();
},{"hammerjs":2}],2:[function(require,module,exports){
(function(window, document, exportName, undefined) {
'use strict';
var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round;
var abs = Math.abs;
var now = Date.now;
/**
* set a timeout with a given scope
* @param {Function} fn
* @param {Number} timeout
* @param {Object} context
* @returns {number}
*/
function setTimeoutContext(fn, timeout, context) {
return setTimeout(bindFn(fn, context), timeout);
}
/**
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
/**
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
/**
* wrap a method with a deprecation warning and stack trace
* @param {Function} method
* @param {String} name
* @param {String} message
* @returns {Function} A new function wrapping the supplied method.
*/
function deprecate(method, name, message) {
var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
return function() {
var e = new Error('get-stack-trace');
var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
.replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
var log = window.console && (window.console.warn || window.console.log);
if (log) {
log.call(window.console, deprecationMessage, stack);
}
return method.apply(this, arguments);
};
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} target
* @param {...Object} objects_to_assign
* @returns {Object} target
*/
var assign;
if (typeof Object.assign !== 'function') {
assign = function assign(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
} else {
assign = Object.assign;
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge=false]
* @returns {Object} dest
*/
var extend = deprecate(function extend(dest, src, merge) {
var keys = Object.keys(src);
var i = 0;
while (i < keys.length) {
if (!merge || (merge && dest[keys[i]] === undefined)) {
dest[keys[i]] = src[keys[i]];
}
i++;
}
return dest;
}, 'extend', 'Use `assign`.');
/**
* merge the values from src in the dest.
* means that properties that exist in dest will not be overwritten by src
* @param {Object} dest
* @param {Object} src
* @returns {Object} dest
*/
var merge = deprecate(function merge(dest, src) {
return extend(dest, src, true);
}, 'merge', 'Use `assign`.');
/**
* simple class inheritance
* @param {Function} child
* @param {Function} base
* @param {Object} [properties]
*/
function inherit(child, base, properties) {
var baseP = base.prototype,
childP;
childP = child.prototype = Object.create(baseP);
childP.constructor = child;
childP._super = baseP;
if (properties) {
assign(childP, properties);
}
}
/**
* simple function bind
* @param {Function} fn
* @param {Object} context
* @returns {Function}
*/
function bindFn(fn, context) {
return function boundFn() {
return fn.apply(context, arguments);
};
}
/**
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* use the val2 when val1 is undefined
* @param {*} val1
* @param {*} val2
* @returns {*}
*/
function ifUndefined(val1, val2) {
return (val1 === undefined) ? val2 : val1;
}
/**
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
}
/**
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
}
/**
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
return i;
}
i++;
}
return -1;
}
}
/**
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function sortUniqueArray(a, b) {
return a[key] > b[key];
});
}
}
return results;
}
/**
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix, prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = (prefix) ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/**
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument || element;
return (doc.defaultView || doc.parentWindow || window);
}
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';
var COMPUTE_INTERVAL = 25;
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];
/**
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget;
// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function(ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
Input.prototype = {
/**
* should handle the inputEvent data and trigger the callback
* @virtual
*/
handler: function() { },
/**
* bind the events
*/
init: function() {
this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
},
/**
* unbind the events
*/
destroy: function() {
this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
}
};
/**
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type;
var inputClass = manager.options.inputClass;
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new (Type)(manager, inputHandler);
}
/**
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = input.pointers.length;
var changedPointersLen = input.changedPointers.length;
var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
input.isFirst = !!isFirst;
input.isFinal = !!isFinal;
if (isFirst) {
manager.session = {};
}
// source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType = eventType;
// compute scale, rotation etc
computeInputData(manager, input);
// emit secret event
manager.emit('hammer.input', input);
manager.recognize(input);
manager.session.prevInput = input;
}
/**
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = manager.session;
var pointers = input.pointers;
var pointersLength = pointers.length;
// store the first input to calculate the distance and direction
if (!session.firstInput) {
session.firstInput = simpleCloneInputData(input);
}
// to compute scale and rotation we need to store the multiple touches
if (pointersLength > 1 && !session.firstMultiple) {
session.firstMultiple = simpleCloneInputData(input);
} else if (pointersLength === 1) {
session.firstMultiple = false;
}
var firstInput = session.firstInput;
var firstMultiple = session.firstMultiple;
var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
var center = input.center = getCenter(pointers);
input.timeStamp = now();
input.deltaTime = input.timeStamp - firstInput.timeStamp;
input.angle = getAngle(offsetCenter, center);
input.distance = getDistance(offsetCenter, center);
computeDeltaXY(session, input);
input.offsetDirection = getDirection(input.deltaX, input.deltaY);
var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
input.overallVelocityX = overallVelocity.x;
input.overallVelocityY = overallVelocity.y;
input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;
input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);
computeIntervalInputData(session, input);
// find the correct target
var target = manager.element;
if (hasParent(input.srcEvent.target, target)) {
target = input.srcEvent.target;
}
input.target = target;
}
function computeDeltaXY(session, input) {
var center = input.center;
var offset = session.offsetDelta || {};
var prevDelta = session.prevDelta || {};
var prevInput = session.prevInput || {};
if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
prevDelta = session.prevDelta = {
x: prevInput.deltaX || 0,
y: prevInput.deltaY || 0
};
offset = session.offsetDelta = {
x: center.x,
y: center.y
};
}
input.deltaX = prevDelta.x + (center.x - offset.x);
input.deltaY = prevDelta.y + (center.y - offset.y);
}
/**
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = session.lastInterval || input,
deltaTime = input.timeStamp - last.timeStamp,
velocity, velocityX, velocityY, direction;
if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
/**
* create a simple clone from the input used for storage of firstInput and firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
/**
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = pointers.length;
// no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0, y = 0, i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
if (abs(x) >= abs(y)) {
return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}
/**
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.sqrt((x * x) + (y * y));
}
/**
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / Math.PI;
}
/**
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}
/**
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
/**
* Mouse events input
* @constructor
* @extends Input
*/
function MouseInput() {
this.evEl = MOUSE_ELEMENT_EVENTS;
this.evWin = MOUSE_WINDOW_EVENTS;
this.pressed = false; // mousedown state
Input.apply(this, arguments);
}
inherit(MouseInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function MEhandler(ev) {
var eventType = MOUSE_INPUT_MAP[ev.type];
// on start we want to have the left mouse button down
if (eventType & INPUT_START && ev.button === 0) {
this.pressed = true;
}
if (eventType & INPUT_MOVE && ev.which !== 1) {
eventType = INPUT_END;
}
// mouse must be down
if (!this.pressed) {
return;
}
if (eventType & INPUT_END) {
this.pressed = false;
}
this.callback(this.manager, eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
}
});
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
};
// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
2: INPUT_TYPE_TOUCH,
3: INPUT_TYPE_PEN,
4: INPUT_TYPE_MOUSE,
5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};
var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
// IE10 has prefixed support, and case-sensitive
if (window.MSPointerEvent && !window.PointerEvent) {
POINTER_ELEMENT_EVENTS = 'MSPointerDown';
POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}
/**
* Pointer events input
* @constructor
* @extends Input
*/
function PointerEventInput() {
this.evEl = POINTER_ELEMENT_EVENTS;
this.evWin = POINTER_WINDOW_EVENTS;
Input.apply(this, arguments);
this.store = (this.manager.session.pointerEvents = []);
}
inherit(PointerEventInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function PEhandler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = (pointerType == INPUT_TYPE_TOUCH);
// get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId');
// start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
}
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
// update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
}
});
var SINGLE_TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* Touch events input
* @constructor
* @extends Input
*/
function SingleTouchInput() {
this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
this.started = false;
Input.apply(this, arguments);
}
inherit(SingleTouchInput, Input, {
handler: function TEhandler(ev) {
var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
// should we handle the touch events?
if (type === INPUT_START) {
this.started = true;
}
if (!this.started) {
return;
}
var touches = normalizeSingleTouches.call(this, ev, type);
// when done, reset the started state
if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
this.started = false;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function normalizeSingleTouches(ev, type) {
var all = toArray(ev.touches);
var changed = toArray(ev.changedTouches);
if (type & (INPUT_END | INPUT_CANCEL)) {
all = uniqueArray(all.concat(changed), 'identifier', true);
}
return [all, changed];
}
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* Multi-user touch events input
* @constructor
* @extends Input
*/
function TouchInput() {
this.evTarget = TOUCH_TARGET_EVENTS;
this.targetIds = {};
Input.apply(this, arguments);
}
inherit(TouchInput, Input, {
handler: function MTEhandler(ev) {
var type = TOUCH_INPUT_MAP[ev.type];
var touches = getTouches.call(this, ev, type);
if (!touches) {
return;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function getTouches(ev, type) {
var allTouches = toArray(ev.touches);
var targetIds = this.targetIds;
// when there is only one touch, the process can be simplified
if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
targetIds[allTouches[0].identifier] = true;
return [allTouches, allTouches];
}
var i,
targetTouches,
changedTouches = toArray(ev.changedTouches),
changedTargetTouches = [],
target = this.target;
// get target touches from touches
targetTouches = allTouches.filter(function(touch) {
return hasParent(touch.target, target);
});
// collect touches
if (type === INPUT_START) {
i = 0;
while (i < targetTouches.length) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
}
// filter changed touches to only contain touches that exist in the collected target ids
i = 0;
while (i < changedTouches.length) {
if (targetIds[changedTouches[i].identifier]) {
changedTargetTouches.push(changedTouches[i]);
}
// cleanup removed touches
if (type & (INPUT_END | INPUT_CANCEL)) {
delete targetIds[changedTouches[i].identifier];
}
i++;
}
if (!changedTargetTouches.length) {
return;
}
return [
// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
changedTargetTouches
];
}
/**
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;
function TouchMouseInput() {
Input.apply(this, arguments);
var handler = bindFn(this.handler, this);
this.touch = new TouchInput(this.manager, handler);
this.mouse = new MouseInput(this.manager, handler);
this.primaryTouch = null;
this.lastTouches = [];
}
inherit(TouchMouseInput, Input, {
/**
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
handler: function TMEhandler(manager, inputEvent, inputData) {
var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
return;
}
// when we're in a touch event, record touches to de-dupe synthetic mouse event
if (isTouch) {
recordTouches.call(this, inputEvent, inputData);
} else if (isMouse && isSyntheticEvent.call(this, inputData)) {
return;
}
this.callback(manager, inputEvent, inputData);
},
/**
* remove the event listeners
*/
destroy: function destroy() {
this.touch.destroy();
this.mouse.destroy();
}
});
function recordTouches(eventType, eventData) {
if (eventType & INPUT_START) {
this.primaryTouch = eventData.changedPointers[0].identifier;
setLastTouch.call(this, eventData);
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
setLastTouch.call(this, eventData);
}
}
function setLastTouch(eventData) {
var touch = eventData.changedPointers[0];
if (touch.identifier === this.primaryTouch) {
var lastTouch = {x: touch.clientX, y: touch.clientY};
this.lastTouches.push(lastTouch);
var lts = this.lastTouches;
var removeLastTouch = function() {
var i = lts.indexOf(lastTouch);
if (i > -1) {
lts.splice(i, 1);
}
};
setTimeout(removeLastTouch, DEDUP_TIMEOUT);
}
}
function isSyntheticEvent(eventData) {
var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
for (var i = 0; i < this.lastTouches.length; i++) {
var t = this.lastTouches[i];
var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
return true;
}
}
return false;
}
var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
// magical touchAction value
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();
/**
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
function TouchAction(manager, value) {
this.manager = manager;
this.set(value);
}
TouchAction.prototype = {
/**
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
set: function(value) {
// find out the touch-action by the event handlers
if (value == TOUCH_ACTION_COMPUTE) {
value = this.compute();
}
if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
}
this.actions = value.toLowerCase().trim();
},
/**
* just re-set the touchAction value
*/
update: function() {
this.set(this.manager.options.touchAction);
},
/**
* compute the value for the touchAction property based on the recognizer's settings
* @returns {String} value
*/
compute: function() {
var actions = [];
each(this.manager.recognizers, function(recognizer) {
if (boolOrFn(recognizer.options.enable, [recognizer])) {
actions = actions.concat(recognizer.getTouchAction());
}
});
return cleanTouchActions(actions.join(' '));
},
/**
* this method is called on each input cycle and provides the preventing of the browser behavior
* @param {Object} input
*/
preventDefaults: function(input) {
var srcEvent = input.srcEvent;
var direction = input.offsetDirection;
// if the touch action did prevented once this session
if (this.manager.session.prevented) {
srcEvent.preventDefault();
return;
}
var actions = this.actions;
var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
if (hasNone) {
//do not prevent defaults if this is a tap gesture
var isTapPointer = input.pointers.length === 1;
var isTapMovement = input.distance < 2;
var isTapTouchTime = input.deltaTime < 250;
if (isTapPointer && isTapMovement && isTapTouchTime) {
return;
}
}
if (hasPanX && hasPanY) {
// `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
return;
}
if (hasNone ||
(hasPanY && direction & DIRECTION_HORIZONTAL) ||
(hasPanX && direction & DIRECTION_VERTICAL)) {
return this.preventSrc(srcEvent);
}
},
/**
* call preventDefault to prevent the browser's default behavior (scrolling in most cases)
* @param {Object} srcEvent
*/
preventSrc: function(srcEvent) {
this.manager.session.prevented = true;
srcEvent.preventDefault();
}
};
/**
* when the touchActions are collected they are not a valid value, so we need to clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
// if both pan-x and pan-y are set (different recognizers
// for different directions, e.g. horizontal pan but vertical swipe?)
// we need none (as otherwise with pan-x pan-y combined none of these
// recognizers will work, since the browser would handle all panning
if (hasPanX && hasPanY) {
return TOUCH_ACTION_NONE;
}
// pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
}
// manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
function getTouchActionProps() {
if (!NATIVE_TOUCH_ACTION) {
return false;
}
var touchMap = {};
var cssSupports = window.CSS && window.CSS.supports;
['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) {
// If css.supports is not supported but there is native touch-action assume it supports
// all values. This is the case for IE 10 and 11.
touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
});
return touchMap;
}
/**
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input, with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
function Recognizer(options) {
this.options = assign({}, this.defaults, options || {});
this.id = uniqueId();
this.manager = null;
// default is enable true
this.options.enable = ifUndefined(this.options.enable, true);
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
}
Recognizer.prototype = {
/**
* @virtual
* @type {Object}
*/
defaults: {},
/**
* set options
* @param {Object} options
* @return {Recognizer}
*/
set: function(options) {
assign(this.options, options);
// also update the touchAction, in case something changed about the directions/enabled state
this.manager && this.manager.touchAction.update();
return this;
},
/**
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
recognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
},
/**
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRecognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
delete this.simultaneous[otherRecognizer.id];
return this;
},
/**
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
requireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
var requireFail = this.requireFail;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (inArray(requireFail, otherRecognizer) === -1) {
requireFail.push(otherRecognizer);
otherRecognizer.requireFailure(this);
}
return this;
},
/**
* drop the requireFailure link. it does not remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRequireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
var index = inArray(this.requireFail, otherRecognizer);
if (index > -1) {
this.requireFail.splice(index, 1);
}
return this;
},
/**
* has require failures boolean
* @returns {boolean}
*/
hasRequireFailures: function() {
return this.requireFail.length > 0;
},
/**
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
canRecognizeWith: function(otherRecognizer) {
return !!this.simultaneous[otherRecognizer.id];
},
/**
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
emit: function(input) {
var self = this;
var state = this.state;
function emit(event) {
self.manager.emit(event, input);
}
// 'panstart' and 'panmove'
if (state < STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
emit(self.options.event); // simple 'eventName' events
if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
emit(input.additionalEvent);
}
// panend and pancancel
if (state >= STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
},
/**
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
tryEmit: function(input) {
if (this.canEmit()) {
return this.emit(input);
}
// it's failing anyway
this.state = STATE_FAILED;
},
/**
* can we emit?
* @returns {boolean}
*/
canEmit: function() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
},
/**
* update the recognizer
* @param {Object} inputData
*/
recognize: function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign({}, inputData);
// is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
}
// reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone);
// the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
},
/**
* return the state of the recognizer
* the actual recognizing happens in this method
* @virtual
* @param {Object} inputData
* @returns {Const} STATE
*/
process: function(inputData) { }, // jshint ignore:line
/**
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
getTouchAction: function() { },
/**
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
reset: function() { }
};
/**
* get a usable string, used as event postfix
* @param {Const} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* direction cons to string
* @param {Const} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
}
/**
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
function AttrRecognizer() {
Recognizer.apply(this, arguments);
}
inherit(AttrRecognizer, Recognizer, {
/**
* @namespace
* @memberof AttrRecognizer
*/
defaults: {
/**
* @type {Number}
* @default 1
*/
pointers: 1
},
/**
* Used to check if it the recognizer receives valid input, like input.distance > 10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
attrTest: function(input) {
var optionPointers = this.options.pointers;
return optionPointers === 0 || input.pointers.length === optionPointers;
},
/**
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
process: function(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input);
// on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
}
});
/**
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function PanRecognizer() {
AttrRecognizer.apply(this, arguments);
this.pX = null;
this.pY = null;
}
inherit(PanRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PanRecognizer
*/
defaults: {
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
},
getTouchAction: function() {
var direction = this.options.direction;
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
},
directionTest: function(input) {
var options = this.options;
var hasMoved = true;
var distance = input.distance;
var direction = input.direction;
var x = input.deltaX;
var y = input.deltaY;
// lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x != this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y != this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction & options.direction;
},
attrTest: function(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) &&
(this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
},
emit: function(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
var direction = directionStr(input.direction);
if (direction) {
input.additionalEvent = this.options.event + direction;
}
this._super.emit.call(this, input);
}
});
/**
* Pinch
* Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
* @constructor
* @extends AttrRecognizer
*/
function PinchRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(PinchRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'pinch',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
},
emit: function(input) {
if (input.scale !== 1) {
var inOut = input.scale < 1 ? 'in' : 'out';
input.additionalEvent = this.options.event + inOut;
}
this._super.emit.call(this, input);
}
});
/**
* Press
* Recognized when the pointer is down for x ms without any movement.
* @constructor
* @extends Recognizer
*/
function PressRecognizer() {
Recognizer.apply(this, arguments);
this._timer = null;
this._input = null;
}
inherit(PressRecognizer, Recognizer, {
/**
* @namespace
* @memberof PressRecognizer
*/
defaults: {
event: 'press',
pointers: 1,
time: 251, // minimal time of the pointer to be pressed
threshold: 9 // a minimal movement is ok, but keep it low
},
getTouchAction: function() {
return [TOUCH_ACTION_AUTO];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTime = input.deltaTime > options.time;
this._input = input;
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
this.reset();
} else if (input.eventType & INPUT_START) {
this.reset();
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.time, this);
} else if (input.eventType & INPUT_END) {
return STATE_RECOGNIZED;
}
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function(input) {
if (this.state !== STATE_RECOGNIZED) {
return;
}
if (input && (input.eventType & INPUT_END)) {
this.manager.emit(this.options.event + 'up', input);
} else {
this._input.timeStamp = now();
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Rotate
* Recognized when two or more pointer are moving in a circular motion.
* @constructor
* @extends AttrRecognizer
*/
function RotateRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(RotateRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof RotateRecognizer
*/
defaults: {
event: 'rotate',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
}
});
/**
* Swipe
* Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function SwipeRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(SwipeRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof SwipeRecognizer
*/
defaults: {
event: 'swipe',
threshold: 10,
velocity: 0.3,
direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
pointers: 1
},
getTouchAction: function() {
return PanRecognizer.prototype.getTouchAction.call(this);
},
attrTest: function(input) {
var direction = this.options.direction;
var velocity;
if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
velocity = input.overallVelocity;
} else if (direction & DIRECTION_HORIZONTAL) {
velocity = input.overallVelocityX;
} else if (direction & DIRECTION_VERTICAL) {
velocity = input.overallVelocityY;
}
return this._super.attrTest.call(this, input) &&
direction & input.offsetDirection &&
input.distance > this.options.threshold &&
input.maxPointers == this.options.pointers &&
abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
},
emit: function(input) {
var direction = directionStr(input.offsetDirection);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this.manager.emit(this.options.event, input);
}
});
/**
* A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
* between the given interval and position. The delay option can be used to recognize multi-taps without firing
* a single tap.
*
* The eventData from the emitted event contains the property `tapCount`, which contains the amount of
* multi-taps being recognized.
* @constructor
* @extends Recognizer
*/
function TapRecognizer() {
Recognizer.apply(this, arguments);
// previous time and center,
// used for tap counting
this.pTime = false;
this.pCenter = false;
this._timer = null;
this._input = null;
this.count = 0;
}
inherit(TapRecognizer, Recognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'tap',
pointers: 1,
taps: 1,
interval: 300, // max time between the multi-tap taps
time: 250, // max time of the pointer to be down (like finger on the screen)
threshold: 9, // a minimal movement is ok, but keep it low
posThreshold: 10 // a multi-tap can be a bit off the initial position
},
getTouchAction: function() {
return [TOUCH_ACTION_MANIPULATION];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTouchTime = input.deltaTime < options.time;
this.reset();
if ((input.eventType & INPUT_START) && (this.count === 0)) {
return this.failTimeout();
}
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (validMovement && validTouchTime && validPointers) {
if (input.eventType != INPUT_END) {
return this.failTimeout();
}
var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
this.pTime = input.timeStamp;
this.pCenter = input.center;
if (!validMultiTap || !validInterval) {
this.count = 1;
} else {
this.count += 1;
}
this._input = input;
// if tap count matches we have recognized it,
// else it has began recognizing...
var tapCount = this.count % options.taps;
if (tapCount === 0) {
// no failing requirements, immediately trigger the tap event
// or wait as long as the multitap interval to trigger
if (!this.hasRequireFailures()) {
return STATE_RECOGNIZED;
} else {
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.interval, this);
return STATE_BEGAN;
}
}
}
return STATE_FAILED;
},
failTimeout: function() {
this._timer = setTimeoutContext(function() {
this.state = STATE_FAILED;
}, this.options.interval, this);
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function() {
if (this.state == STATE_RECOGNIZED) {
this._input.tapCount = this.count;
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Simple way to create a manager with a default set of recognizers.
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Hammer(element, options) {
options = options || {};
options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
return new Manager(element, options);
}
/**
* @const {string}
*/
Hammer.VERSION = '2.0.7';
/**
* default settings
* @namespace
*/
Hammer.defaults = {
/**
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @type {Boolean}
* @default true
*/
enable: true,
/**
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* @type {Array}
*/
preset: [
// RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
[RotateRecognizer, {enable: false}],
[PinchRecognizer, {enable: false}, ['rotate']],
[SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
[PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
[TapRecognizer],
[TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
[PressRecognizer]
],
/**
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userSelect: 'none',
/**
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: 'none',
/**
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: 'none',
/**
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: 'none',
/**
* Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: 'none',
/**
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: 'rgba(0,0,0,0)'
}
};
var STOP = 1;
var FORCED_STOP = 2;
/**
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Manager(element, options) {
this.options = assign({}, Hammer.defaults, options || {});
this.options.inputTarget = this.options.inputTarget || element;
this.handlers = {};
this.session = {};
this.recognizers = [];
this.oldCssProps = {};
this.element = element;
this.input = createInputInstance(this);
this.touchAction = new TouchAction(this, this.options.touchAction);
toggleCssProps(this, true);
each(this.options.recognizers, function(item) {
var recognizer = this.add(new (item[0])(item[1]));
item[2] && recognizer.recognizeWith(item[2]);
item[3] && recognizer.requireFailure(item[3]);
}, this);
}
Manager.prototype = {
/**
* set options
* @param {Object} options
* @returns {Manager}
*/
set: function(options) {
assign(this.options, options);
// Options that need a little more setup
if (options.touchAction) {
this.touchAction.update();
}
if (options.inputTarget) {
// Clean up existing event listeners and reinitialize
this.input.destroy();
this.input.target = options.inputTarget;
this.input.init();
}
return this;
},
/**
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
stop: function(force) {
this.session.stopped = force ? FORCED_STOP : STOP;
},
/**
* run the recognizers!
* called by the inputHandler function on every movement of the pointers (touches)
* it walks through all the recognizers and tries to detect the gesture that is being made
* @param {Object} inputData
*/
recognize: function(inputData) {
var session = this.session;
if (session.stopped) {
return;
}
// run the touch-action polyfill
this.touchAction.preventDefaults(inputData);
var recognizer;
var recognizers = this.recognizers;
// this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer = session.curRecognizer;
// reset when the last recognizer is recognized
// or when we're in a new session
if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
curRecognizer = session.curRecognizer = null;
}
var i = 0;
while (i < recognizers.length) {
recognizer = recognizers[i];
// find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the recognizer.
if (session.stopped !== FORCED_STOP && ( // 1
!curRecognizer || recognizer == curRecognizer || // 2
recognizer.canRecognizeWith(curRecognizer))) { // 3
recognizer.recognize(inputData);
} else {
recognizer.reset();
}
// if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
curRecognizer = session.curRecognizer = recognizer;
}
i++;
}
},
/**
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
get: function(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event == recognizer) {
return recognizers[i];
}
}
return null;
},
/**
* add a recognizer to the manager
* existing recognizers with the same event name will be removed
* @param {Recognizer} recognizer
* @returns {Recognizer|Manager}
*/
add: function(recognizer) {
if (invokeArrayArg(recognizer, 'add', this)) {
return this;
}
// remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
recognizer.manager = this;
this.touchAction.update();
return recognizer;
},
/**
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
remove: function(recognizer) {
if (invokeArrayArg(recognizer, 'remove', this)) {
return this;
}
recognizer = this.get(recognizer);
// let's make sure this recognizer exists
if (recognizer) {
var recognizers = this.recognizers;
var index = inArray(recognizers, recognizer);
if (index !== -1) {
recognizers.splice(index, 1);
this.touchAction.update();
}
}
return this;
},
/**
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
on: function(events, handler) {
if (events === undefined) {
return;
}
if (handler === undefined) {
return;
}
var handlers = this.handlers;
each(splitStr(events), function(event) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
});
return this;
},
/**
* unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
off: function(events, handler) {
if (events === undefined) {
return;
}
var handlers = this.handlers;
each(splitStr(events), function(event) {
if (!handler) {
delete handlers[event];
} else {
handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
}
});
return this;
},
/**
* emit event to the listeners
* @param {String} event
* @param {Object} data
*/
emit: function(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
}
// no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) {
return;
}
data.type = event;
data.preventDefault = function() {
data.srcEvent.preventDefault();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
},
/**
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
destroy: function() {
this.element && toggleCssProps(this, false);
this.handlers = {};
this.session = {};
this.input.destroy();
this.element = null;
}
};
/**
* add/remove the css properties as defined in manager.options.cssProps
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = manager.element;
if (!element.style) {
return;
}
var prop;
each(manager.options.cssProps, function(value, name) {
prop = prefixed(element.style, name);
if (add) {
manager.oldCssProps[prop] = element.style[prop];
element.style[prop] = value;
} else {
element.style[prop] = manager.oldCssProps[prop] || '';
}
});
if (!add) {
manager.oldCssProps = {};
}
}
/**
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = document.createEvent('Event');
gestureEvent.initEvent(event, true, true);
gestureEvent.gesture = data;
data.target.dispatchEvent(gestureEvent);
}
assign(Hammer, {
INPUT_START: INPUT_START,
INPUT_MOVE: INPUT_MOVE,
INPUT_END: INPUT_END,
INPUT_CANCEL: INPUT_CANCEL,
STATE_POSSIBLE: STATE_POSSIBLE,
STATE_BEGAN: STATE_BEGAN,
STATE_CHANGED: STATE_CHANGED,
STATE_ENDED: STATE_ENDED,
STATE_RECOGNIZED: STATE_RECOGNIZED,
STATE_CANCELLED: STATE_CANCELLED,
STATE_FAILED: STATE_FAILED,
DIRECTION_NONE: DIRECTION_NONE,
DIRECTION_LEFT: DIRECTION_LEFT,
DIRECTION_RIGHT: DIRECTION_RIGHT,
DIRECTION_UP: DIRECTION_UP,
DIRECTION_DOWN: DIRECTION_DOWN,
DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
DIRECTION_VERTICAL: DIRECTION_VERTICAL,
DIRECTION_ALL: DIRECTION_ALL,
Manager: Manager,
Input: Input,
TouchAction: TouchAction,
TouchInput: TouchInput,
MouseInput: MouseInput,
PointerEventInput: PointerEventInput,
TouchMouseInput: TouchMouseInput,
SingleTouchInput: SingleTouchInput,
Recognizer: Recognizer,
AttrRecognizer: AttrRecognizer,
Tap: TapRecognizer,
Pan: PanRecognizer,
Swipe: SwipeRecognizer,
Pinch: PinchRecognizer,
Rotate: RotateRecognizer,
Press: PressRecognizer,
on: addEventListeners,
off: removeEventListeners,
each: each,
merge: merge,
extend: extend,
assign: assign,
inherit: inherit,
bindFn: bindFn,
prefixed: prefixed
});
// this prevents errors when Hammer is loaded in the presence of an AMD
// style loader but by script tag, not by the loader.
var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
freeGlobal.Hammer = Hammer;
if (typeof define === 'function' && define.amd) {
define(function() {
return Hammer;
});
} else if (typeof module != 'undefined' && module.exports) {
module.exports = Hammer;
} else {
window[exportName] = Hammer;
}
})(window, document, 'Hammer');
},{}]},{},[1]);
| {
"content_hash": "9ba6e07c0ff710b115fd6a1dc1c3e848",
"timestamp": "",
"source": "github",
"line_count": 2707,
"max_line_length": 480,
"avg_line_length": 27.830439601034357,
"alnum_prop": 0.5970373123432046,
"repo_name": "luhdriloh/luhdriloh.github.io",
"id": "409f57ac89a8205b5e7df7ee946de47944241c62",
"size": "75481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bundle.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1801"
},
{
"name": "HTML",
"bytes": "2078"
},
{
"name": "JavaScript",
"bytes": "75481"
}
],
"symlink_target": ""
} |
This directory contains test infrastructure for Minigo, largely based of the
work done by https://github.com/kubeflow/kubeflow.
Our tests are run on the Kubernetes test runner called prow. See the [Prow
docs](https://github.com/kubernetes/test-infra/tree/master/prow) for more
details.
Some UIs to check out:
Testgrid (Test Results Dashboard): https://k8s-testgrid.appspot.com/sig-big-data
Prow (Test-runner dashboard): https://prow.k8s.io/?repo=tensorflow%2Fminigo
## Updating continuous integration tests
You will need to update the `cc-base` Docker image if you modify the certain
files in the repo (e.g. `WORKSPACE`, `.bazelrc`, `cc/tensorflow/*`) because they
will break the Docker cache before the slow `./cc/configure_tensorflow.sh` step.
```shell
(cd cluster/base && PROJECT=tensor-go VERSION_TAG=latest make base-push)
```
See the list of `COPY` files in `cluster/base/Dockerfile` for the complete list.
The test image may need to be rebuilt occasionally if installed libraries or
tools need updating (e.g. `clang-format`, `tensorflow`):
```shell
(cd testing/ && PROJECT=tensor-go VERSION_TAG=latest make pushv2)
```
## Test a pull request locally
You can test a PR sent to github locally using the following steps. This
enables you to poke around if something's failing.
```shell
export PATH=$HOME/go/bin:$PATH
cd $HOME # Or somewhere else outside the minigo repo
git clone git@github.com:kubernetes/test-infra.git
cd test-infra/config
./pj-on-kind.sh pull-tf-minigo-cc
```
Then enter the pull request number when prompted.
To interactively debug the `pj-on-kind` test, edit
`config/jobs/tensorflow/minigo/minigo.yaml` in the `test-infra` repository
and change the command run by `pull-tf-minigo-cc` to run `sleep 10000000`
instead of `./cc/test.sh`.
Find the name of the pod name:
```shell
export KUBECONFIG="$(kind get kubeconfig-path --name="mkpod")"
kubectl get pods --all-namespaces
```
The pod name will be a long hex string, something like
`fc19639a-b497-11e9-95be-ecb1d74c871e`.
You can now attach to the running pod using:
```shell
kubectl exec -it --namespace default $POD_NAME bash
```
## Components
- `../test.sh`: the actual tests that are run. TODO(#188): Change this to
output junit/XML and Prow will split out the tests.
- `Dockerfile`: Run the tests in this container (and pull in test-infra stuff as the runner).
- `Makefile`: Build the Dockerfile
- `bootstrap_v2.sh`: The Prow wrapper. You'll notice that `bootstrap_v2.sh`
does not actually reference `../test.sh`. That gets linked in via Prow's
**Job** config (see below).
## Prow configuration
Minigo has some configuration directly in Prow to make all this jazz work:
- **Test configuration**. This configures the specific test-suites that are run on prow
https://github.com/kubernetes/test-infra/blob/master/config/jobs/tensorflow/minigo/minigo.yaml
- **Test UI Configuration**: What shows up in testgrid, the Prow test-ui?
https://github.com/kubernetes/test-infra/blob/master/testgrid/config.yaml
- **Bootstrap-jobs-config**: This is what links `../test.sh` with
`bootstrap_v2.sh`. See:
https://github.com/kubernetes/test-infra/blob/master/jobs/config.json
- **Other Plugin Config**. We also use the Size and LGTM plugins provided by
Prow. See
https://github.com/kubernetes/test-infra/blob/master/prow/plugins.yaml
| {
"content_hash": "cd697ec407444af452b3e075ab5e42f4",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 96,
"avg_line_length": 34.864583333333336,
"alnum_prop": 0.7487302061547655,
"repo_name": "mlperf/training_results_v0.7",
"id": "f0c5b093afd6e1b015980be6f461706fa293d8ac",
"size": "3365",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "NVIDIA/benchmarks/minigo/implementations/tensorflow/minigo/testing/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Awk",
"bytes": "14530"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "172914"
},
{
"name": "C++",
"bytes": "13037795"
},
{
"name": "CMake",
"bytes": "113458"
},
{
"name": "CSS",
"bytes": "70255"
},
{
"name": "Clojure",
"bytes": "622652"
},
{
"name": "Cuda",
"bytes": "1974745"
},
{
"name": "Dockerfile",
"bytes": "149523"
},
{
"name": "Groovy",
"bytes": "160449"
},
{
"name": "HTML",
"bytes": "171537"
},
{
"name": "Java",
"bytes": "189275"
},
{
"name": "JavaScript",
"bytes": "98224"
},
{
"name": "Julia",
"bytes": "430755"
},
{
"name": "Jupyter Notebook",
"bytes": "11091342"
},
{
"name": "Lua",
"bytes": "17720"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "215967"
},
{
"name": "Perl",
"bytes": "1551186"
},
{
"name": "PowerShell",
"bytes": "13906"
},
{
"name": "Python",
"bytes": "36943114"
},
{
"name": "R",
"bytes": "134921"
},
{
"name": "Raku",
"bytes": "7280"
},
{
"name": "Ruby",
"bytes": "4930"
},
{
"name": "SWIG",
"bytes": "140111"
},
{
"name": "Scala",
"bytes": "1304960"
},
{
"name": "Shell",
"bytes": "1312832"
},
{
"name": "Smalltalk",
"bytes": "3497"
},
{
"name": "Starlark",
"bytes": "69877"
},
{
"name": "TypeScript",
"bytes": "243012"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>100chilly - Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
<meta property="og:title" content="Home">
<meta property="og:site_name" content="100chilly - Home">
<meta property="og:url" content="https://www.100chilly.website/">
<meta property="og:description" content="Personal website of 100chilly/Mitsue Tomohiro">
<meta property="og:type" content="website">
<meta property="og:image" content="https://www.100chilly.website/img/embed.png">
<meta name="theme-color" content="#7289DA">
<meta name="twitter:card" content="summary_large_image">
<link type="application/json+oembed" href="oembed.json">
<link rel="apple-touch-icon" sizes="57x57" href="img/icons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="img/icons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="img/icons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="img/icons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="img/icons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="img/icons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="img/icons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="img/icons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="img/icons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="img/icons/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="img/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="img/icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="img/icons/favicon-16x16.png">
<!-- CSS -->
<link href="libraries/materialize/materialize.min.css" type="text/css" rel="stylesheet">
<link href="libraries/normalize/normalize.css" type="text/css" rel="stylesheet">
<link href="min/plugin-min.css" type="text/css" rel="stylesheet">
<link href="min/custom-min.css" type="text/css" rel="stylesheet" >
<link href="css/style-min.css" type="text/css" rel="stylesheet" >
<script src="https://kit.fontawesome.com/c3ff3e7776.js" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body id="top" class="scrollspy">
<!-- Pre Loader -->
<div id="loader-wrapper">
<div id="loader"></div>
<div class="loader-section section-left"></div>
<div class="loader-section section-right"></div>
</div>
<!--Navigation-->
<div class="navbar-fixed">
<nav id="nav_f" class="default_color" role="navigation">
<div class="container">
<div class="nav-wrapper">
<a href="./" id="logo-container" class="brand-logo" style="color: #0a8bd6;">100chilly</a>
<ul class="right hide-on-med-and-down">
<li><a href="#intro">Who?</a></li>
<li><a href="#works">Projects</a></li>
<li><a href="#social">Social</a></li>
<li><a href="#gallery">Gallery</a></li>
<li><a href="#friends">Friends</a></li>
<!-- <li><a href="#contact">Contact</a></li> -->
<!-- <li><a href="./watch/">Watch</a></li> -->
</ul>
<ul id="nav-mobile" class="side-nav">
<li><a href="#intro">Who?</a></li>
<li><a href="#works">Projects</a></li>
<li><a href="#social">Social</a></li>
<li><a href="#gallery">Gallery</a></li>
<li><a href="#friends">Friends</a></li>
<!-- <li><a href="#contact">Contact</a></li> -->
<!-- <li><a href="./watch/">Watch</a></li> -->
</ul>
<a href="#" data-activates="nav-mobile" class="button-collapse"><i class="importanttext mdi-navigation-menu"></i></a>
</div>
</div>
</nav>
</div>
<!--Hero-->
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<h1 class="text_h center header cd-headline letters type">
<span>I love</span>
<span class="cd-words-wrapper waiting">
<b class="is-visible">video games.</b>
<b>anime.</b>
<b>designing websites.</b>
<b>helping others.</b>
<b>creating communities.</b>
</span>
</h1>
</div>
</div>
<!--Intro and service-->
<div id="intro" class="section scrollspy">
<div class="container">
<div class="row">
<div class="col s12">
<h4 class="center header text_h2"> Hi Everyone! My name is <span class="span_h2">100chilly</span>. I am a <span class="span_h2">Web Developer/Designer</span>, <span class="span_h2">Programmer</span>, and a <span class="span_h2">Gamer.</span></h4>
<h5 class="center text_h2">I've worked on a ton of stuff over the course of <span id="age" class="span_h2">twenty four years</span> on Earth. <span class="span_h2">Below are some of my works, both past and current.</span></h5>
</div>
</div>
</div>
</div>
<div class="parallax-container">
<div class="parallax"><img src="img/parallax0.png"></div>
</div>
<!--Work-->
<div class="section scrollspy" id="works">
<div class="container">
<h2 class="header text_b">Projects I've worked on </h2>
<h5 class="text_b">Note: Please read each website's description as some of the Emails and Links may no longer work!</h5>
<div class="row">
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/project1.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Binary Gaming <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Binary Gaming (2011-2015)<i class="mdi-navigation-close right"></i></span>
<p>This was a gaming community I ran from 2011-2015. I severely underestimated the potential outcome for the community and therfore it was handed over to the <a href="http://binarygaming.net/">australians</a>. </p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/project2.jpg">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">BTC <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">BinaryTech Coalition <i class="mdi-navigation-close right"></i></span>
<p>BinaryTech Coalition was a Player-Made Faction for the indie game, <a href="http://www.spaceengineersgame.com/">Space Engineers</a>. This was a branch of Binary Gaming and is no longer active. </p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/project3.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Qubed Q3 <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Qubed Q3 (2015-2017)<i class="mdi-navigation-close right"></i></span>
<p>Ambitious project I was associated with. <b>Qubed Q3</b> was a very diverse gaming community. We specialized in delivering quality fun and entertainment via livestreams and self-hosted game servers. We ended shutting down on <b>October 31st, 2017</b> due to disagreements.</p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/project4.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">IVGAS <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">International Video Game and Anime Syndicate (2017-2018)<i class="mdi-navigation-close right"></i></span>
<p>A grand project I was associated with. <b>International Video Game and Anime Syndicate (IVGAS)</b> was a new community that didn't just focus on mainstream gaming or even gaming as a whole. We where a very diverse group of people who come from all walks of life and enjoy gaming or anime or even both! We shut down due to over hype killing off our potential gain very early on.</p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/project5.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">MVGD<i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Mitsue's Video Gaming Den<i class="mdi-navigation-close right"></i></span>
<p>Not really a project, but a general place to gather, chit chat and play some video games. If you wanna drop by, please do @ <a href="http://discord.gg/3t2Gjzy">MVGD's Discord</a></p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/project6.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Cyber Radiation <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Cyber Radiation<i class="mdi-navigation-close right"></i></span>
<p>Cyber Radiation is a VRChat Club I work for and partner with. We're a pretty tight knit group of individuals that enjoy eachother's company and enjoy meeting likeminded people. We have SFW and NSFW events every week with new folks joining here and there. If your thinking of joining or want a pretty cool community to hang out in, head over to the Discord @ <a href="https://discord.gg/uzZ3pmS">https://discord.gg/uzZ3pmS</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Parallax-->
<div class="parallax-container">
<div class="parallax"><img src="img/parallax1.png"></div>
</div>
<!--Team-->
<div class="section scrollspy" id="social">
<div class="container">
<h2 class="header text_b"> Social </h2>
<div class="container">
<div class="card">
<div class="card-image">
<img class="activator" src="./img/100chilly.png">
</div>
<div class="card-content">
<span class="card-title activator black-text">100chilly</span>
<p>Astronomical Anomaly</p>
<a class="black-text" href="https://steamcommunity.com/id/100chilly/">
<i class="fab fa-steam-square"></i>
</a>
<a class="black-text" href="https://twitter.com/100chilly">
<i class="fab fa-twitter-square"></i>
</a>
<a class="black-text" href="https://www.facebook.com/100chilly">
<i class="fab fa-facebook-square"></i>
</a>
<a class="black-text" href="https://www.youtube.com/channel/UC9FDHCk3vS-eJViBY5cCsUw">
<i class="fab fa-youtube-square"></i>
</a>
<a class="black-text" href="https://www.twitch.tv/100chilly/">
<i class="fab fa-twitch"></i>
</a>
<a class="black-text" href="https://github.com/100chilly/">
<i class="fab fa-github-square"></i>
</a>
<a class="black-text" href="https://www.reddit.com/user/100chilly/">
<i class="fab fa-reddit-square"></i>
</a>
<a class="black-text" href="https://trello.com/100chilly">
<i class="fab fa-trello"></i>
</a>
<a class="black-text" href="https://soundcloud.com/100chilly">
<i class="fab fa-soundcloud"></i>
</a>
<a class="black-text" href="https://keybase.io/100chilly">
<i class="fab fa-keybase"></i>
</a>
</div>
<div class="card-reveal">
<span class="card-title black-text">About 100chilly<i class="material-icons right">x</i></span>
<p>Also known as Mitsue Tomohiro, Mitsue, or Mitty.</p>
<p>Astronomical Anomaly with a massive weakness to cute things, Clearly an <a href="https://kitsu.io/users/100chilly">Anime</a>/<a href="https://vndb.org/u133269/list">Visual Novels</a> Fan, and <a href="https://steamcommunity.com/id/100chilly/games/?tab=all">PC Gamer</a>.</p>
<p>Likes to experience different cultures, food, and drinks.</p>
<p>Has a very bad habit of playing late night Tech Support for people.</p>
<p>Tech Nerd for sure.</p>
<p>Somewhat shy.</p>
</div>
</div>
</div>
</div>
</div>
<div class="parallax-container">
<div class="parallax"><img src="img/parallax2.png"></div>
</div>
<div class="section scrollspy" id="gallery">
<div class="container">
<h2 class="header text_b"> Gallery </h2>
<div class="row" id="imageGallery">
<iframe src="https://drive.google.com/embeddedfolderview?id=1cRo7PHmmn80ac7g1xByQ9q_KYGk6ohBY#grid" style="width:100%; height:500px; max-width:100%; border:0; position:relative;"></iframe>
</div>
</div>
</div>
<div class="parallax-container">
<div class="parallax"><img src="img/parallax3.png"></div>
</div>
<div class="section scrollspy" id="friends">
<div class="container">
<h2 class="header text_b">Friends of 100chilly/Mitsue </h2>
<div class="row">
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/friends1.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">DwelFlowVR <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">DwelFlowVR (Twitch Streamer)<i class="mdi-navigation-close right"></i></span>
<p>Dwel is a friend of mine who streams over on <a href="https://www.twitch.tv/dwelflowvr" target="_blank">Twitch</a>. They are... a very unique person. They have created such an awesome and wacky community on Twitch and Discord. If you want to check them out, see their <a href="https://twitter.com/DwelVR" target="_blank">Twitter</a> or <a href="https://discord.gg/VGseebX" target="_blank">Discord</a>.</p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/friends2.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">KnoxxFox <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">KnoxxFox/LunaSkylark (Twitch Streamer)<i class="mdi-navigation-close right"></i></span>
<p>KnoxxFox is another great friend of mine. They are mainly a League of Legends streamer. They are eccentric, derpy, and overall chill person to be around. If you're bored or are curious, I highly recommend you check them out on <a href="https://www.twitch.tv/knoxxfox" target="_blank">Twitch</a> or <a href="https://skip.gg/ZoeBotDiscord" target="_blank">Discord</a>.</p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/friends3.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Archangelion and DragonsFae <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Archangelion and DragonsFae (Twitch Streamers)<i class="mdi-navigation-close right"></i></span>
<p>Archangelion and DragonsFae I happend to met on my first day of being a corporal in the LPD and we've been friends ever since. I found out later that they were streamers. They are both vareity streamers over on Twitch.</p>
<p><a href="https://www.twitch.tv/archangelion" target="_blank">Archangelion's Twitch channel</a></p>
<p><a href="https://www.twitch.tv/dragonsfae" target="_blank">DragonFae's Twitch channel</a></p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/friends4.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Nana <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">NanaDragon (VRChat Content Creator)<i class="mdi-navigation-close right"></i></span>
<p>Nana is a friend of mine who creates adorable and funny vrchat clips/content. They're such an adorable ball of dragon energy and always seem to be doing their best. If you want to check them out, see their <a href="https://twitter.com/NanaDragonLoli" target="_blank">Twitter</a>.</p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/friends5.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Byakko Howaito <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Byakko Howaito (Content Creator)<i class="mdi-navigation-close right"></i></span>
<p>Byakko is an adorable celestial white tiger and a friend of mine who streams over on <a href="https://www.twitch.tv/ByakkoHowaito" target="_blank">Twitch</a>. Cute and adorable as they are, they always put a smile on my face. If you want to check them out, see their <a href="https://twitter.com/ByakkoMedia" target="_blank">Twitter</a> or <a href="https://discord.gg/byakkohowaito" target="_blank">Discord</a>.</p>
</div>
</div>
</div>
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="img/friends6.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">JonsAtWar <i class="mdi-navigation-more-vert right"></i></span>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">JonsAtWar (Twitch Streamer)<i class="mdi-navigation-close right"></i></span>
<p>Jonathan is a friend of mine who streams over on <a href="https://www.twitch.tv/jonsatwar" target="_blank">Twitch</a>. They are former army, a father, and a friend. They also stream for <a href="https://www.stackup.org/" target="_blank">Stack Up</a>, a really cool military charity (check them out as well). If you want to check Jonathan out, see their <a href="https://twitter.com/JonsAtWar" target="_blank">Twitter</a> or <a href="https://bit.ly/wardiscord" target="_blank">Discord</a>.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="parallax-container">
<div class="parallax"><img src="img/parallax4.png"></div>
</div>
<!--Footer-->
<<footer id="contact" class="page-footer scrollspy">
<div class="container">
<!-- <div class="row">
<div class="col l3 s12">
<h5 class="white-text"></h5>
<ul class="white-text">
</ul>
</div>
<div class="col l6 s12">
<form class="col s12" action="contact.php" method="post">
<div class="row">
<div class="input-field col s6">
<i class="mdi-action-account-circle prefix white-text"></i>
<input id="icon_prefix" name="name" type="text" class="validate white-text">
<label for="icon_prefix" class="white-text">First Name</label>
</div>
<div class="input-field col s6">
<i class="mdi-communication-email prefix white-text"></i>
<input id="icon_email" name="email" type="email" class="validate white-text">
<label for="icon_email" class="white-text">Email</label>
</div>
<div class="input-field col s12">
<i class="mdi-editor-mode-edit prefix white-text"></i>
<textarea id="icon_prefix2" name="message" class="materialize-textarea white-text"></textarea>
<label for="icon_prefix2" class="white-text">Message</label>
</div>
<div class="col offset-s7 s5">
<button class="btn waves-effect waves-light blue darken-1" type="submit">Submit
<i class="mdi-content-send right white-text"></i>
</button>
</div>
</div>
</form>
</div>
<div class="col l3 s12">
<h5 class="white-text"></h5>
<ul class="white-text">
</ul>
</div>
<div class="col l3 s12">
<h5 class="white-text">Favorite Quote:</h5>
<ul class="white-text">
<li style="font-size: 190%; text-shadow: 2px 2px 4px;">"No. Try not. Do... or do not. There is no try."</li>
<li style="font-size: 200%;">~Master Yoda</li>
</ul>
</div>
</div> -->
</div>
<div class="footer-copyright default_color">
<div class="container">
Made by <a class="importanttext" href="https://www.100chilly.website/">100chilly</a> (© 100chilly)
</div>
</div>
</footer>
<!-- Scripts-->
<script defer src="libraries/jquery/jquery-3.5.1.min.js"></script>
<script defer src="libraries/materialize/materialize.min.js"></script>
<script defer src="min/plugin-min.js"></script>
<script defer src="js/init.js"></script>
<script defer src="js/age.js"></script>
<script defer src="js/carousel.js"></script>
</body>
</html> | {
"content_hash": "19d371ed5bfed1fa7cd33b1e0207f69e",
"timestamp": "",
"source": "github",
"line_count": 453,
"max_line_length": 519,
"avg_line_length": 60.04415011037528,
"alnum_prop": 0.5321691176470589,
"repo_name": "100chilly/100chilly.github.io",
"id": "954516cf38dd64a44b2aeb681dbe38e29807e73d",
"size": "27200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8171"
},
{
"name": "HTML",
"bytes": "25492"
},
{
"name": "JavaScript",
"bytes": "18711"
},
{
"name": "PHP",
"bytes": "1626"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>admin-linux: _cookbook.thread.semaphore Namespace Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">admin-linux
 <span id="projectnumber">0.0.0</span>
</div>
<div id="projectbrief">Admin Linux</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="../../index.html"><span>Main Page</span></a></li>
<li class="current"><a href="../../namespaces.html"><span>Packages</span></a></li>
<li><a href="../../annotated.html"><span>Classes</span></a></li>
<li><a href="../../files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="../../search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="../../search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="../../namespaces.html"><span>Packages</span></a></li>
<li><a href="../../namespacemembers.html"><span>Package Functions</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Variables</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="../../de/db4/namespace__cookbook.html">_cookbook</a></li><li class="navelem"><a class="el" href="../../d3/d1f/namespace__cookbook_1_1thread.html">thread</a></li><li class="navelem"><a class="el" href="../../d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html">semaphore</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#func-members">Functions</a> |
<a href="#var-members">Variables</a> </div>
<div class="headertitle">
<div class="title">_cookbook.thread.semaphore Namespace Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="../../dc/ddd/class__cookbook_1_1thread_1_1semaphore_1_1Producer.html">Producer</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="../../de/dfa/class__cookbook_1_1thread_1_1semaphore_1_1Cusumer.html">Cusumer</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a5fbba75227af2444a9cd91f99d4cca94"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html#a5fbba75227af2444a9cd91f99d4cca94">test_semaphore</a></td></tr>
<tr class="separator:a5fbba75227af2444a9cd91f99d4cca94"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="var-members"></a>
Variables</h2></td></tr>
<tr class="memitem:a9a0b5a124aff3e078787972f21d297e3"><td class="memItemLeft" align="right" valign="top">list </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html#a9a0b5a124aff3e078787972f21d297e3">share</a> = []</td></tr>
<tr class="separator:a9a0b5a124aff3e078787972f21d297e3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a67e6819d1307ed665cb515e3f47a990e"><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html#a67e6819d1307ed665cb515e3f47a990e">MAX_COUNTS</a> = 5</td></tr>
<tr class="separator:a67e6819d1307ed665cb515e3f47a990e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a522d222885e9efd1ac70e59a9c880c8f"><td class="memItemLeft" align="right" valign="top">tuple </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html#a522d222885e9efd1ac70e59a9c880c8f">semaphore</a> = threading.BoundedSemaphore(<a class="el" href="../../d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html#a67e6819d1307ed665cb515e3f47a990e">MAX_COUNTS</a>)</td></tr>
<tr class="separator:a522d222885e9efd1ac70e59a9c880c8f"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function Documentation</h2>
<a class="anchor" id="a5fbba75227af2444a9cd91f99d4cca94"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">def _cookbook.thread.semaphore.test_semaphore </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<pre class="fragment">Test multithreading using Semaphore.</pre>
<p>Definition at line <a class="el" href="../../d7/dd3/semaphore_8py_source.html#l00076">76</a> of file <a class="el" href="../../d7/dd3/semaphore_8py_source.html">semaphore.py</a>.</p>
</div>
</div>
<h2 class="groupheader">Variable Documentation</h2>
<a class="anchor" id="a67e6819d1307ed665cb515e3f47a990e"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int _cookbook.thread.semaphore.MAX_COUNTS = 5</td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d7/dd3/semaphore_8py_source.html#l00038">38</a> of file <a class="el" href="../../d7/dd3/semaphore_8py_source.html">semaphore.py</a>.</p>
</div>
</div>
<a class="anchor" id="a522d222885e9efd1ac70e59a9c880c8f"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">tuple _cookbook.thread.semaphore.semaphore = threading.BoundedSemaphore(<a class="el" href="../../d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html#a67e6819d1307ed665cb515e3f47a990e">MAX_COUNTS</a>)</td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d7/dd3/semaphore_8py_source.html#l00039">39</a> of file <a class="el" href="../../d7/dd3/semaphore_8py_source.html">semaphore.py</a>.</p>
</div>
</div>
<a class="anchor" id="a9a0b5a124aff3e078787972f21d297e3"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">list _cookbook.thread.semaphore.share = []</td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d7/dd3/semaphore_8py_source.html#l00037">37</a> of file <a class="el" href="../../d7/dd3/semaphore_8py_source.html">semaphore.py</a>.</p>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Sep 17 2014 14:49:33 for admin-linux by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html>
| {
"content_hash": "703c6228831c403a563688ef39704a4f",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 823,
"avg_line_length": 56.12765957446808,
"alnum_prop": 0.6660348749052313,
"repo_name": "leven-cn/admin-linux",
"id": "21c568cdeab80bc8153afde5602271d74800a3a2",
"size": "10552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/html/d4/dbe/namespace__cookbook_1_1thread_1_1semaphore.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "29559"
},
{
"name": "JavaScript",
"bytes": "48783"
},
{
"name": "Python",
"bytes": "40094"
},
{
"name": "TeX",
"bytes": "283920"
},
{
"name": "VimL",
"bytes": "5886"
}
],
"symlink_target": ""
} |
.charsheet {
position: absolute;
left: 0;
padding: 0 0 0 10px !important;
height: calc(100% - 70px);
width: calc(100% - 12px);
}
.sheet-content {
height: 100%;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: column;
}
.sheet-body {
display: block;
padding: 5px 0 5px 0;
overflow-x: visible;
overflow-y: scroll;
position: relative;
flex: 1 1 auto;
}
.sheet-body::-webkit-scrollbar {
-webkit-appearance: none;
width: 8px;
height: 8px;
}
.sheet-body::-webkit-scrollbar-thumb {
border-radius: 4px;
border: 2px solid transparent;
background-color: rgba(0, 0, 0, .5);
}
.sheet-footer {
padding-top: 3px;
text-align: right;
background: url(http://i.imgur.com/R0FTYGB.jpg) white no-repeat;
flex: 0 0 auto;
}
.sheet-footer button[type=roll] {
background: transparent;
border: 2px solid gray;
}
.sheet-txt-lg { font-size: 150%; }
.sheet-80pct { width: 80% !important; }
.sheet-text-right { text-align: right; }
.sheet-text-center { text-align: center; }
button[type=roll]::before { content: "" !important; }
button[type=roll].btn {
font-size: 13px;
line-height: 13px;
}
.sheet-fixedwidth { display: inline-block; }
.sheet-center-table.sheet-80pct {
margin-left: 10%;
margin-right: 10%;
}
.sheet-table {
display: table;
width: 100%;
position: relative;
}
.sheet-table-header { display: table-header-group; }
div.sheet-table-body,
fieldset.sheet-table-body + .repcontainer { display: table-row-group; }
.sheet-table-row,
.sheet-table .repcontrol,
.sheet-table-body + .repcontainer .repitem { display: table-row; }
.sheet-table-cell { display: table-cell; }
.sheet-table-header .sheet-table-cell { font-weight: bold; }
.sheet-table-cell:not(:last-child) { padding-right: 3px; }
.sheet-table .repcontrol { width: 100%; }
.sheet-table .repcontainer + .repcontrol .repcontrol_edit {
position: absolute;
right: 0;
}
.sheet-table .editmode + .repcontrol .repcontrol_edit {
right: 41px;
left: initial;
}
.sheet-table [data-groupname=repeating_intimacies].editmode + .repcontrol .repcontrol_edit,
.sheet-table [data-groupname=repeating_charms].editmode + .repcontrol .repcontrol_edit,
.sheet-table [data-groupname=repeating_spells].editmode + .repcontrol .repcontrol_edit { right: 0; }
[data-groupname=repeating_weapon].editmode .repitem .itemcontrol,
[data-groupname=repeating_armor].editmode .repitem .itemcontrol,
[data-groupname=repeating_intimacies].editmode .repitem .itemcontrol,
[data-groupname=repeating_spells].editmode .repitem .itemcontrol { height: 28px; }
[data-groupname=repeating_weapon].editmode .repitem .itemcontrol { width: calc(100% - 41px); }
[data-groupname=repeating_armor].editmode .repitem .itemcontrol { width: calc(100% - 30px); }
[data-groupname=repeating_weapon].editmode .sheet-table-cell,
[data-groupname=repeating_armor].editmode .sheet-table-cell { position: relative; }
[data-groupname=repeating_weapon].editmode .sheet-table-cell { left: -41px; }
[data-groupname=repeating_armor].editmode .sheet-table-cell { left: -30px; }
.sheet-flexbox-h > label,
.sheet-flexbox0 {
width: 100%;
line-height: 28px;
margin-bottom: 0;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
}
.sheet-flexbox-inline {
display: -webkit-inline-flex;
display: inline-flex;
width: 100%;
}
.sheet-flexbox-inline > label > span {
white-space: nowrap;
font-size: 89%;
}
.sheet-flexbox-h input[type=text],
.sheet-flexbox-h input[type=number],
.sheet-flexbox-h select {
-webkit-flex: 1 1 40%;
flex: 1 1 40%;
margin-left: 5px;
}
.sheet-2col {
display: inline-block;
vertical-align: top;
}
.sheet-3colrow .sheet-2col:last-child { margin-right: 0; }
.sheet-3colrow .sheet-2col {
width: calc(66% - 5px);
margin-right: 30px;
}
.sheet-2col .sheet-2colrow .sheet-col {
width: calc(50% - 11px);
margin-right: 18px;
position: relative;
}
[title] { cursor: help; }
.sheet-dotted { border-bottom: 1px dotted black; }
input[type=text],
input[type=number] {
display: inline-block;
width: 165px;
font-size: 12pt;
height: 25px;
border: 0px;
border-bottom: 1px solid black;
border-radius: 0px;
background-color: transparent;
}
input[type=number] { text-align: center; }
input[type=number][disabled],
input[type=number][readonly],
select[disabled] {
background-color: rgba(128, 128, 128, 0.25);
}
input[type=text]:not(:focus),
input[type=number]:not(:focus),
[readonly]:focus {
-moz-box-shadow: 0 0 0 #000;
-webkit-box-shadow: 0 0 0 #000;
box-shadow: 0 0 0 #000;
}
h1,
hr {
background-image: url(http://i.imgur.com/TwZ84rO.jpg);
background-position: left 50%;
background-repeat: repeat-x;
background-size: auto 10px;
text-align: center;
width: 100%;
}
hr { height: 10px; }
label {
font-size: 16px;
display: inline;
cursor: pointer;
padding-right: 0;
}
h1 span {
background: #fff;
padding: 0 5px;
font-variant: small-caps;
}
*, .sheet-printed { font-family: Cimiez, Arial, sans-serif; }
input, select, option, optgroup, textarea, .btn:not([type=roll]) { font-family: Arial, sans-serif; }
.btn.pictos { font-family: Pictos; }
* { font-variant: small-caps; }
input, select, option, optgroup, textarea, .sheet-normal-caps, .btn:not([type=roll]) { font-variant: normal; }
::-webkit-input-placeholder { font-style: italic; }
:-moz-placeholder { font-style: italic; }
::-moz-placeholder { font-style: italic; }
:-ms-input-placeholder { font-style: italic; }
.sheet-trait > * {
vertical-align: middle;
}
.sheet-trait {
position: relative;
margin-bottom: 3px;
}
.sheet-6rows {
height: calc(6em + 30px);
}
.sheet-motes {
margin-top: 10px;
clear: right;
position: relative;
padding-left: 30px;
}
.sheet-motes input[type=number] {
width: 1.75em;
font-size: 16px;
}
.sheet-motes:last-child input[type=number] { width: 71px; }
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance: textfield;
}
.sheet-motes span { display: inline-block; }
.sheet-motes span:last-child {
position: absolute;
right: 40px;
font-size: 20px;
}
textarea {
resize: none;
width: 96%;
background-color: transparent;
}
select {
width: 45px;
margin-bottom: 0;
background-color: transparent;
border: 0;
border-bottom: 1px solid black;
border-radius: 0;
}
table td,
table th {
font-size: 13px;
font-weight: bolder;
font-family: "arial";
text-align: left;
width: 0%;
border: 0px #000000;
padding: 2px;
vertical-align: middle;
color: #000000;
margin:0px 0px;
}
h2 {
text-decoration:overline underline;
}
/* Hide actual checkbox */
input[type=checkbox] {
position: absolute;
opacity: 0.0;
width: 15px;
cursor: pointer;
z-index: 10;
margin-top: 5px;
}
/* Styles for fake checkbox (checked or unchecked) */
input[type=checkbox] + span::before {
border: solid 1px #000000;
line-height: 11px;
text-align: center;
display: inline-block;
vertical-align: middle;
-moz-box-shadow: 0 0 0 #000;
-webkit-box-shadow: 0 0 0 #000;
box-shadow: 0 0 0 #000;
background: #000000;
background: -moz-radial-gradient(#f6f6f6, #dfdfdf);
background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);
background: -ms-radial-gradient(#f6f6f6, #dfdfdf);
background: -o-radial-gradient(#f6f6f6, #dfdfdf);
background: radial-gradient(#f6f6f6, #dfdfdf);
position: relative;
content: "";
opacity: 1.0;
width: 10px;
height: 10px;
font-size: 12px;
-moz-border-radius: 1px;
-webkit-border-radius: 1px;
border-radius: 1px;
}
/* Fake checkbox (checked) */
input[type=checkbox]:checked + span::before {
content: "✓";
color: #a00;
font-weight: bold;
-moz-box-shadow: 0 0 2px transparent;
-webkit-box-shadow: 0 0 2px transparent;
box-shadow: 0 0 2px transparent;
}
/* Crafting/MA popup */
input[type=checkbox].sheet-unnamed-toggle {
width: 100%;
height: 100%;
margin: 0;
}
input[type=checkbox].sheet-unnamed-toggle + span::before {
width: 100%;
height: calc(100% - 3px);
content: attr(title);
text-align: center;
line-height: 100%;
font-size: 18px;
overflow: hidden;
}
.sheet-layer7,
.sheet-layer7::before { z-index: 7; }
.sheet-layer6,
.sheet-layer6::before { z-index: 6; }
.sheet-layer5,
.sheet-layer5::before { z-index: 5; }
.sheet-layer4,
.sheet-layer4::before { z-index: 4; }
.sheet-layer3,
.sheet-layer3::before { z-index: 3; }
input[type=checkbox].sheet-unnamed-toggle:checked + span::before {
border-bottom: 0;
}
input[type=checkbox].sheet-unnamed-toggle:not(:checked) + span + div { display: none; }
input[type=checkbox].sheet-unnamed-toggle:checked + span + div {
display: block;
position: relative;
top: -1px;
left: -142px;
border: 1px solid black;
padding: 5px;
background-color: #f6f6f6;
width: 250px;
}
.sheet-unnamed-toggle + span + div > .sheet-trait > label,
[data-groupname=repeating_crafts] input,
[data-groupname=repeating_ma] input { width: 130px; }
.sheet-unnamed-toggle + span + div > .sheet-trait > label,
.sheet-unnamed-toggle + span + div > .sheet-trait > label > label,
[class=sheet-equations] input {
width: 100px;
padding-left: 5px;
}
[data-groupname=repeating_abilities] input[type=text] { width: 120px; }
[data-groupname=repeating_specialties] input,
.sheet-crafting-projects input { margin-top: 3px; }
[data-groupname=repeating_merits] .repitem {
display: inline-block;
width: calc(50% - 20px);
margin-right: 20px;
position: relative;
}
[data-groupname=repeating_merits] input[type=text] { width: calc(100% - 120px); }
[data-groupname=repeating_weapon] input[type=text] { width: 170px; }
[data-groupname=repeating_weapon] input[type=number] { width: 40px; }
[data-groupname=repeating_intimacies] input[type=text],
[data-groupname=repeating_charms] input,
[data-groupname=repeating_spells] input[type=text],
[data-groupname=repeating_spells] input[type=number] {
width: 80px;
margin-top: 3px;
}
[data-groupname=repeating_intimacies] select,
[data-groupname=repeating_intimacies] input[type=text] { width: 100%; }
[data-groupname=repeating_weapon] input,
[data-groupname=repeating_armor] input,
[data-groupname=repeating_intimacies] select,
[data-groupname=repeating_intimacies] input[type=text],
[data-groupname=repeating_charms] select,
[data-groupname=repeating_charms] input[type=text],
[data-groupname=repeating_charms] input[type=number],
[data-groupname=repeating_spells] select,
[data-groupname=repeating_spells] input[type=text],
[data-groupname=repeating_spells] input[type=number] { margin-bottom: 3px; }
.sheet-unnamed-toggle + span + div > .sheet-trait > label {
display: inline-block;
margin: 0;
}
.repcontrol_del,
.repcontrol_move {
z-index: 11;
position: absolute;
}
.repcontrol_del { right: 0; }
.editmode + .repcontrol .repcontrol_edit {
float: none !important;
position: relative;
left: calc(100% - 52px);
}
.repcontainer { margin-bottom: 5px; }
/* Rotating click to set dots */
div.sheet-dots,
div.sheet-dots input[class^=sheet-dots],
div.sheet-dots input[class^=sheet-dots] + span {
width: 100px;
height: 20px;
}
div.sheet-damage-box { margin-left: 2px; }
div.sheet-damage-box,
div.sheet-damage-box input[class^=sheet-dots],
div.sheet-damage-box input[class^=sheet-dots] + span {
width: 20px;
height: 20px;
}
div.sheet-dots-full,
div.sheet-dots-full input[class^=sheet-dots],
div.sheet-dots-full input[class^=sheet-dots] + span {
width: 251px;
height: 20px;
}
input[class^=sheet-dots],
input[class^=sheet-dots] + span,
input[class^=sheet-dots] + span::before {
position: absolute;
top: 0;
left: 0;
}
div.sheet-dots {
display: inline-block;
position: absolute;
padding: 0;
right: 15px;
}
div.sheet-dots-full,
div.sheet-damage-box {
position: relative;
}
input[class^=sheet-dots] + span {
display: inline-block;
z-index: 0;
}
input[class^=sheet-dots] {
opacity: 0;
z-index: 1;
}
input.sheet-dots0 { z-index: 2; }
.sheet-layer3 input.sheet-dots0 { z-index: 5; }
.sheet-layer5 input.sheet-dots0 { z-index: 7; }
input.sheet-dots0:checked ~ input.sheet-dots1,
input.sheet-dots1:checked ~ input.sheet-dots2,
input.sheet-dots2:checked ~ input.sheet-dots3,
input.sheet-dots3:checked ~ input.sheet-dots4,
input.sheet-dots4:checked ~ input.sheet-dots5,
input.sheet-dots5:checked ~ input.sheet-dots6,
input.sheet-dots6:checked ~ input.sheet-dots7,
input.sheet-dots7:checked ~ input.sheet-dots8,
input.sheet-dots8:checked ~ input.sheet-dots9,
input.sheet-dots9:checked ~ input.sheet-dots10 { z-index: 3; }
.sheet-layer4 input.sheet-dots0:checked ~ input.sheet-dots1,
.sheet-layer4 input.sheet-dots1:checked ~ input.sheet-dots2,
.sheet-layer4 input.sheet-dots2:checked ~ input.sheet-dots3,
.sheet-layer4 input.sheet-dots3:checked ~ input.sheet-dots4,
.sheet-layer4 input.sheet-dots4:checked ~ input.sheet-dots5,
.sheet-layer4 input.sheet-dots5:checked ~ input.sheet-dots6,
.sheet-layer4 input.sheet-dots6:checked ~ input.sheet-dots7,
.sheet-layer4 input.sheet-dots7:checked ~ input.sheet-dots8,
.sheet-layer4 input.sheet-dots8:checked ~ input.sheet-dots9,
.sheet-layer4 input.sheet-dots9:checked ~ input.sheet-dots10 { z-index: 6; }
.sheet-layer6 input.sheet-dots0:checked ~ input.sheet-dots1,
.sheet-layer6 input.sheet-dots1:checked ~ input.sheet-dots2,
.sheet-layer6 input.sheet-dots2:checked ~ input.sheet-dots3,
.sheet-layer6 input.sheet-dots3:checked ~ input.sheet-dots4,
.sheet-layer6 input.sheet-dots4:checked ~ input.sheet-dots5,
.sheet-layer6 input.sheet-dots5:checked ~ input.sheet-dots6,
.sheet-layer6 input.sheet-dots6:checked ~ input.sheet-dots7,
.sheet-layer6 input.sheet-dots7:checked ~ input.sheet-dots8,
.sheet-layer6 input.sheet-dots8:checked ~ input.sheet-dots9,
.sheet-layer6 input.sheet-dots9:checked ~ input.sheet-dots10 { z-index: 8; }
div.sheet-dots input.sheet-dots0:checked + span::before { content: url(http://i.imgur.com/brHawNF.png); }
div.sheet-dots input.sheet-dots1:checked + span::before { content: url(http://i.imgur.com/FxaE1ej.png); }
div.sheet-dots input.sheet-dots2:checked + span::before { content: url(http://i.imgur.com/mmaaeuA.png); }
div.sheet-dots input.sheet-dots3:checked + span::before { content: url(http://i.imgur.com/XzoEKTo.png); }
div.sheet-dots input.sheet-dots4:checked + span::before { content: url(http://i.imgur.com/7Km42YB.png); }
div.sheet-dots input.sheet-dots5:checked + span::before { content: url(http://i.imgur.com/fQOCs6f.png); }
div.sheet-dots input.sheet-dots6:checked + span::before { content: url(http://i.imgur.com/5viTRx5.png); }
div.sheet-dots input.sheet-dots7:checked + span::before { content: url(http://i.imgur.com/r51uCCA.png); }
div.sheet-dots input.sheet-dots8:checked + span::before { content: url(http://i.imgur.com/QlLZpUb.png); }
div.sheet-dots input.sheet-dots9:checked + span::before { content: url(http://i.imgur.com/mnoMk57.png); }
div.sheet-dots input.sheet-dots10:checked + span::before { content: url(http://i.imgur.com/jhxHSkd.png); }
div.sheet-dots-full input.sheet-dots0:checked + span::before { content: url(http://i.imgur.com/aoLkPUD.png); }
div.sheet-dots-full input.sheet-dots1:checked + span::before { content: url(http://i.imgur.com/yuMkIYx.png); }
div.sheet-dots-full input.sheet-dots2:checked + span::before { content: url(http://i.imgur.com/v8N22sh.png); }
div.sheet-dots-full input.sheet-dots3:checked + span::before { content: url(http://i.imgur.com/f4los8X.png); }
div.sheet-dots-full input.sheet-dots4:checked + span::before { content: url(http://i.imgur.com/JcMtOks.png); }
div.sheet-dots-full input.sheet-dots5:checked + span::before { content: url(http://i.imgur.com/b5t5pWv.png); }
div.sheet-dots-full input.sheet-dots6:checked + span::before { content: url(http://i.imgur.com/DrkRvoQ.png); }
div.sheet-dots-full input.sheet-dots7:checked + span::before { content: url(http://i.imgur.com/P8edx1p.png); }
div.sheet-dots-full input.sheet-dots8:checked + span::before { content: url(http://i.imgur.com/lJPrvey.png); }
div.sheet-dots-full input.sheet-dots9:checked + span::before { content: url(http://i.imgur.com/updBVIp.png); }
div.sheet-dots-full input.sheet-dots10:checked + span::before { content: url(http://i.imgur.com/1ymfexj.png); }
div.sheet-damage-box input.sheet-dots0:checked + span::before { content: url(http://i.imgur.com/HAiWBJU.png); }
div.sheet-damage-box input.sheet-dots1:checked + span::before { content: url(http://i.imgur.com/ZA7t2og.png); }
div.sheet-damage-box input.sheet-dots2:checked + span::before { content: url(http://i.imgur.com/Skkftsx.png); }
div.sheet-damage-box input.sheet-dots3:checked + span::before { content: url(http://i.imgur.com/WwEsO6c.png); }
input.sheet-dots0,
input[class^=sheet-dots]:checked + span + input { cursor: pointer; }
.sheet-temp-will { padding-left: 12px; }
.sheet-temp-will input,
.sheet-temp-will input + span {
margin-right: 9.75px;
}
.sheet-temp-will input:last-child,
.sheet-temp-will input:last-child + span {
margin: 0;
}
.sheet-health-track { text-align: center; }
.sheet-health-level {
display: inline-block;
width: 23.6px;
}
.sheet-health-level select {
width: 23px;
-webkit-appearance: none;
-moz-appearance: none;
text-indent: 4px;
text-overflow: '';
cursor: pointer;
font-weight: bolder;
font-family: Cimiez, Arial, sans-serif;
color: #d00;
height: 23px;
padding: 0;
font-size: 13px;
}
.sheet-health-level select::-ms-expand { display: none; }
@font-face {
font-family: Cimiez;
src: local('Cimiez Roman PDF.ttf'),
url(http://lithl.info/cimiez.ttf) format('truetype');
}
/* Sheet head tabs */
div.sheet-tab-content {
display: none;
border-top:1px solid #ffffff;
margin-top:2px;
}
input.sheet-tab-character-sheet:checked ~ div.sheet-tab-character-sheet,
input.sheet-tab-spell-sheet:checked ~ div.sheet-tab-spell-sheet,
input.sheet-tab-charm-sheet:checked ~ div.sheet-tab-charm-sheet,
input.sheet-tab-settings-sheet:checked ~ div.sheet-tab-settings-sheet,
{
display: block;
}
input.sheet-tab {
width: 140px;
height: 30px;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
border:none;
outline:none;
position: relative;
cursor: pointer;
z-index: 1;
}
input.sheet-tab::before {
content: attr(title);
border:1px solid #444;
border-top:0;
border-radius:0 0 10px 10px;
sheet-text-align: center;
display: block;
color:#444;
background:#fff;
width: 140px;
line-height: 30px;
font-size: 16px;
text-align:center
}
input.sheet-tab-charms::before,
input.sheet-tab-charms {
width: 80px;
}
input.sheet-tab-spells::before,
input.sheet-tab-spells {
width: 90px;
}
input.sheet-tab-settings::before,
input.sheet-tab-settings {
width: 30px;
font-family:Pictos;
}
input.sheet-tab:active,
input.sheet-tab:focus {
outline:none;
}
input.sheet-tab:hover::before {
background:#840000;
color: #FFDF00;
}
input.sheet-tab:checked::before,
input.sheet-tab:checked:hover::before {
background:#840000;
color: #FFDF00;
font-weight:bold;
}
/* Spell / Charm tabs */
div.sheet-charm-effect,
div.sheet-spell-effect {
display: none;
padding-top: 5px;
}
input.sheet-charmeffect:checked ~ div.sheet-charm-effect,
input.sheet-spelleffect:checked ~ div.sheet-spell-effect {
display: block;
}
input.sheet-charmeffect,
input.sheet-spelleffect {
width:99%;
background-color: #f6f6f6;
height: 20px;
margin: 0;
}
input.sheet-charmeffect + span::before,
input.sheet-spelleffect + span::before {
width: 99%;
height: calc(100% - 3px);
content: attr(title);
text-align: center;
line-height: 100%;
font-size: 18px;
}
input.sheet-charmeffect:checked + span:before,
input.sheet-spelleffect:checked + span:before {
content: attr(title) !important;
}
.sheet-charms-spells-trait{
font-size: 12px;
}
input.sheet-charms-spells-trait{
height:20px;
font-size: 12px;
}
| {
"content_hash": "7168fa73e744fb8f4d6f00ca64b7187a",
"timestamp": "",
"source": "github",
"line_count": 750,
"max_line_length": 111,
"avg_line_length": 27.469333333333335,
"alnum_prop": 0.6801281428987477,
"repo_name": "Lithl/roll20-character-sheets",
"id": "0cbb3496c16e9be4c81fb22eacb498ec3063f478",
"size": "20604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Exalted 3/Ex3-Sheet.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6507037"
},
{
"name": "HTML",
"bytes": "64979271"
},
{
"name": "JavaScript",
"bytes": "546130"
},
{
"name": "Makefile",
"bytes": "50"
}
],
"symlink_target": ""
} |
namespace AssemblyLine.Common.Exceptions
{
public class ConflictException : AssemblyLineException
{
public ConflictException(string message)
: base(message)
{
}
}
} | {
"content_hash": "f58bb8a8d6d73280a7bdf9ad25a26db9",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 58,
"avg_line_length": 21.3,
"alnum_prop": 0.6244131455399061,
"repo_name": "alexey-ernest/assembly-line",
"id": "77403a61ad165fd9ce2838e6d72045ba996b8367",
"size": "215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AssemblyLine.Common/Exceptions/ConflictException.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "106"
},
{
"name": "C#",
"bytes": "190726"
},
{
"name": "CSS",
"bytes": "1100"
},
{
"name": "HTML",
"bytes": "5069"
},
{
"name": "JavaScript",
"bytes": "62940"
}
],
"symlink_target": ""
} |
// Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <XCTest/XCTest.h>
#import "MDCFontTextStyle.h"
#import "MDCTypography.h"
#import "UIFont+MaterialTypography.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wprivate-header"
#import "UIFont+MaterialTypographyPrivate.h"
#pragma clang diagnostic pop
NS_ASSUME_NONNULL_BEGIN
static const CGFloat kEpsilon = (CGFloat)0.001;
/**
For our tests we are following a Given When Then structure as defined in
http://martinfowler.com/bliki/GivenWhenThen.html
The essential idea is to break down writing a scenario (or test) into three sections:
The |given| part describes the state of the world before you begin the behavior you're specifying
in this scenario. You can think of it as the pre-conditions to the test.
The |when| section is that behavior that you're specifying.
Finally the |then| section describes the changes you expect due to the specified behavior.
For us this just means that we have the Given When Then guide posts as comments for each unit test.
*/
@interface TypographyTests : XCTestCase
@end
/** This font loader is for Bodoni Ornaments and is for testing the missing bold/italic fonts. */
@interface BodoniOrnamentsFontLoader : NSObject <MDCTypographyFontLoading>
@end
@implementation BodoniOrnamentsFontLoader
- (nullable UIFont *)lightFontOfSize:(CGFloat)fontSize {
return [UIFont fontWithName:@"Bodoni Ornaments" size:fontSize];
}
- (UIFont *)regularFontOfSize:(CGFloat)fontSize {
return [UIFont fontWithName:@"Bodoni Ornaments" size:fontSize];
}
- (nullable UIFont *)mediumFontOfSize:(CGFloat)fontSize {
return [UIFont fontWithName:@"Bodoni Ornaments" size:fontSize];
}
@end
@implementation TypographyTests
#pragma mark - font name and size
- (void)testDisplay4Font {
// Given
// When
UIFont *font = [MDCTypography display4Font];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 112, kEpsilon,
@"The font size of display 4 must be 112.");
}
- (void)testDisplay3Font {
// Given
// When
UIFont *font = [MDCTypography display3Font];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 56, kEpsilon,
@"The font size of display 3 must be 56.");
}
- (void)testDisplay2Font {
// Given
// When
UIFont *font = [MDCTypography display2Font];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 45, kEpsilon,
@"The font size of display 2 must be 45.");
}
- (void)testDisplay1Font {
// Given
// When
UIFont *font = [MDCTypography display1Font];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 34, kEpsilon,
@"The font size of display 1 must be 32.");
}
- (void)testHeadlineFont {
// Given
// When
UIFont *font = [MDCTypography headlineFont];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 24, kEpsilon,
@"The font size of headline must be 24.");
}
- (void)testTitleFont {
// Given
// When
UIFont *font = [MDCTypography titleFont];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 20, kEpsilon, @"The font size of title must be 20.");
}
- (void)testSubheadFont {
// Given
// When
UIFont *font = [MDCTypography subheadFont];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 16, kEpsilon, @"The font size of subhead must be 16.");
}
- (void)testBody2Font {
// Given
// When
UIFont *font = [MDCTypography body2Font];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 14, kEpsilon, @"The font size of body 2 must be 14.");
}
- (void)testBody1Font {
// Given
// When
UIFont *font = [MDCTypography body1Font];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 14, kEpsilon, @"The font size of body 1 must be 14.");
}
- (void)testCaptionFont {
// Given
// When
UIFont *font = [MDCTypography captionFont];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 12, kEpsilon, @"The font size of caption must be 12.");
}
- (void)testButtonFont {
// Given
// When
UIFont *font = [MDCTypography buttonFont];
// Then
XCTAssertEqualWithAccuracy(font.pointSize, 14, kEpsilon, @"The font size of button must be 14.");
}
- (void)testFontFamilyMatchesSystemFontFamily {
// Given
NSArray<NSNumber *> *allFontStyles = @[
@(MDCFontTextStyleBody1),
@(MDCFontTextStyleBody2),
@(MDCFontTextStyleCaption),
@(MDCFontTextStyleHeadline),
@(MDCFontTextStyleSubheadline),
@(MDCFontTextStyleTitle),
@(MDCFontTextStyleDisplay1),
@(MDCFontTextStyleDisplay2),
@(MDCFontTextStyleDisplay3),
@(MDCFontTextStyleDisplay4),
@(MDCFontTextStyleButton),
];
for (NSNumber *styleObject in allFontStyles) {
// When
MDCFontTextStyle style = styleObject.integerValue;
UIFont *mdcFont = [UIFont mdc_preferredFontForMaterialTextStyle:style];
UIFont *systemFont = [UIFont systemFontOfSize:mdcFont.pointSize weight:UIFontWeightRegular];
// Then
XCTAssertEqualObjects(systemFont.familyName, mdcFont.familyName);
}
}
- (void)testExtendedDescription {
// Given
UIFont *systemFont = [UIFont systemFontOfSize:22.0 weight:UIFontWeightRegular];
XCTAssertNotNil(systemFont);
// When
NSString *fontExtendedDescription = [systemFont mdc_extendedDescription];
// Then
XCTAssertNotNil(fontExtendedDescription);
}
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "4857e71b6f931bcc8a640c4a6e59b3ee",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 100,
"avg_line_length": 28.117924528301888,
"alnum_prop": 0.7149807079349102,
"repo_name": "material-components/material-components-ios",
"id": "de3fb748674e53077153115245b75d475e366705",
"size": "5961",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "components/Typography/tests/unit/TypographyTests.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "15108"
},
{
"name": "Objective-C",
"bytes": "7907886"
},
{
"name": "Python",
"bytes": "22330"
},
{
"name": "Ruby",
"bytes": "108390"
},
{
"name": "Shell",
"bytes": "118227"
},
{
"name": "Swift",
"bytes": "896400"
}
],
"symlink_target": ""
} |
const icVector2Int icVector2Int::ZERO(0,0);
const icVector2Int icVector2Int::X_AXIS(1,0);
const icVector2Int icVector2Int::Y_AXIS(0,1);
| {
"content_hash": "7fa70fb6d657db0b125701d7e544d86a",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 45,
"avg_line_length": 34.25,
"alnum_prop": 0.781021897810219,
"repo_name": "binofet/ice",
"id": "f6147d06e1aa514046bc555c96aff9e0dc6b154e",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Engine/src/Math/Vector/icVector2Int.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "187"
},
{
"name": "C",
"bytes": "2344779"
},
{
"name": "C++",
"bytes": "5717615"
},
{
"name": "CMake",
"bytes": "12014"
},
{
"name": "HTML",
"bytes": "113099"
},
{
"name": "Objective-C",
"bytes": "174"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<!-- Document Settings -->
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- Page Meta -->
<title>Augmenting JavaScript objects with toString and valueOf</title>
<meta name="description" content="A place where I share my thoughts about programming." />
<!-- Mobile Meta -->
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Brand icon -->
<link rel="shortcut icon" href="/assets/images/favicon.ico" >
<!-- Styles'n'Scripts -->
<link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
<link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" />
<!-- highlight.js -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css">
<style>.hljs { background: none; }</style>
<!-- Ghost outputs important style and meta data with this tag -->
<link rel="canonical" href="http://blog.marcinchwedczuk.pl//augmenting-JavaScript-objects-with-toString-and-valueOf" />
<meta name="referrer" content="origin" />
<link rel="next" href="/page2/" />
<meta property="og:site_name" content="Programming is Magic" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Augmenting JavaScript objects with toString and valueOf" />
<meta property="og:description" content="A place where I share my thoughts about programming." />
<meta property="og:url" content="http://blog.marcinchwedczuk.pl//augmenting-JavaScript-objects-with-toString-and-valueOf" />
<meta property="og:image" content="/assets/images/cover7.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Augmenting JavaScript objects with toString and valueOf" />
<meta name="twitter:description" content="A place where I share my thoughts about programming." />
<meta name="twitter:url" content="http://blog.marcinchwedczuk.pl//augmenting-JavaScript-objects-with-toString-and-valueOf" />
<meta name="twitter:image:src" content="/assets/images/cover7.jpg" />
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Website",
"publisher": "Programming is Magic",
"name": "Augmenting JavaScript objects with toString and valueOf",
"url": "http://blog.marcinchwedczuk.pl//augmenting-JavaScript-objects-with-toString-and-valueOf",
"image": "/assets/images/cover7.jpg",
"description": "A place where I share my thoughts about programming."
}
</script>
<meta name="generator" content="Jekyll 3.0.0" />
<link rel="alternate" type="application/rss+xml" title="Programming is Magic" href="/feed.xml" />
</head>
<body class="home-template nav-closed">
<!-- The blog navigation links -->
<div class="nav">
<h3 class="nav-title">Menu</h3>
<a href="#" class="nav-close">
<span class="hidden">Close</span>
</a>
<ul>
<li class="nav-home " role="presentation"><a href="/">Home</a></li>
<!-- <li class="nav-about " role="presentation"><a href="/about">About</a></li> -->
<li class="nav-about " role="presentation">
<a href="/tag/java">
java (29)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: java -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/dotnet">
dotnet (11)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: dotnet -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/algorithms">
algorithms (7)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: algorithms -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/architecture">
architecture (7)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: architecture -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/scala">
scala (7)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: scala -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/javascript">
javascript (5)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: javascript -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/polish">
polish (5)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: polish -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/csharp">
csharp (4)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: csharp -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/elektronika">
elektronika (4)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: elektronika -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/hibernate">
hibernate (3)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: hibernate -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/linux">
linux (3)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: linux -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/unit-testing">
unit-testing (3)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: unit-testing -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/hardware-review">
hardware-review (2)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: hardware-review -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/cheatsheet">
cheatsheet (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: cheatsheet -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/ctf">
ctf (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: ctf -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/devcon">
devcon (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: devcon -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/eclipse">
eclipse (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: eclipse -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/electronics">
electronics (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: electronics -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/functional-programming">
functional-programming (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: functional-programming -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/git">
git (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: git -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/hacking">
hacking (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: hacking -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/hardware">
hardware (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: hardware -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/kotlin">
kotlin (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: kotlin -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/low-level">
low-level (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: low-level -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/other">
other (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: other -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/postman">
postman (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: postman -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/powershell">
powershell (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: powershell -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/regex">
regex (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: regex -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/security">
security (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: security -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/sql">
sql (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: sql -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/ssh">
ssh (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: ssh -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/tips">
tips (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: tips -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/vim">
vim (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: vim -->
</a>
</li>
<li class="nav-about " role="presentation">
<a href="/tag/windows">
windows (1)
<!-- augmenting-JavaScript-objects-with-toString-and-valueOf name: windows -->
</a>
</li>
</ul>
<a class="subscribe-button icon-feed" href="/feed.xml">Subscribe</a>
</div>
<span class="nav-cover"></span>
<div class="site-wrapper">
<!-- All the main content gets inserted here, index.hbs, post.hbs, etc -->
<!-- default -->
<!-- The comment above "< default" means - insert everything in this file into -->
<!-- the [body] of the default.hbs template, which contains our header/footer. -->
<!-- Everything inside the #post tags pulls data from the post -->
<!-- #post -->
<header class="main-header post-head " style="background-image: url(/assets/images/cover7.jpg) ">
<nav class="main-nav overlay clearfix">
<a class="blog-logo" href="/"><img src="/assets/images/home.png" alt="Blog Logo" /></a>
<a class="menu-button icon-menu" href="#"><span class="word">Menu</span></a>
</nav>
</header>
<main class="content" role="main">
<article class="post tag-test tag-content">
<header class="post-header">
<h1 class="post-title">Augmenting JavaScript objects with toString and valueOf</h1>
<section class="post-meta">
<!-- <a href='/'>mc</a> -->
<a href='/author/mc'>Marcin Chwedczuk</a>
<time class="post-date" datetime="2016-06-09">09 Jun 2016</time>
<!-- [[tags prefix=" on "]] -->
on
<a href='/tag/javascript'>Javascript</a>
</section>
</header>
<section class="post-content">
<p>Today I want to present two useful methods: <code class="highlighter-rouge">toString</code> and <code class="highlighter-rouge">valueOf</code>. Both of these methods are
used by JavaScript interpreter when converting objects to primitive types.</p>
<p>We will start with <code class="highlighter-rouge">toString</code> that can be useful for debugging purposes, say we have an object:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="kd">var</span> <span class="nx">point</span> <span class="o">=</span> <span class="p">{</span>
<span class="na">x</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span>
<span class="na">y</span><span class="p">:</span> <span class="mi">20</span>
<span class="p">};</span></code></pre></figure>
<p>When we try to convert it to <code class="highlighter-rouge">String</code> e.g. using <code class="highlighter-rouge">'' + point</code> expression, we get (in Chrome):</p>
<figure class="highlight"><pre><code class="language-no-highlight" data-lang="no-highlight">[object Object]</code></pre></figure>
<p>Wouldn’t it be nice to get <code class="highlighter-rouge">(10, 20)</code>? With support of <code class="highlighter-rouge">toString</code> we can do it, simply
let’s augment our point with <code class="highlighter-rouge">toString</code> method:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="nx">point</span><span class="p">.</span><span class="nx">toString</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="s1">'('</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">x</span> <span class="o">+</span> <span class="s1">', '</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">y</span> <span class="o">+</span> <span class="s1">')'</span><span class="p">;</span>
<span class="p">};</span></code></pre></figure>
<p>now <code class="highlighter-rouge">String(point)</code> returns:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="s2">"(10, 20)"</span></code></pre></figure>
<p>This works too when we concatenate our point with string, or when we are join’ing array of points:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="o">></span> <span class="s1">'current position: '</span> <span class="o">+</span> <span class="nx">point</span>
<span class="s2">"current position: (10, 20)"</span>
<span class="o">></span> <span class="p">[</span><span class="nx">point</span><span class="p">,</span> <span class="nx">point</span><span class="p">,</span> <span class="nx">point</span><span class="p">].</span><span class="nx">join</span><span class="p">(</span><span class="s1">'; '</span><span class="p">);</span>
<span class="s2">"(10, 20); (10, 20); (10, 20)"</span></code></pre></figure>
<p>It will also work in any other situation when object is coerced to <code class="highlighter-rouge">String</code> type. Unfortunately
it doesn’t work with <code class="highlighter-rouge">console.log</code>:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="o">></span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">point</span><span class="p">)</span>
<span class="nb">Object</span> <span class="p">{</span><span class="nl">x</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span> <span class="nx">y</span><span class="p">:</span> <span class="mi">20</span><span class="p">}</span></code></pre></figure>
<p>Now we go into interesting topic: when JavaScript objects are converted to string’s?
We already given two examples: when object is concatenated with string and when we explicitly
convert object to string via <code class="highlighter-rouge">String(obj)</code> call.
But this will also happen when we use object with operators like <code class="highlighter-rouge">></code> or <code class="highlighter-rouge">>=</code>.
Exact rules are pretty compiled and
if your are interested in them I advice reading chapter 8 (Type coercion) and 9 (Operators) from excellent
<a href="http://speakingjs.com/es5/ch08.html">Speaking JS book.</a>
For now let’s consider simple example, what will happen when we try to use <code class="highlighter-rouge">></code> on
points with <code class="highlighter-rouge">toString</code> method:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="kd">var</span> <span class="nx">Point</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">x</span> <span class="o">=</span> <span class="nx">x</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="nx">y</span> <span class="o">=</span> <span class="nx">y</span><span class="p">;</span>
<span class="p">};</span>
<span class="nx">Point</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">toString</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="s1">'('</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">x</span> <span class="o">+</span> <span class="s1">', '</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">y</span> <span class="o">+</span> <span class="s1">')'</span><span class="p">;</span>
<span class="p">};</span>
<span class="kd">var</span> <span class="nx">p1</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Point</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">p2</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Point</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">p3</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Point</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="mi">15</span><span class="p">);</span></code></pre></figure>
<p>When interpreter executes expression like <code class="highlighter-rouge">p1 > p2</code> first it tries to convert objects to
primitives - first by calling <code class="highlighter-rouge">valueOf</code> method (by default it will return <code class="highlighter-rouge">this</code>) and if
it not return primitive value then it tries <code class="highlighter-rouge">toString</code>. Since we are providing our own
version of <code class="highlighter-rouge">toString</code> that returns primitive value (a <code class="highlighter-rouge">String</code>) interpreter will use values returned
by <code class="highlighter-rouge">toString</code> to compare points, so:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="o">></span> <span class="c1">// because '(20, 30)' > '(10, 20)' - strings in JS are compared lexicographically</span>
<span class="o">></span> <span class="nx">p1</span> <span class="o">></span> <span class="nx">p2</span>
<span class="kc">false</span>
<span class="o">></span> <span class="nx">p2</span> <span class="o">></span> <span class="nx">p1</span>
<span class="kc">true</span>
<span class="o">></span> <span class="c1">// because '(20, 30)' > '(20, 15)':</span>
<span class="o">></span> <span class="nx">p2</span> <span class="o">></span> <span class="nx">p3</span>
<span class="kc">true</span></code></pre></figure>
<p>Looks like we overloaded <code class="highlighter-rouge">></code> operator in JavaScript, yay! But we must be aware of limitations of
this technique: first we are comparing strings not object properties, second string in JS are compared
lexicographically so <code class="highlighter-rouge">'2' > '111'</code>. In other words don’t use it in production code it may cause
too much confusion, explicit method like
<code class="highlighter-rouge">Point.compare</code> would be much better.</p>
<p>Now we can turn to <code class="highlighter-rouge">valueOf</code> method, in it’s working it is similar to <code class="highlighter-rouge">toString</code> method, only difference
is that it is called when object must be converted to <code class="highlighter-rouge">Number</code>.
Let’s see quick example:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="kd">var</span> <span class="nx">obj</span> <span class="o">=</span> <span class="p">{</span>
<span class="na">valueOf</span><span class="p">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="mi">42</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">};</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nb">Number</span><span class="p">(</span><span class="nx">obj</span><span class="p">));</span> <span class="c1">// prints 42</span></code></pre></figure>
<p>Object is converted to number when used with operators like: <code class="highlighter-rouge">+</code>, <code class="highlighter-rouge">*</code> and <code class="highlighter-rouge">-</code>. Also <code class="highlighter-rouge">valueOf</code> is used
when objects are compared using <code class="highlighter-rouge">></code> or <code class="highlighter-rouge">>=</code> operators. <code class="highlighter-rouge">valueOf</code> is not as useful as <code class="highlighter-rouge">toString</code> IMHO,
but it’s worth to know. One more fact is that <code class="highlighter-rouge">Date</code> objects have custom implementation of <code class="highlighter-rouge">valueOf</code> method
that returns number of milliseconds from epoch (in other words it returns same value as <code class="highlighter-rouge">getTime()</code>). Thanks
to this we can use <code class="highlighter-rouge">></code> to compare dates, and get difference in milliseconds between dates as: <code class="highlighter-rouge">date2 - date1</code>.</p>
</section>
<footer class="post-footer">
<!-- Everything inside the #author tags pulls data from the author -->
<!-- #author-->
<figure class="author-image">
<a class="img" href="/author/mc" style="background-image: url(/assets/images/mc.png)"><span class="hidden">mc's Picture</span></a>
</figure>
<section class="author">
<h4><a href="/author/mc">Marcin Chwedczuk</a></h4>
<p> A programmer, a geek, a human</p>
<div class="author-meta">
<span class="author-location icon-location"> Warsaw, Poland</span>
<span class="author-link icon-link"><a href="http://marcinchwedczuk.pl"> http://marcinchwedczuk.pl</a></span>
</div>
</section>
<!-- /author -->
<section class="share">
<h4>Share this post</h4>
<a class="icon-twitter" href="http://twitter.com/share?text=Augmenting JavaScript objects with toString and valueOf&url=http://blog.marcinchwedczuk.plaugmenting-JavaScript-objects-with-toString-and-valueOf"
onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;">
<span class="hidden">Twitter</span>
</a>
<a class="icon-facebook" href="https://www.facebook.com/sharer/sharer.php?u=http://blog.marcinchwedczuk.plaugmenting-JavaScript-objects-with-toString-and-valueOf"
onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;">
<span class="hidden">Facebook</span>
</a>
<a class="icon-google-plus" href="https://plus.google.com/share?url=http://blog.marcinchwedczuk.plaugmenting-JavaScript-objects-with-toString-and-valueOf"
onclick="window.open(this.href, 'google-plus-share', 'width=490,height=530');return false;">
<span class="hidden">Google+</span>
</a>
</section>
<!-- Add Disqus Comments -->
</footer>
</article>
</main>
<aside class="read-next">
<!-- [[! next_post ]] -->
<a class="read-next-story " style="background-image: url(/assets/images/cover2.jpg)" href="/object-and-collection-initializers-in-csharp">
<section class="post">
<h2>Object and collection initializers in C#</h2>
<p>In this post I want to present a nice C# syntax sugar: object and collection...</p>
</section>
</a>
<!-- [[! /next_post ]] -->
<!-- [[! prev_post ]] -->
<a class="read-next-story prev " style="background-image: url(/assets/images/cover7.jpg)" href="/creating-and-using-adnotations-in-java">
<section class="post">
<h2>Creating and using annotations in Java</h2>
<p>Java annotations are simple data that we can attach to program elements like classes, fields...</p>
</section>
</a>
<!-- [[! /prev_post ]] -->
</aside>
<!-- /post -->
<!-- The tiny footer at the very bottom -->
<footer class="site-footer clearfix">
<section class="copyright"><a href="/">Programming is Magic</a> © 2021</section>
<section class="poweredby">Proudly published with <a href="https://jekyllrb.com/">Jekyll</a> using <a href="https://github.com/jekyller/jasper">Jasper</a></section>
</footer>
</div>
<!-- highlight.js -->
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<!-- jQuery needs to come before `` so that jQuery can be used in code injection -->
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- Ghost outputs important scripts and data with this tag -->
<!-- -->
<!-- Add Google Analytics -->
<!-- Google Analytics Tracking code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-82096342-1', 'auto');
ga('send', 'pageview');
</script>
<!-- Fitvids makes video embeds responsive and awesome -->
<script type="text/javascript" src="/assets/js/jquery.fitvids.js"></script>
<!-- The main JavaScript file for Casper -->
<script type="text/javascript" src="/assets/js/index.js"></script>
</body>
</html>
| {
"content_hash": "6b28ba75ec18dd408dc560980db12789",
"timestamp": "",
"source": "github",
"line_count": 658,
"max_line_length": 396,
"avg_line_length": 47.785714285714285,
"alnum_prop": 0.5479757020640524,
"repo_name": "marcin-chwedczuk/marcin-chwedczuk.github.io",
"id": "a45ccdfa6917769daf9be3ba55d8b27843149bce",
"size": "31463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "augmenting-JavaScript-objects-with-toString-and-valueOf.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50689"
},
{
"name": "HTML",
"bytes": "4176352"
},
{
"name": "JavaScript",
"bytes": "16468"
},
{
"name": "Shell",
"bytes": "594"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WorkflowCore.Persistence.Sqlite")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("86bc1e05-e9ce-4e53-b324-885a2fdbce74")]
| {
"content_hash": "bb6bb314c572f24b1a5e4791f0196086",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 84,
"avg_line_length": 44.55555555555556,
"alnum_prop": 0.7805486284289277,
"repo_name": "danielgerlag/workflow-core",
"id": "04f04aacc44ff8d83aba3666c211131fa510bef7",
"size": "804",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/providers/WorkflowCore.Persistence.Sqlite/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1108519"
},
{
"name": "Dockerfile",
"bytes": "507"
},
{
"name": "TSQL",
"bytes": "634"
}
],
"symlink_target": ""
} |
Ti=Statutory Rights
sec=Nothing in this Agreement affects any statutory rights granted or terms required, in either case, by mandatory statutory law that cannot be waived or limited by contract. If there is a conflict between the terms and conditions of this Agreement and mandatory statutory law, mandatory statutory law will prevail.
=[G/Z/ol/Base]
| {
"content_hash": "6421415b3cd8561f8683a581db100425",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 315,
"avg_line_length": 70.6,
"alnum_prop": 0.8101983002832861,
"repo_name": "CommonAccord/Cmacc-Org",
"id": "05bbc6835f804483ae790eed5f6b09aabc985f95",
"size": "353",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Doc/F/US/00/Agt/Service/MSA/ABA/Sec/General/Statute/0.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4996"
},
{
"name": "HTML",
"bytes": "130299"
},
{
"name": "PHP",
"bytes": "1463"
}
],
"symlink_target": ""
} |
#ifndef __MANROLAND_COMMON_H
#define __MANROLAND_COMMON_H
/*
* High Level Configuration Options
* (easy to change)
*/
#define CONFIG_BOARD_EARLY_INIT_R
/* Partitions */
#define CONFIG_DOS_PARTITION
/*
* Command line configuration.
*/
#define CONFIG_CMD_DATE
#define CONFIG_CMD_DISPLAY
#define CONFIG_CMD_DHCP
#define CONFIG_CMD_PING
#define CONFIG_CMD_EEPROM
#define CONFIG_CMD_I2C
#define CONFIG_CMD_DTT
#define CONFIG_CMD_IDE
#define CONFIG_CMD_FAT
#define CONFIG_CMD_MII
#define CONFIG_CMD_SNTP
/*
* 8-symbol LED display (can be accessed with 'display' command)
*/
#define CONFIG_PDSP188x
#define CONFIG_TIMESTAMP 1 /* Print image info with timestamp */
/*
* Autobooting
*/
#define CONFIG_BOOTDELAY 5 /* autoboot after 5 seconds */
#define CONFIG_PREBOOT "echo;" \
"echo Type \\\"run flash_nfs\\\" to mount root filesystem over NFS;" \
"echo"
#undef CONFIG_BOOTARGS
#define CONFIG_EXTRA_ENV_SETTINGS \
"netdev=eth0\0" \
"nfsargs=setenv bootargs root=/dev/nfs rw " \
"nfsroot=${serverip}:${rootpath}\0" \
"ramargs=setenv bootargs root=/dev/ram rw\0" \
"addwdt=setenv bootargs ${bootargs} wdt=off\0" \
"logval=4\0" \
"addlog=setenv bootargs ${bootargs} loglevel=${logval}\0" \
"addip=setenv bootargs ${bootargs} " \
"ip=${ipaddr}:${serverip}:${gatewayip}:${netmask}" \
":${hostname}:${netdev}:off panic=1\0" \
"kernel_addr=ff810000\0" \
"fdt_addr="__stringify(CONFIG_SYS_FLASH_BASE)"\0" \
"flash_nfs=run nfsargs addip addcon addwdt addlog;" \
"bootm ${kernel_addr} - ${fdt_addr}\0" \
"rootpath=/opt/eldk/ppc_82xx\0" \
"kernel_addr_r=300000\0" \
"fdt_addr_r=200000\0" \
"fdt_file=" __stringify(CONFIG_HOSTNAME) "/" \
__stringify(CONFIG_HOSTNAME) ".dtb\0" \
"kernel_file=" __stringify(CONFIG_HOSTNAME) "/uImage \0" \
"load_fdt=tftp ${fdt_addr_r} ${fdt_file};\0" \
"load_kernel=tftp ${kernel_addr_r} ${kernel_file};\0" \
"addcon=setenv bootargs ${bootargs} console=ttyPSC0,${baudrate}\0"\
"net_nfs=run load_fdt load_kernel; " \
"run nfsargs addip addcon addwdt addlog;" \
"bootm ${kernel_addr_r} - ${fdt_addr_r}\0" \
"u-boot=" __stringify(CONFIG_HOSTNAME) "/u-boot.bin \0" \
"u-boot_addr_r=200000\0" \
"load=tftp ${u-boot_addr_r} ${u-boot}\0" \
"update=protect off " __stringify(CONFIG_SYS_TEXT_BASE) " +${filesize};"\
"erase " __stringify(CONFIG_SYS_TEXT_BASE) " +${filesize};"\
"cp.b ${u-boot_addr_r} " __stringify(CONFIG_SYS_TEXT_BASE) \
" ${filesize};" \
"protect on " __stringify(CONFIG_SYS_TEXT_BASE) " +${filesize}\0"\
""
#define CONFIG_BOOTCOMMAND "run net_nfs"
#define CONFIG_MISC_INIT_R 1
/*
* Miscellaneous configurable options
*/
#define CONFIG_SYS_LONGHELP /* undef to save memory */
#if defined(CONFIG_CMD_KGDB)
#define CONFIG_SYS_CBSIZE 1024 /* Console I/O Buffer Size */
#else
#define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */
#endif
#define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE+sizeof(CONFIG_SYS_PROMPT)+16)
#define CONFIG_SYS_MAXARGS 16 /* max number of command args*/
#define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE
#define CONFIG_CMDLINE_EDITING 1 /* add command line history */
#define CONFIG_AUTO_COMPLETE /* add autocompletion support */
/* Enable an alternate, more extensive memory test */
#define CONFIG_SYS_ALT_MEMTEST
/*
* Enable loopw command.
*/
#define CONFIG_LOOPW
/* pass open firmware flat tree */
#define CONFIG_OF_LIBFDT 1
#define CONFIG_OF_BOARD_SETUP 1
#endif /* __MANROLAND_COMMON_H */
| {
"content_hash": "92505f1d7f1485a7de6428d3c077eba0",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 74,
"avg_line_length": 29.931623931623932,
"alnum_prop": 0.6690462592804112,
"repo_name": "guileschool/BEAGLEBONE-tutorials",
"id": "941290c776e50ac66bb3e25f4ca2e9c2e830bbd9",
"size": "3628",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "BBB-firmware/u-boot-v2015.10-rc2/include/configs/manroland/common.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3031801"
},
{
"name": "Awk",
"bytes": "679"
},
{
"name": "Batchfile",
"bytes": "451009"
},
{
"name": "C",
"bytes": "187049589"
},
{
"name": "C#",
"bytes": "2330"
},
{
"name": "C++",
"bytes": "9495850"
},
{
"name": "CSS",
"bytes": "3499"
},
{
"name": "GDB",
"bytes": "7284"
},
{
"name": "Lex",
"bytes": "27285"
},
{
"name": "Makefile",
"bytes": "1485717"
},
{
"name": "Objective-C",
"bytes": "1073082"
},
{
"name": "Perl",
"bytes": "679475"
},
{
"name": "Prolog",
"bytes": "258849"
},
{
"name": "Python",
"bytes": "1962938"
},
{
"name": "Roff",
"bytes": "24714"
},
{
"name": "Shell",
"bytes": "319726"
},
{
"name": "Tcl",
"bytes": "1934"
},
{
"name": "XSLT",
"bytes": "1335"
},
{
"name": "Yacc",
"bytes": "56953"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$lang['ut_test_name'] = 'Test Name';
$lang['ut_test_datatype'] = 'Test Datatype';
$lang['ut_res_datatype'] = 'Expected Datatype';
$lang['ut_result'] = 'Result';
$lang['ut_undefined'] = 'Undefined Test Name';
$lang['ut_file'] = 'File Name';
$lang['ut_line'] = 'Line Number';
$lang['ut_passed'] = 'Passed';
$lang['ut_failed'] = 'Failed';
$lang['ut_boolean'] = 'Boolean';
$lang['ut_integer'] = 'Integer';
$lang['ut_float'] = 'Float';
$lang['ut_double'] = 'Float'; // can be the same as float
$lang['ut_string'] = 'String';
$lang['ut_array'] = 'Array';
$lang['ut_object'] = 'Object';
$lang['ut_resource'] = 'Resource';
$lang['ut_null'] = 'Null';
$lang['ut_notes'] = 'Notes';
| {
"content_hash": "955b40280aed75fd8b3e3dbed098a378",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 63,
"avg_line_length": 32.30434782608695,
"alnum_prop": 0.6137281292059219,
"repo_name": "lewnelin/webgalleries",
"id": "54e35e69d046646c3b4fa5386a9bf075685c17d3",
"size": "2405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "system/language/english/unit_test_lang.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "17124"
},
{
"name": "HTML",
"bytes": "8517138"
},
{
"name": "JavaScript",
"bytes": "61399"
},
{
"name": "PHP",
"bytes": "1758243"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AndroidLayouts">
<shared>
<config>
<target>android-23</target>
</config>
</shared>
</component>
<component name="AndroidLogFilters">
<option name="TOOL_WINDOW_CONFIGURED_FILTER" value="Show only selected application" />
</component>
<component name="ChangeListManager">
<list default="true" id="7705c121-d031-4aea-aaf7-fe1d9a8e04ab" name="Default" comment="">
<change afterPath="$PROJECT_DIR$/.idea/libraries/Gradle__com_android_support_support_v4_23_4_0_aar.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../.idea/encodings.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../.idea/misc.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../.idea/modules.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../.idea/vcs.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/gradle.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/gradle.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/libraries/Gradle__com_android_support_support_annotations_23_4_0_jar.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/libraries/Gradle__com_android_support_support_annotations_23_4_0_jar.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/build.gradle" beforeDir="false" afterPath="$PROJECT_DIR$/app/build.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/ParseHandler.java" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/ParseHandler.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/build.gradle" beforeDir="false" afterPath="$PROJECT_DIR$/build.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.properties" beforeDir="false" afterPath="$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.properties" afterDir="false" />
</list>
<ignored path="WeatherForecast-SAX+SQLite+ListView.iws" />
<ignored path=".idea/workspace.xml" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="ExternalProjectsData">
<projectState path="$PROJECT_DIR$">
<ProjectState />
</projectState>
</component>
<component name="ExternalProjectsManager">
<system id="GRADLE">
<state>
<projects_view />
</state>
</system>
</component>
<component name="FavoritesManager">
<favorites_list name="WeatherForecast-SAX+SQLite+ListView" />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/src/main/res/layout/activity_main.xml">
<provider selected="true" editor-type-id="text-editor" />
<provider editor-type-id="android-designer2" />
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/src/main/res/values-v14/styles.xml">
<provider selected="true" editor-type-id="text-editor" />
</entry>
</file>
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/MainActivity.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-735">
<caret line="3" selection-start-line="3" selection-end-line="3" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/ParseHandler.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="209">
<caret line="11" column="66" selection-start-line="11" selection-start-column="66" selection-end-line="11" selection-end-column="66" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.properties">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="95">
<caret line="5" selection-start-line="5" selection-end-line="5" selection-end-column="79" />
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/src/main/res/layout/listview_items.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="76">
<caret line="4" column="33" selection-start-line="4" selection-start-column="33" selection-end-line="4" selection-end-column="33" />
</state>
</provider>
<provider editor-type-id="android-designer2" />
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/Dal.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="621">
<caret line="96" column="24" selection-start-line="96" selection-start-column="24" selection-end-line="96" selection-end-column="24" />
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/build.gradle">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="95">
<caret line="5" selection-start-line="5" selection-end-line="5" />
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherSQLiteHelper.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="627">
<caret line="36" column="26" selection-start-line="36" selection-start-column="26" selection-end-line="36" selection-end-column="26" />
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/build.gradle">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="19">
<caret line="1" selection-start-line="1" selection-end-line="17" />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FindInProjectRecents">
<findStrings>
<find>Desciption</find>
</findStrings>
<dirStrings>
<dir>$PROJECT_DIR$/app/src/main/java</dir>
</dirStrings>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherItem.java" />
<option value="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherItems.java" />
<option value="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherSQLiteHelper.java" />
<option value="$PROJECT_DIR$/app/build.gradle" />
<option value="$PROJECT_DIR$/app/src/main/AndroidManifest.xml" />
<option value="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/Dal.java" />
<option value="$PROJECT_DIR$/README.md" />
<option value="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/MainActivity.java" />
<option value="$PROJECT_DIR$/app/src/main/res/layout/listview_items.xml" />
<option value="$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/ParseHandler.java" />
<option value="$PROJECT_DIR$/build.gradle" />
</list>
</option>
</component>
<component name="ProjectFrameBounds" extendedState="6">
<option name="y" value="23" />
<option name="width" value="1920" />
<option name="height" value="997" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectView">
<navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="ProjectPane" />
<pane id="PackagesPane" />
<pane id="AndroidView">
<subPane>
<expand>
<path>
<item name="WeatherForecast-SAX+SQLite+ListView" type="1abcf292:AndroidViewProjectNode" />
<item name="app" type="feadf853:AndroidModuleNode" />
</path>
<path>
<item name="WeatherForecast-SAX+SQLite+ListView" type="1abcf292:AndroidViewProjectNode" />
<item name="app" type="feadf853:AndroidModuleNode" />
<item name="java" type="edd41e36:AndroidSourceTypeNode" />
</path>
<path>
<item name="WeatherForecast-SAX+SQLite+ListView" type="1abcf292:AndroidViewProjectNode" />
<item name="app" type="feadf853:AndroidModuleNode" />
<item name="java" type="edd41e36:AndroidSourceTypeNode" />
<item name="weatherdemo" type="cbb59c9e:AndroidPsiDirectoryNode" />
</path>
<path>
<item name="WeatherForecast-SAX+SQLite+ListView" type="1abcf292:AndroidViewProjectNode" />
<item name="app" type="feadf853:AndroidModuleNode" />
<item name="assets" type="edd41e36:AndroidSourceTypeNode" />
</path>
<path>
<item name="WeatherForecast-SAX+SQLite+ListView" type="1abcf292:AndroidViewProjectNode" />
<item name="app" type="feadf853:AndroidModuleNode" />
<item name="res" type="d4f16f75:AndroidResFolderNode" />
</path>
<path>
<item name="WeatherForecast-SAX+SQLite+ListView" type="1abcf292:AndroidViewProjectNode" />
<item name="app" type="feadf853:AndroidModuleNode" />
<item name="res" type="d4f16f75:AndroidResFolderNode" />
<item name="drawable" type="ddeffd01:AndroidResFolderTypeNode" />
</path>
<path>
<item name="WeatherForecast-SAX+SQLite+ListView" type="1abcf292:AndroidViewProjectNode" />
<item name="Gradle Scripts" type="ae0cef3a:AndroidBuildScriptsGroupNode" />
</path>
</expand>
<select />
</subPane>
</pane>
<pane id="Scope">
<subPane subId="Project Files">
<expand>
<path>
<item name="Root" type="cbb8eebc:String" user="Root" />
<item name="app" type="cbb8eebc:String" user="app" />
</path>
<path>
<item name="Root" type="cbb8eebc:String" user="Root" />
<item name="app" type="cbb8eebc:String" user="app" />
<item name="app" type="cbb8eebc:String" user="app" />
</path>
<path>
<item name="Root" type="cbb8eebc:String" user="Root" />
<item name="app" type="cbb8eebc:String" user="app" />
<item name="app" type="cbb8eebc:String" user="app" />
<item name="src/main" type="cbb8eebc:String" user="src/main" />
</path>
<path>
<item name="Root" type="cbb8eebc:String" user="Root" />
<item name="app" type="cbb8eebc:String" user="app" />
<item name="app" type="cbb8eebc:String" user="app" />
<item name="src/main" type="cbb8eebc:String" user="src/main" />
<item name="java" type="cbb8eebc:String" user="java" />
</path>
<path>
<item name="Root" type="cbb8eebc:String" user="Root" />
<item name="WeatherForecast-SAX+SQLite+ListView" type="cbb8eebc:String" user="WeatherForecast-SAX+SQLite+ListView" />
</path>
<path>
<item name="Root" type="cbb8eebc:String" user="Root" />
<item name="WeatherForecast-SAX+SQLite+ListView" type="cbb8eebc:String" user="WeatherForecast-SAX+SQLite+ListView" />
<item name="WeatherForecast-SAX+SQLite+ListView" type="cbb8eebc:String" user="WeatherForecast-SAX+SQLite+ListView" />
</path>
</expand>
<select />
</subPane>
</pane>
</panes>
</component>
<component name="PropertiesComponent">
<property name="SearchEverywhereHistoryKey" value="device	ACTION	ActivateDeviceFileExplorerToolWindow" />
<property name="android.project.structure.last.selected" value="SDK Location" />
<property name="android.project.structure.proportion" value="0.15" />
<property name="android.sdk.path" value="$USER_HOME$/Library/Developer/Xamarin/android-sdk-macosx" />
<property name="device.picker.selection" value="Pixel_2_API_26" />
<property name="full.screen.before.presentation.mode" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/../WeatherForecast-SAX+ListView" />
<property name="settings.editor.selected.configurable" value="android.sdk-updates" />
<property name="settings.editor.splitter.proportion" value="0.2" />
<property name="show.migrate.to.gradle.popup" value="false" />
</component>
<component name="RecentsManager">
<key name="IntroduceConstantDialog.RECENTS_KEY">
<recent name="edu.uoregon.bbird.weatherdemo.WeatherSQLiteHelper" />
<recent name="edu.uoregon.bbird.weatherdemo.MainActivity" />
</key>
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager" selected="Android App.app">
<configuration default="true" type="AndroidRunConfigurationType" factoryName="Android Application">
<module name="" />
<option name="DEPLOY" value="true" />
<option name="ARTIFACT_NAME" value="" />
<option name="PM_INSTALL_OPTIONS" value="" />
<option name="ACTIVITY_EXTRA_FLAGS" value="" />
<option name="MODE" value="default_activity" />
<option name="TARGET_SELECTION_MODE" value="SHOW_DIALOG" />
<option name="PREFERRED_AVD" value="" />
<option name="CLEAR_LOGCAT" value="false" />
<option name="SHOW_LOGCAT_AUTOMATICALLY" value="true" />
<option name="SKIP_NOOP_APK_INSTALLATIONS" value="true" />
<option name="FORCE_STOP_RUNNING_APP" value="true" />
<option name="DEBUGGER_TYPE" value="Auto" />
<option name="USE_LAST_SELECTED_DEVICE" value="false" />
<option name="PREFERRED_AVD" value="" />
<option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="-1" />
<option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" />
<Hybrid>
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
</Hybrid>
<Native>
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
</Native>
<Java />
<Profilers>
<option name="GAPID_DISABLE_PCS" value="false" />
</Profilers>
<option name="DEEP_LINK" value="" />
<option name="ACTIVITY_CLASS" value="" />
<method />
</configuration>
<configuration name="<template>" type="Applet" default="true" selected="false">
<option name="MAIN_CLASS_NAME" />
<option name="HTML_FILE_NAME" />
<option name="HTML_USED" value="false" />
<option name="WIDTH" value="400" />
<option name="HEIGHT" value="300" />
<option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" />
<option name="VM_PARAMETERS" />
</configuration>
<configuration default="true" type="TestNGTestDiscovery" factoryName="TestNG Test Discovery" changeList="All">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<module name="" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="SUITE_NAME" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="GROUP_NAME" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="VM_PARAMETERS" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" />
<option name="OUTPUT_DIRECTORY" />
<option name="ANNOTATION_TYPE" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<option name="USE_DEFAULT_REPORTERS" value="false" />
<option name="PROPERTIES_FILE" />
<envs />
<properties />
<listeners />
<method />
</configuration>
<configuration name="<template>" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType" default="true" selected="false">
<option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -XX:MaxPermSize=250m -ea" />
</configuration>
<configuration default="true" type="AndroidJUnit" factoryName="Android JUnit">
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$MODULE_DIR$" />
<method v="2">
<option name="Android.Gradle.BeforeRunTask" enabled="true" />
</method>
</configuration>
<configuration name="app" type="AndroidRunConfigurationType" factoryName="Android App" activateToolWindowBeforeRun="false">
<module name="app" />
<option name="DEPLOY" value="true" />
<option name="DEPLOY_APK_FROM_BUNDLE" value="false" />
<option name="DEPLOY_AS_INSTANT" value="false" />
<option name="ARTIFACT_NAME" value="" />
<option name="PM_INSTALL_OPTIONS" value="" />
<option name="DYNAMIC_FEATURES_DISABLED_LIST" value="" />
<option name="ACTIVITY_EXTRA_FLAGS" value="" />
<option name="MODE" value="default_activity" />
<option name="CLEAR_LOGCAT" value="false" />
<option name="SHOW_LOGCAT_AUTOMATICALLY" value="false" />
<option name="SKIP_NOOP_APK_INSTALLATIONS" value="true" />
<option name="FORCE_STOP_RUNNING_APP" value="true" />
<option name="TARGET_SELECTION_MODE" value="SHOW_DIALOG" />
<option name="USE_LAST_SELECTED_DEVICE" value="false" />
<option name="PREFERRED_AVD" value="" />
<option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="-1" />
<option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" />
<option name="DEBUGGER_TYPE" value="Auto" />
<Auto>
<option name="USE_JAVA_AWARE_DEBUGGER" value="false" />
<option name="SHOW_STATIC_VARS" value="true" />
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
<option name="SHOW_OPTIMIZED_WARNING" value="true" />
</Auto>
<Hybrid>
<option name="USE_JAVA_AWARE_DEBUGGER" value="false" />
<option name="SHOW_STATIC_VARS" value="true" />
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
<option name="SHOW_OPTIMIZED_WARNING" value="true" />
</Hybrid>
<Java />
<Native>
<option name="USE_JAVA_AWARE_DEBUGGER" value="false" />
<option name="SHOW_STATIC_VARS" value="true" />
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
<option name="SHOW_OPTIMIZED_WARNING" value="true" />
</Native>
<Profilers>
<option name="ADVANCED_PROFILING_ENABLED" value="false" />
<option name="STARTUP_CPU_PROFILING_ENABLED" value="false" />
<option name="STARTUP_CPU_PROFILING_CONFIGURATION_NAME" value="Sample Java Methods" />
</Profilers>
<option name="DEEP_LINK" value="" />
<option name="ACTIVITY_CLASS" value="" />
<method v="2">
<option name="Android.Gradle.BeforeRunTask" enabled="true" />
</method>
</configuration>
<configuration default="false" name="app" type="AndroidRunConfigurationType" factoryName="Android Application" activateToolWindowBeforeRun="false">
<module name="app" />
<option name="DEPLOY" value="true" />
<option name="ARTIFACT_NAME" value="" />
<option name="PM_INSTALL_OPTIONS" value="" />
<option name="ACTIVITY_EXTRA_FLAGS" value="" />
<option name="MODE" value="default_activity" />
<option name="TARGET_SELECTION_MODE" value="SHOW_DIALOG" />
<option name="PREFERRED_AVD" value="" />
<option name="CLEAR_LOGCAT" value="false" />
<option name="SHOW_LOGCAT_AUTOMATICALLY" value="true" />
<option name="SKIP_NOOP_APK_INSTALLATIONS" value="true" />
<option name="FORCE_STOP_RUNNING_APP" value="true" />
<option name="DEBUGGER_TYPE" value="Java" />
<option name="USE_LAST_SELECTED_DEVICE" value="false" />
<option name="PREFERRED_AVD" value="" />
<option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="-1" />
<option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" />
<Hybrid>
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
</Hybrid>
<Native>
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
</Native>
<Java />
<Profilers>
<option name="GAPID_DISABLE_PCS" value="false" />
</Profilers>
<option name="DEEP_LINK" value="" />
<option name="ACTIVITY_CLASS" value="" />
<method />
</configuration>
<configuration default="true" type="Application" factoryName="Application">
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration default="true" type="TestNG">
<option name="TEST_OBJECT" value="CLASS" />
<option name="WORKING_DIRECTORY" value="$MODULE_DIR$" />
<properties />
<listeners />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<list>
<item itemvalue="Android App.app" />
</list>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="7705c121-d031-4aea-aaf7-fe1d9a8e04ab" name="Default" comment="" />
<created>1468010976612</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1468010976612</updated>
</task>
<servers />
</component>
<component name="ToolWindowManager">
<frame x="0" y="23" width="1280" height="721" extended-state="6" />
<layout>
<window_info active="true" id="Project" order="0" visible="true" weight="0.27850163" />
<window_info id="Structure" order="1" weight="0.25" />
<window_info id="Captures" order="2" side_tool="true" weight="0.25" />
<window_info id="Build Variants" order="3" side_tool="true" />
<window_info id="Capture Tool" order="4" />
<window_info id="Favorites" order="5" side_tool="true" />
<window_info id="Palette	" order="6" />
<window_info id="Image Layers" order="7" />
<window_info id="Resources Explorer" order="8" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" weight="0.32672113" />
<window_info anchor="bottom" id="Run" order="2" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.272" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="bottom" id="Build" order="7" weight="0.32905483" />
<window_info anchor="bottom" id="Android Profiler" order="8" />
<window_info anchor="bottom" id="Event Log" order="9" side_tool="true" />
<window_info anchor="bottom" id="Logcat" order="10" />
<window_info anchor="bottom" id="Android Monitor" order="11" weight="0.3287841" />
<window_info anchor="bottom" id="Version Control" order="12" />
<window_info anchor="bottom" id="Terminal" order="13" />
<window_info anchor="bottom" id="Gradle Console" order="14" side_tool="true" />
<window_info anchor="bottom" id="Messages" order="15" weight="0.32760897" />
<window_info anchor="bottom" id="Flutter Performance" order="16" side_tool="true" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="right" id="Device File Explorer" order="3" side_tool="true" weight="0.29321486" />
<window_info anchor="right" id="Android Model" order="4" side_tool="true" />
<window_info anchor="right" id="Gradle" order="5" />
<window_info anchor="right" id="Designer" order="6" />
<window_info anchor="right" id="Theme Preview" order="7" />
<window_info anchor="right" id="Preview" order="8" />
<window_info anchor="right" id="Capture Analysis" order="9" />
<window_info anchor="right" id="Flutter Inspector" order="10" />
<window_info anchor="right" id="Flutter Outline" order="11" />
</layout>
<layout-to-restore>
<window_info id="Project" order="0" visible="true" weight="0.21530758" />
<window_info id="Structure" order="1" weight="0.25" />
<window_info id="Captures" order="2" weight="0.25" />
<window_info id="Build Variants" order="3" side_tool="true" />
<window_info id="Capture Tool" order="4" />
<window_info id="Favorites" order="5" side_tool="true" />
<window_info id="Palette	" order="6" />
<window_info id="Image Layers" order="7" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" visible="true" weight="0.32893" />
<window_info anchor="bottom" id="Run" order="2" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.5006605" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="bottom" id="Event Log" order="7" side_tool="true" />
<window_info anchor="bottom" id="Android Monitor" order="8" weight="0.3287841" />
<window_info anchor="bottom" id="Version Control" order="9" />
<window_info anchor="bottom" id="Terminal" order="10" />
<window_info anchor="bottom" id="Gradle Console" order="11" side_tool="true" />
<window_info anchor="bottom" id="Messages" order="12" weight="0.32760897" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="right" id="Android Model" order="3" side_tool="true" />
<window_info anchor="right" id="Gradle" order="4" />
<window_info anchor="right" id="Designer" order="5" />
<window_info anchor="right" id="Theme Preview" order="6" />
<window_info anchor="right" id="Preview" order="7" />
<window_info anchor="right" id="Capture Analysis" order="8" />
</layout-to-restore>
</component>
<component name="Vcs.Log.UiProperties">
<option name="RECENTLY_FILTERED_USER_GROUPS">
<collection />
</option>
<option name="RECENTLY_FILTERED_BRANCH_GROUPS">
<collection />
</option>
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<breakpoints>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherSQLiteHelper.java</url>
<line>34</line>
<properties />
<option name="timeStamp" value="26" />
</line-breakpoint>
</breakpoints>
</breakpoint-manager>
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherItems.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="38">
<caret line="2" selection-start-line="2" selection-end-line="2" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/assets/weather97439.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="209">
<caret line="11" column="43" selection-start-line="11" selection-start-column="33" selection-end-line="11" selection-end-column="43" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherItem.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="323">
<caret line="21" column="51" selection-start-line="21" selection-start-column="30" selection-end-line="21" selection-end-column="51" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/Library/Developer/Xamarin/android-sdk-macosx/sources/android-23/android/app/ActivityThread.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="42484">
<caret line="2414" selection-start-line="2414" selection-end-line="2414" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/README.md">
<provider selected="true" editor-type-id="split-provider[text-editor;markdown-preview-editor]">
<state split_layout="SPLIT">
<first_editor>
<folding />
</first_editor>
<second_editor />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/assets/weather97405.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="19">
<caret line="1" column="152" selection-start-line="1" selection-start-column="122" selection-end-line="1" selection-end-column="152" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/AndroidManifest.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="437">
<caret line="23" selection-start-line="23" selection-end-line="23" />
</state>
</provider>
<provider editor-type-id="android-manifest" />
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/res/values-v11/styles.xml">
<provider selected="true" editor-type-id="text-editor">
<state>
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/res/values/styles.xml">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/res/layout/activity_main.xml">
<provider selected="true" editor-type-id="text-editor" />
<provider editor-type-id="android-designer2" />
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/res/values-v14/styles.xml">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/res/layout/listview_items.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="76">
<caret line="4" column="33" selection-start-line="4" selection-start-column="33" selection-end-line="4" selection-end-column="33" />
</state>
</provider>
<provider editor-type-id="android-designer2" />
</entry>
<entry file="file://$PROJECT_DIR$/app/build.gradle">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="95">
<caret line="5" selection-start-line="5" selection-end-line="5" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/ParseHandler.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="209">
<caret line="11" column="66" selection-start-line="11" selection-start-column="66" selection-end-line="11" selection-end-column="66" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.properties">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="95">
<caret line="5" selection-start-line="5" selection-end-line="5" selection-end-column="79" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/build.gradle">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="19">
<caret line="1" selection-start-line="1" selection-end-line="17" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/WeatherSQLiteHelper.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="627">
<caret line="36" column="26" selection-start-line="36" selection-start-column="26" selection-end-line="36" selection-end-column="26" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/Dal.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="621">
<caret line="96" column="24" selection-start-line="96" selection-start-column="24" selection-end-line="96" selection-end-column="24" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/src/main/java/edu/uoregon/bbird/weatherdemo/MainActivity.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-735">
<caret line="3" selection-start-line="3" selection-end-line="3" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
</component>
</project> | {
"content_hash": "b4133b56875559e7317fa961ff75ef93",
"timestamp": "",
"source": "github",
"line_count": 736,
"max_line_length": 262,
"avg_line_length": 50.30434782608695,
"alnum_prop": 0.6210296024200519,
"repo_name": "UO-CIS/CIS399AndroidDemos",
"id": "4b31f59c40778586bbd31b4faa547cc96c0ba72f",
"size": "37024",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WeatherForecast-SAX+SQLite+ListView/.idea/workspace.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "140880"
}
],
"symlink_target": ""
} |
package org.apache.batik.svggen.font;
/**
* @version $Id$
* @author <a href="mailto:david@steadystate.co.uk">David Schweinsberg</a>
*/
public class Point {
public int x = 0;
public int y = 0;
public boolean onCurve = true;
public boolean endOfContour = false;
public boolean touched = false;
public Point(int x, int y, boolean onCurve, boolean endOfContour) {
this.x = x;
this.y = y;
this.onCurve = onCurve;
this.endOfContour = endOfContour;
}
}
| {
"content_hash": "987cbdf6f2a5e165084318a7d4a8d40b",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 74,
"avg_line_length": 23.318181818181817,
"alnum_prop": 0.6276803118908382,
"repo_name": "Squeegee/batik",
"id": "19696cec563843733744620733a526c1c08f8b71",
"size": "1312",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sources/org/apache/batik/svggen/font/Point.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "12494222"
},
{
"name": "JavaScript",
"bytes": "16619"
},
{
"name": "Shell",
"bytes": "7211"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.servicio.reparaciones.servicio;
import com.servicio.reparaciones.modelo.nosql.Bodega;
import com.servicio.reparaciones.servicio.I.Ibodega;
import com.servicio.reparaciones.servicio.util.Calendario;
import com.servicio.reparaciones.util.MongoPersistence;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.mongodb.morphia.query.UpdateResults;
/**
*
* @author luis
*/
@Stateless
@LocalBean
public class BodegaService implements Ibodega, Serializable {
private static final long serialVersionUID = 5629220083619316205L;
private MongoPersistence conn = new MongoPersistence();
private Datastore ds = conn.context();
private Calendario calendario = new Calendario();
@Override
public Integer generatedCodigo() {
Integer size = ObtenerListaBodegas().size();
Integer code = 1000 + 1 * size;
return code;
}
@Override
public Boolean insert(Bodega bodega) {
Boolean exito = Boolean.FALSE;
if (findByCodigo(bodega).getCodigo() == null
&& bodega != null) {
bodega.setCodigo(generatedCodigo());
bodega.setFlag(1);
this.ds.save(bodega);
exito = Boolean.TRUE;
}
return exito;
}
@Override
public Boolean update(Bodega bodega) {
Query<Bodega> query = this.ds.createQuery(Bodega.class);
query.and(
query.criteria("codigo").equal(bodega.getCodigo())
);
UpdateOperations<Bodega> update = this.ds.createUpdateOperations(Bodega.class);
update.set("nombre", bodega.getNombre()).
set("provincia", bodega.getProvincia()).
set("canton", bodega.getCanton()).
set("responsable", bodega.getResponsable()).
set("username", bodega.getUsername()).
set("lastChange", this.calendario.getCalendario().getTime()).
set("flag", bodega.getFlag());
UpdateResults results = this.ds.update(query, update);
return results.getUpdatedExisting();
}
@Override
public Bodega findByCodigo(Bodega bodega) {
Bodega find = new Bodega();
Query<Bodega> result = this.ds.find(Bodega.class).
field("codigo").equal(bodega.getCodigo()).
field("flag").equal(1);
if (result.asList() != null && !result.asList().isEmpty()) {
find = result.asList().get(0);
}
return find;
}
public Bodega findByNombre(Bodega bodega) {
Bodega find = new Bodega();
Query<Bodega> result = this.ds.find(Bodega.class).
field("nombre").equal(bodega.getNombre()).
field("flag").equal(1);
if (result.asList() != null && !result.asList().isEmpty()) {
find = result.asList().get(0);
}
return find;
}
@Override
public void delete(Bodega bodega) {
this.ds.delete(bodega);
}
@Override
public Boolean deleteFlag(Bodega bodega) {
bodega.setFlag(0);
Query<Bodega> query = this.ds.createQuery(Bodega.class);
query.and(
query.criteria("codigo").equal(bodega.getCodigo())
);
UpdateOperations<Bodega> update = this.ds.createUpdateOperations(Bodega.class);
update.set("flag", bodega.getFlag());
UpdateResults results = this.ds.update(query, update);
return results.getUpdatedExisting();
}
@Override
public List<Bodega> ObtenerListaBodegas(Integer flag) {
List<Bodega> list = new ArrayList<>();
Query<Bodega> result = this.ds.find(Bodega.class).
field("flag").equal(flag);
if (result.asList() != null && !result.asList().isEmpty()) {
list = result.asList();
}
if (list == null) {
list = new ArrayList<>();
}
return list;
}
public List<Bodega> ObtenerListaBodegas() {
List<Bodega> list = new ArrayList<>();
Query<Bodega> result = this.ds.find(Bodega.class);
if (result.asList() != null && !result.asList().isEmpty()) {
list = result.asList();
}
if (list == null) {
list = new ArrayList<>();
}
return list;
}
}
| {
"content_hash": "5dfe2ad02b168222b3861d71baa36e4c",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 87,
"avg_line_length": 33.241134751773046,
"alnum_prop": 0.6101984211649243,
"repo_name": "ServicioReparaciones/ServicioReparaciones",
"id": "6a2c9106ccd2acf99e64210597ee82428724893d",
"size": "4687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ServicioReparaciones-ejb/src/main/java/com/servicio/reparaciones/servicio/BodegaService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "845780"
},
{
"name": "HTML",
"bytes": "320926"
},
{
"name": "Java",
"bytes": "586372"
},
{
"name": "JavaScript",
"bytes": "40445"
}
],
"symlink_target": ""
} |
/**
*
*/
package uk.ac.manchester.cs.pronto;
import java.util.Set;
import org.mindswap.pellet.KnowledgeBase;
import org.semanticweb.owlapi.model.OWLOntology;
import aterm.ATermAppl;
/**
* <p>Title: ProbKnowledgeBase</p>
*
* <p>Description:
* </p>
*
* <p>Copyright: Copyright (c) 2007, 2008</p>
*
* <p>Company: Clark & Parsia, LLC. <http://www.clarkparsia.com></p>
*
* @author pavel
*/
public class ProbKnowledgeBase {
protected PTBox m_ptbox;
protected PABox m_pabox;
protected boolean m_bPreprocessed = false;
public PTBox getPTBox() {
return m_ptbox;
}
public void setPTBox(PTBox ptbox) {
m_ptbox = ptbox;
}
public PABox getPABox() {
return m_pabox;
}
public void setPABox(PABox pabox) {
m_pabox = pabox;
}
public PTBox getPTBoxForIndividual(ATermAppl individual) {
Set<ConditionalConstraint> concreteCC = m_pabox.getConstraintsForIndividual(individual);
PTBox ptbox = null;
if (null != concreteCC) {
ptbox = newPTBox(m_ptbox.getClassicalKnowledgeBase(), m_ptbox.getClassicalOntology(), concreteCC);
ptbox.getSupplementalData().setCache( m_ptbox.getSupplementalData().getCache() );
}
return ptbox;
}
protected PTBox newPTBox(KnowledgeBase kb, OWLOntology ontology, Set<ConditionalConstraint> ccSet) {
return new PTBoxImpl(kb, ontology, ccSet);
}
public void preprocess() {
if( !m_bPreprocessed ) {
m_ptbox.preprocess();
}
m_bPreprocessed = true;
}
protected void addClass(ATermAppl newClass, ATermAppl expr) {
KnowledgeBase kb = m_ptbox.getClassicalKnowledgeBase();
if (null != expr) {
kb.addClass( newClass );
kb.addEquivalentClass( newClass, expr );
}
}
}
| {
"content_hash": "ce558a5a2c98e8125235acc273ea4d13",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 101,
"avg_line_length": 18.526881720430108,
"alnum_prop": 0.677307022634939,
"repo_name": "klinovp/pronto",
"id": "12d02700b2d49654f79601e4c7ab2a71cd6c9c66",
"size": "1723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/uk/ac/manchester/cs/pronto/ProbKnowledgeBase.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "590"
},
{
"name": "Java",
"bytes": "610256"
},
{
"name": "Shell",
"bytes": "306"
},
{
"name": "Web Ontology Language",
"bytes": "2789"
}
],
"symlink_target": ""
} |
// Needed for NET40
using System.Runtime.CompilerServices;
namespace Theraot.Threading.Needles
{
public interface IWaitablePromise : IPromise, INotifyCompletion
{
void Wait();
}
public interface IWaitablePromise<out T> : IPromise<T>, IWaitablePromise
{
// Empty
}
} | {
"content_hash": "c940273939e50c639adbb9b70a7f5963",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 76,
"avg_line_length": 19.3125,
"alnum_prop": 0.6763754045307443,
"repo_name": "theraot/Theraot",
"id": "6fe8b93a23f4b0e5b3d9f56c7a739ecab0b02d28",
"size": "311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Framework.Core/Theraot/Threading/Needles/IWaitablePromise.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "7210557"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:orientation="vertical" >
<TextView
android:id="@+id/lbl_paired_printers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.CustomFont.Semilight"
android:textColor="@color/gray_contrast_color"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:lineSpacingExtra="-4sp"
android:layout_marginTop="8dp"
android:text="@string/lbl_paired_printers"
android:textSize="16sp" />
<ListView
android:id="@+id/list_paired_devices"
android:layout_width="match_parent"
android:layout_marginTop="4dp"
android:layout_height="0dp"
android:layout_weight="0.5" >
</ListView>
<TextView
android:id="@+id/lbl_discovered_printers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.CustomFont.Semilight"
android:textColor="@color/gray_contrast_color"
android:layout_marginTop="8dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:lineSpacingExtra="-4sp"
android:text="@string/lbl_discovered_printers"
android:textSize="16sp" />
<LinearLayout
android:id="@+id/layout_discovering_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:gravity="center"
android:orientation="horizontal" >
<com.alertdialogpro.material.ProgressBarCompat
android:layout_width="25dp"
android:layout_height="25dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_discovering_printers"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:textAppearance="@style/TextAppearance.CustomFont.Semilight"
android:textSize="14sp"
android:textColor="@color/gray_contrast_color"/>
</LinearLayout>
<ListView
android:id="@+id/list_discovered_devices"
android:layout_width="match_parent"
android:layout_marginTop="4dp"
android:layout_height="0dp"
android:layout_weight="0.5" >
</ListView>
</LinearLayout>
| {
"content_hash": "33baf00c3708a0c89cfff4aec24f83c9",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 73,
"avg_line_length": 36.76056338028169,
"alnum_prop": 0.6969348659003831,
"repo_name": "diegoRodriguezAguila/Cobranza.Elfec.Mobile",
"id": "17fcf79ffa7ee74fb555c8faf6da0e40184d4e8f",
"size": "2610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cobranzaElfecMobile/src/main/res/layout/dialog_bluetooth_device_picker.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "612968"
}
],
"symlink_target": ""
} |
package at.rovo.drum.event;
import at.rovo.drum.DrumListener;
/**
* A <em>DrumEvent</em> is an event triggered during processing of the passed data. The event is intended for {@link
* DrumListener} which want to be notified on internal state changes to monitor the current state of the system.
*
* @param <T> The concrete type of the event
* @author Roman Vottner
*/
public abstract class DrumEvent<T extends DrumEvent<T>> {
/**
* The name of the DRUM instance the event was triggered from
*/
protected String drumName;
/**
* The class of the respective event type
*/
private Class<T> clazz;
/**
* The thread the event was triggered from
*/
protected final Thread currentThread = Thread.currentThread();
/**
* Creates a new DRUM event object.
*
* @param drumName The name of the DRUM instance the event was triggered from
* @param clazz The class of the event type
*/
DrumEvent(String drumName, Class<T> clazz) {
this.drumName = drumName;
this.clazz = clazz;
}
/**
* The name of the DRUM instance that triggered the event.
*
* @return The name of the DRUM instance
*/
public String getDrumName() {
return this.drumName;
}
/**
* The class of the event type.
*
* @return The class of the evnet type
*/
public Class<T> getRealClass() {
return this.clazz;
}
/**
* A reference to the thread the event was triggered from.
*
* @return The thread that triggered the event
*/
public Thread getThread() {
return this.currentThread;
}
@Override
public String toString() {
return "DrumEvent[name=" + this.drumName + ", clazz=" + clazz + ", thread=" + currentThread.getName() + "]";
}
}
| {
"content_hash": "0bee80afaa5365d6dd352c5a922a6ba4",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 116,
"avg_line_length": 26.63768115942029,
"alnum_prop": 0.6207834602829162,
"repo_name": "RovoMe/JDrum",
"id": "cf80aec4be91e65dcdfa25064682786039393e20",
"size": "1838",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jdrum-commons/src/main/java/at/rovo/drum/event/DrumEvent.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "267782"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="?attr/colorPrimary"
tools:ignore="Overdraw">
<ImageButton
android:id="@+id/cancel_button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
style="?android:attr/borderlessButtonStyle"
android:src="@drawable/icon_close"
android:contentDescription="@string/edit_cancel_text"
/>
<Space
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3" />
<ImageButton
android:id="@+id/save_button"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
style="?android:attr/borderlessButtonStyle"
android:src="@drawable/icon_check"
android:contentDescription="@string/edit_save_text"
/>
</LinearLayout>
| {
"content_hash": "80d16ecc92dd1336a884cebaf1cf47d3",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 62,
"avg_line_length": 32.55555555555556,
"alnum_prop": 0.6501706484641638,
"repo_name": "debun8/texo",
"id": "ea0463b0dd724a695d9e4ca1cdf0515c5209fe02",
"size": "1172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/dialog_toolbar.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "161549"
}
],
"symlink_target": ""
} |
<?php namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
'App\Console\Commands\LaraditScriptAuthenticationCommand',
'App\Console\Commands\LaraditUserProfileCommand',
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
}
}
| {
"content_hash": "4f0ff0a354eb63fcb34af5fe635384b4",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 62,
"avg_line_length": 21.357142857142858,
"alnum_prop": 0.7357859531772575,
"repo_name": "jrm2k6/laradit-l5-sample-project",
"id": "1d0cf1fcaa16ad9d4ccccaab49a8abe049289ac1",
"size": "598",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Console/Kernel.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "503"
},
{
"name": "PHP",
"bytes": "69885"
}
],
"symlink_target": ""
} |
namespace google {
namespace spanner {
namespace emulator {
namespace backend {
// StorageIteratorRowCursor is an implementation of RowCursor that reads from
// storage using an array of storage iterators.
//
// This class is not thread-safe.
class StorageIteratorRowCursor : public RowCursor {
public:
StorageIteratorRowCursor(
std::vector<std::unique_ptr<StorageIterator>> iterators,
std::vector<const Column*> columns)
: iterators_(std::move(iterators)), columns_(std::move(columns)) {}
// Implementation of the RowCursor interface
bool Next() override;
absl::Status Status() const override;
int NumColumns() const override;
const std::string ColumnName(int i) const override;
const zetasql::Value ColumnValue(int i) const override;
const zetasql::Type* ColumnType(int i) const override;
private:
const std::vector<std::unique_ptr<StorageIterator>> iterators_;
// Index of the iterator being read by row cursor in iterators_.
int current_ = 0;
// Set of columns to read.
const std::vector<const Column*> columns_;
};
} // namespace backend
} // namespace emulator
} // namespace spanner
} // namespace google
#endif // THIRD_PARTY_CLOUD_SPANNER_EMULATOR_BACKEND_TRANSACTION_ROW_CURSOR_H_
| {
"content_hash": "475e2e01f1896d8ba36dcfe7c56d57c8",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 79,
"avg_line_length": 31.225,
"alnum_prop": 0.7317854283426741,
"repo_name": "GoogleCloudPlatform/cloud-spanner-emulator",
"id": "d2a84d3712b77aaba5fc454709bb29e2c4b66c73",
"size": "2123",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/transaction/row_cursor.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "930"
},
{
"name": "C",
"bytes": "1191"
},
{
"name": "C++",
"bytes": "2784986"
},
{
"name": "Dockerfile",
"bytes": "1074"
},
{
"name": "Go",
"bytes": "11426"
},
{
"name": "Python",
"bytes": "27832"
},
{
"name": "Shell",
"bytes": "18701"
},
{
"name": "Starlark",
"bytes": "171188"
}
],
"symlink_target": ""
} |
package main
import (
"fmt"
"log"
"os"
"time"
"bytes"
"encoding/json"
"net/http"
)
const BaseUrl = "https://api.github.com/repos"
type IssuesSearchResult struct {
TotalCount int `json:"total_count"`
Items []*Issue
}
type Issue struct {
Number int
HTMLURL string `json:"html_url"`
Title string
State string
User *User
CreatedAt time.Time `json:"created_at"`
Body string // in Markdown format
}
type User struct {
Login string
HTMLURL string `json:"html_url"`
}
func ListIssues(user, repo string) ([]*Issue, error) {
url := BaseUrl + "/" + user + "/" + repo + "/issues"
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("search query failed: %s", resp.Status)
}
var result []*Issue
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
resp.Body.Close()
return nil, err
}
resp.Body.Close()
return result, nil
}
func CreateIssue(user, repo, title string) (*Issue, error) {
url := BaseUrl + "/" + user + "/" + repo + "/issues"
values := map[string]string{
"title": title,
"body": title,
"assignee": "hophacker",
}
jsonValue, _ := json.Marshal(values)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "token 5717860b349ae716e227d90072cdcd81e8cec9a6")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
var issue Issue
if err := json.NewDecoder(resp.Body).Decode(&issue); err != nil {
return nil, err
}
return &issue, nil
}
func LockIssue(user, repo, number string, lock bool) error {
url := BaseUrl + "/" + user + "/" + repo + "/issues/" + number + "/lock"
req, err := http.NewRequest("PUT", url, bytes.NewBuffer([]byte{}))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "token 5717860b349ae716e227d90072cdcd81e8cec9a6")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
return err
}
func UpdateIssue(user, repo, number, title, body string) (*Issue, error) {
url := BaseUrl + "/" + user + "/" + repo + "/issues/" + number
fmt.Println(url)
values := map[string]string{
"title": title,
"body": body,
}
jsonValue, _ := json.Marshal(values)
req, err := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonValue))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "token 5717860b349ae716e227d90072cdcd81e8cec9a6")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
var issue Issue
if err := json.NewDecoder(resp.Body).Decode(&issue); err != nil {
return nil, err
}
return &issue, nil
}
func printIssue(issue *Issue) {
fmt.Printf("#%-5d %9.9s %.55s %.55s\n", issue.Number, issue.User.Login, issue.Title, issue.Body)
}
func main() {
if len(os.Args) < 4 {
fmt.Println("Please run with parameters: [list|create] [user] [repo] [:title]")
return
}
action := os.Args[1]
user := os.Args[2]
repo := os.Args[3]
switch action {
case "list":
issue, err := ListIssues(user, repo)
if err != nil {
log.Fatal(err)
}
for _, item := range issue {
printIssue(item)
}
case "create":
issue, err := CreateIssue(user, repo, os.Args[4])
if err == nil {
printIssue(issue)
}
case "lock":
err := LockIssue(user, repo, os.Args[4], true)
if err != nil {
log.Fatal(err)
}
case "unlock":
err := LockIssue(user, repo, os.Args[4], false)
if err != nil {
log.Fatal(err)
}
case "update":
number, title, body := os.Args[4], os.Args[5], ""
if len(os.Args) > 6 {
body = os.Args[6]
}
issue, err := UpdateIssue(user, repo, number, title, body)
if err != nil {
log.Fatal(err)
} else {
printIssue(issue)
}
}
} | {
"content_hash": "ba2f4379ecee598b45bc1d2676f9ef19",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 97,
"avg_line_length": 24.448275862068964,
"alnum_prop": 0.612599905970851,
"repo_name": "rallets-network/gopl-exercise",
"id": "de3bfa1dcf5a04a1e0157ad23e789ffad5e43633",
"size": "4254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ch4/4.11/lcn.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "177703"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v5.6.0: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v5.6.0
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1ActivityControl.html">ActivityControl</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">v8::ActivityControl Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ControlOption</b> enum name (defined in <a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a>)</td><td class="entry"><a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>kAbort</b> enum value (defined in <a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a>)</td><td class="entry"><a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>kContinue</b> enum value (defined in <a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a>)</td><td class="entry"><a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classv8_1_1ActivityControl.html#a1300f10611306a3e8f79239e057eb0bf">ReportProgressValue</a>(int done, int total)=0</td><td class="entry"><a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>~ActivityControl</b>() (defined in <a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a>)</td><td class="entry"><a class="el" href="classv8_1_1ActivityControl.html">v8::ActivityControl</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "5d878e85abcc7ff13de0b94cb2b2c70b",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 371,
"avg_line_length": 54.06306306306306,
"alnum_prop": 0.6615564072654557,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "ec62b1930a588964a68fe282e57cbab6fbc07a05",
"size": "6001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dd97d07/html/classv8_1_1ActivityControl-members.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package sound.specific;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.sound.sampled.AudioFormat;
import sound.SoundManager;
public class JadeSoundManager {
private static final AudioFormat f1 = new AudioFormat(22050, 8, 1, true, true); // 22050 Hz.
private static final AudioFormat f2 = new AudioFormat(10512, 8, 1, true, true); // 10512 Hz.
private static final String fileName = "sounds/mario_sounds.txt";
private SoundManager s1;
private SoundManager s2;
private class SoundRecord {
public String name;
public String location;
public int hz;
public SoundRecord(String name, String location, int hz) {
this.name = name;
this.location = location;
this.hz = hz;
}
}
public JadeSoundManager() {
s1 = new SoundManager(f1);
s2 = new SoundManager(f2);
Scanner s = null;
try {
s = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println(e);
}
while(s.hasNextLine()) {
String line = s.nextLine();
Scanner ls = new Scanner(line);
SoundRecord sr = new SoundRecord(ls.next(), ls.next(), ls.nextInt());
}
}
}
| {
"content_hash": "30aa00b6989c1351d8d6f6d7cb94d94f",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 93,
"avg_line_length": 23.132075471698112,
"alnum_prop": 0.6606851549755302,
"repo_name": "DanayaMel/Projects",
"id": "074a68da351d79217472978127a5bb200651ca46",
"size": "1226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sound/specific/JadeSoundManager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "137192"
}
],
"symlink_target": ""
} |
#ifndef SHRPX_DOWNSTREAM_QUEUE_H
#define SHRPX_DOWNSTREAM_QUEUE_H
#include "shrpx.h"
#include <cinttypes>
#include <map>
#include <set>
#include <memory>
#include "template.h"
using namespace nghttp2;
namespace shrpx {
class Downstream;
// Link entry in HostEntry.blocked and downstream because downstream
// could be deleted in anytime and we'd like to find Downstream in
// O(1). Downstream has field to link back to this object.
struct BlockedLink {
Downstream *downstream;
BlockedLink *dlnext, *dlprev;
};
class DownstreamQueue {
public:
struct HostEntry {
HostEntry(ImmutableString &&key);
HostEntry(HostEntry &&) = default;
HostEntry &operator=(HostEntry &&) = default;
HostEntry(const HostEntry &) = delete;
HostEntry &operator=(const HostEntry &) = delete;
// Key that associates this object
ImmutableString key;
// Set of stream ID that blocked by conn_max_per_host_.
DList<BlockedLink> blocked;
// The number of connections currently made to this host.
size_t num_active;
};
using HostEntryMap = std::map<StringRef, HostEntry, std::less<StringRef>>;
// conn_max_per_host == 0 means no limit for downstream connection.
DownstreamQueue(size_t conn_max_per_host = 0, bool unified_host = true);
~DownstreamQueue();
// Add |downstream| to this queue. This is entry point for
// Downstream object.
void add_pending(std::unique_ptr<Downstream> downstream);
// Set |downstream| to failure state, which means that downstream
// failed to connect to backend.
void mark_failure(Downstream *downstream);
// Set |downstream| to active state, which means that downstream
// connection has started.
void mark_active(Downstream *downstream);
// Set |downstream| to blocked state, which means that download
// connection was blocked because conn_max_per_host_ limit.
void mark_blocked(Downstream *downstream);
// Returns true if we can make downstream connection to given
// |host|.
bool can_activate(const StringRef &host) const;
// Removes and frees |downstream| object. If |downstream| is in
// Downstream::DISPATCH_ACTIVE, and |next_blocked| is true, this
// function may return Downstream object with the same target host
// in Downstream::DISPATCH_BLOCKED if its connection is now not
// blocked by conn_max_per_host_ limit.
Downstream *remove_and_get_blocked(Downstream *downstream,
bool next_blocked = true);
Downstream *get_downstreams() const;
HostEntry &find_host_entry(const StringRef &host);
StringRef make_host_key(const StringRef &host) const;
StringRef make_host_key(Downstream *downstream) const;
private:
// Per target host structure to keep track of the number of
// connections to the same host.
HostEntryMap host_entries_;
DList<Downstream> downstreams_;
// Maximum number of concurrent connections to the same host.
size_t conn_max_per_host_;
// true if downstream host is treated as the same. Used for reverse
// proxying.
bool unified_host_;
};
} // namespace shrpx
#endif // SHRPX_DOWNSTREAM_QUEUE_H
| {
"content_hash": "c463f7872e751cc029bf09acddf884f7",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 76,
"avg_line_length": 33.376344086021504,
"alnum_prop": 0.7177835051546392,
"repo_name": "krzychb/rtd-test-bed",
"id": "1a7503431ad01c6d2a5a8da81860f29940f1a3dc",
"size": "4263",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "components/nghttp/nghttp2/src/shrpx_downstream_queue.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "248929"
},
{
"name": "Batchfile",
"bytes": "9428"
},
{
"name": "C",
"bytes": "42611901"
},
{
"name": "C++",
"bytes": "10437923"
},
{
"name": "CMake",
"bytes": "316611"
},
{
"name": "CSS",
"bytes": "1340"
},
{
"name": "Dockerfile",
"bytes": "4319"
},
{
"name": "GDB",
"bytes": "2764"
},
{
"name": "Go",
"bytes": "146670"
},
{
"name": "HCL",
"bytes": "468"
},
{
"name": "HTML",
"bytes": "115431"
},
{
"name": "Inno Setup",
"bytes": "14977"
},
{
"name": "Lex",
"bytes": "7273"
},
{
"name": "M4",
"bytes": "189150"
},
{
"name": "Makefile",
"bytes": "439631"
},
{
"name": "Objective-C",
"bytes": "133538"
},
{
"name": "PHP",
"bytes": "498"
},
{
"name": "Pawn",
"bytes": "151052"
},
{
"name": "Perl",
"bytes": "141532"
},
{
"name": "Python",
"bytes": "1868534"
},
{
"name": "Roff",
"bytes": "102712"
},
{
"name": "Ruby",
"bytes": "206821"
},
{
"name": "Shell",
"bytes": "625528"
},
{
"name": "Smarty",
"bytes": "5972"
},
{
"name": "Tcl",
"bytes": "110"
},
{
"name": "TeX",
"bytes": "1961"
},
{
"name": "Visual Basic",
"bytes": "294"
},
{
"name": "XSLT",
"bytes": "80335"
},
{
"name": "Yacc",
"bytes": "15875"
}
],
"symlink_target": ""
} |
'use strict';
function Preload() {
this.asset = null;
this.ready = false;
}
Preload.prototype = {
preload: function() {
this.asset = this.add.sprite(this.width/2,this.height/2, 'preloader');
this.asset.anchor.setTo(0.5, 0.5);
this.load.onLoadComplete.addOnce(this.onLoadComplete, this);
this.load.setPreloadSprite(this.asset);
this.load.image('marker', 'assets/marker.png');
this.load.tilemap('map', 'assets/level1.json', null, Phaser.Tilemap.TILED_JSON);
this.load.image('tileset', 'assets/tileset.png');
this.load.image ('marker', 'assets/marker.png');
this.load.spritesheet('arrows', 'assets/arrows.png', 16, 16, 4);
},
create: function() {
this.asset.cropEnabled = false;
},
update: function() {
if(!!this.ready) {
this.game.state.start('play');
}
},
onLoadComplete: function() {
this.ready = true;
}
};
module.exports = Preload; | {
"content_hash": "9fcb0b61b2183d218c9923b5786ccff8",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 84,
"avg_line_length": 27.696969696969695,
"alnum_prop": 0.6477024070021882,
"repo_name": "vigov5/fill_me",
"id": "683b92c29427a33e08a7953955bb9b1a20af3f7a",
"size": "915",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "game/states/preload.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "306"
},
{
"name": "HTML",
"bytes": "980"
},
{
"name": "JavaScript",
"bytes": "2941235"
},
{
"name": "Smarty",
"bytes": "384"
}
],
"symlink_target": ""
} |
int *global_ptr = &global; // Without this line, everything is fine
int main()
{
func();
printf("global = 0x%x (%p)%s\n", global, &global, ((global != 0x42)? ", ERROR!!!":""));
return global != 0x42;
}
| {
"content_hash": "98b0ffe9d93586e4677a142755d0f6b5",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 91,
"avg_line_length": 26.875,
"alnum_prop": 0.5627906976744186,
"repo_name": "efortuna/AndroidSDKClone",
"id": "f47ef0026963aedbc1cdfde9bd06322d36511b6a",
"size": "251",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "ndk_experimental/tests/device/issue28598-linker-global-ref/jni/main.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AppleScript",
"bytes": "0"
},
{
"name": "Assembly",
"bytes": "79928"
},
{
"name": "Awk",
"bytes": "101642"
},
{
"name": "C",
"bytes": "110780727"
},
{
"name": "C++",
"bytes": "62609188"
},
{
"name": "CSS",
"bytes": "318944"
},
{
"name": "Component Pascal",
"bytes": "220"
},
{
"name": "Emacs Lisp",
"bytes": "4737"
},
{
"name": "Groovy",
"bytes": "82931"
},
{
"name": "IDL",
"bytes": "31867"
},
{
"name": "Java",
"bytes": "102919416"
},
{
"name": "JavaScript",
"bytes": "44616"
},
{
"name": "Objective-C",
"bytes": "196166"
},
{
"name": "Perl",
"bytes": "45617403"
},
{
"name": "Prolog",
"bytes": "1828886"
},
{
"name": "Python",
"bytes": "34997242"
},
{
"name": "Rust",
"bytes": "17781"
},
{
"name": "Shell",
"bytes": "1585527"
},
{
"name": "Visual Basic",
"bytes": "962"
},
{
"name": "XC",
"bytes": "802542"
}
],
"symlink_target": ""
} |
const int ExtensionWelcomeNotification::kRequestedShowTimeDays = 14;
namespace {
class NotificationCallbacks
: public message_center::NotificationDelegate {
public:
NotificationCallbacks(
Profile* profile,
const message_center::NotifierId notifier_id,
const std::string& welcome_notification_id,
ExtensionWelcomeNotification::Delegate* delegate)
: profile_(profile),
notifier_id_(notifier_id.type, notifier_id.id),
welcome_notification_id_(welcome_notification_id),
delegate_(delegate) {
}
// Overridden from NotificationDelegate:
virtual void Display() OVERRIDE {}
virtual void Error() OVERRIDE {}
virtual void Close(bool by_user) OVERRIDE {
if (by_user) {
// Setting the preference here may cause the notification erasing
// to reenter. Posting a task avoids this issue.
delegate_->PostTask(
FROM_HERE,
base::Bind(&NotificationCallbacks::MarkAsDismissed, this));
}
}
virtual void Click() OVERRIDE {}
virtual void ButtonClick(int index) OVERRIDE {
if (index == 0) {
OpenNotificationLearnMoreTab();
} else if (index == 1) {
DisableNotificationProvider();
Close(true);
} else {
NOTREACHED();
}
}
private:
void MarkAsDismissed() {
profile_->GetPrefs()->SetBoolean(prefs::kWelcomeNotificationDismissedLocal,
true);
}
void OpenNotificationLearnMoreTab() {
chrome::NavigateParams params(
profile_,
GURL(chrome::kNotificationWelcomeLearnMoreURL),
content::PAGE_TRANSITION_LINK);
params.disposition = NEW_FOREGROUND_TAB;
params.window_action = chrome::NavigateParams::SHOW_WINDOW;
chrome::Navigate(¶ms);
}
void DisableNotificationProvider() {
message_center::Notifier notifier(notifier_id_, base::string16(), true);
message_center::MessageCenter* message_center =
delegate_->GetMessageCenter();
message_center->DisableNotificationsByNotifier(notifier_id_);
message_center->RemoveNotification(welcome_notification_id_, false);
message_center->GetNotifierSettingsProvider()->SetNotifierEnabled(
notifier, false);
}
virtual ~NotificationCallbacks() {}
Profile* const profile_;
const message_center::NotifierId notifier_id_;
std::string welcome_notification_id_;
// Weak ref owned by ExtensionWelcomeNotification.
ExtensionWelcomeNotification::Delegate* const delegate_;
DISALLOW_COPY_AND_ASSIGN(NotificationCallbacks);
};
class DefaultDelegate : public ExtensionWelcomeNotification::Delegate {
public:
DefaultDelegate() {}
virtual message_center::MessageCenter* GetMessageCenter() OVERRIDE {
return g_browser_process->message_center();
}
virtual base::Time GetCurrentTime() OVERRIDE {
return base::Time::Now();
}
virtual void PostTask(
const tracked_objects::Location& from_here,
const base::Closure& task) OVERRIDE {
base::MessageLoop::current()->PostTask(from_here, task);
}
private:
DISALLOW_COPY_AND_ASSIGN(DefaultDelegate);
};
} // namespace
ExtensionWelcomeNotification::ExtensionWelcomeNotification(
const std::string& extension_id,
Profile* const profile,
ExtensionWelcomeNotification::Delegate* const delegate)
: notifier_id_(message_center::NotifierId::APPLICATION, extension_id),
profile_(profile),
delegate_(delegate) {
welcome_notification_dismissed_pref_.Init(
prefs::kWelcomeNotificationDismissed,
profile_->GetPrefs(),
base::Bind(
&ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged,
base::Unretained(this)));
welcome_notification_dismissed_local_pref_.Init(
prefs::kWelcomeNotificationDismissedLocal,
profile_->GetPrefs());
}
// static
scoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create(
const std::string& extension_id,
Profile* const profile) {
return Create(extension_id, profile, new DefaultDelegate()).Pass();
}
// static
scoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create(
const std::string& extension_id,
Profile* const profile,
Delegate* const delegate) {
return scoped_ptr<ExtensionWelcomeNotification>(
new ExtensionWelcomeNotification(extension_id, profile, delegate)).Pass();
}
ExtensionWelcomeNotification::~ExtensionWelcomeNotification() {
if (delayed_notification_) {
delayed_notification_.reset();
PrefServiceSyncable::FromProfile(profile_)->RemoveObserver(this);
} else {
HideWelcomeNotification();
}
}
void ExtensionWelcomeNotification::OnIsSyncingChanged() {
DCHECK(delayed_notification_);
PrefServiceSyncable* const pref_service_syncable =
PrefServiceSyncable::FromProfile(profile_);
if (pref_service_syncable->IsSyncing()) {
pref_service_syncable->RemoveObserver(this);
scoped_ptr<Notification> previous_notification(
delayed_notification_.release());
ShowWelcomeNotificationIfNecessary(*(previous_notification.get()));
}
}
void ExtensionWelcomeNotification::ShowWelcomeNotificationIfNecessary(
const Notification& notification) {
if ((notification.notifier_id() == notifier_id_) && !delayed_notification_) {
PrefServiceSyncable* const pref_service_syncable =
PrefServiceSyncable::FromProfile(profile_);
if (pref_service_syncable->IsSyncing()) {
PrefService* const pref_service = profile_->GetPrefs();
if (!UserHasDismissedWelcomeNotification()) {
const PopUpRequest pop_up_request =
pref_service->GetBoolean(
prefs::kWelcomeNotificationPreviouslyPoppedUp)
? POP_UP_HIDDEN
: POP_UP_SHOWN;
if (pop_up_request == POP_UP_SHOWN) {
pref_service->SetBoolean(
prefs::kWelcomeNotificationPreviouslyPoppedUp, true);
}
if (IsWelcomeNotificationExpired()) {
ExpireWelcomeNotification();
} else {
ShowWelcomeNotification(
notification.display_source(), pop_up_request);
}
}
} else {
delayed_notification_.reset(new Notification(notification));
pref_service_syncable->AddObserver(this);
}
}
}
// static
void ExtensionWelcomeNotification::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* prefs) {
prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissed,
false,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissedLocal,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
prefs->RegisterBooleanPref(prefs::kWelcomeNotificationPreviouslyPoppedUp,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
prefs->RegisterInt64Pref(prefs::kWelcomeNotificationExpirationTimestamp,
0,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
message_center::MessageCenter*
ExtensionWelcomeNotification::GetMessageCenter() const {
return delegate_->GetMessageCenter();
}
void ExtensionWelcomeNotification::ShowWelcomeNotification(
const base::string16& display_source,
const PopUpRequest pop_up_request) {
message_center::ButtonInfo learn_more(
l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BUTTON_LEARN_MORE));
learn_more.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_NOTIFICATION_WELCOME_LEARN_MORE);
message_center::ButtonInfo disable(
l10n_util::GetStringUTF16(IDS_NOTIFIER_WELCOME_BUTTON));
disable.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_NOTIFIER_BLOCK_BUTTON);
message_center::RichNotificationData rich_notification_data;
rich_notification_data.priority = 2;
rich_notification_data.buttons.push_back(learn_more);
rich_notification_data.buttons.push_back(disable);
if (welcome_notification_id_.empty())
welcome_notification_id_ = base::GenerateGUID();
if (!welcome_notification_id_.empty()) {
scoped_ptr<message_center::Notification> message_center_notification(
new message_center::Notification(
message_center::NOTIFICATION_TYPE_BASE_FORMAT,
welcome_notification_id_,
l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_TITLE),
l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BODY),
ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_NOTIFICATION_WELCOME_ICON),
display_source,
notifier_id_,
rich_notification_data,
new NotificationCallbacks(
profile_, notifier_id_, welcome_notification_id_,
delegate_.get())));
if (pop_up_request == POP_UP_HIDDEN)
message_center_notification->set_shown_as_popup(true);
GetMessageCenter()->AddNotification(message_center_notification.Pass());
StartExpirationTimer();
}
}
void ExtensionWelcomeNotification::HideWelcomeNotification() {
if (!welcome_notification_id_.empty() &&
GetMessageCenter()->FindVisibleNotificationById(
welcome_notification_id_) != NULL) {
GetMessageCenter()->RemoveNotification(welcome_notification_id_, false);
StopExpirationTimer();
}
}
bool ExtensionWelcomeNotification::UserHasDismissedWelcomeNotification() const {
// This was previously a syncable preference; now it's per-machine.
// Only the local pref will be written moving forward, but check for both so
// users won't be double-toasted.
bool shown_synced = profile_->GetPrefs()->GetBoolean(
prefs::kWelcomeNotificationDismissed);
bool shown_local = profile_->GetPrefs()->GetBoolean(
prefs::kWelcomeNotificationDismissedLocal);
return (shown_synced || shown_local);
}
void ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged() {
if (UserHasDismissedWelcomeNotification()) {
HideWelcomeNotification();
}
}
void ExtensionWelcomeNotification::StartExpirationTimer() {
if (!expiration_timer_ && !IsWelcomeNotificationExpired()) {
base::Time expiration_timestamp = GetExpirationTimestamp();
if (expiration_timestamp.is_null()) {
SetExpirationTimestampFromNow();
expiration_timestamp = GetExpirationTimestamp();
DCHECK(!expiration_timestamp.is_null());
}
expiration_timer_.reset(
new base::OneShotTimer<ExtensionWelcomeNotification>());
expiration_timer_->Start(
FROM_HERE,
expiration_timestamp - delegate_->GetCurrentTime(),
this,
&ExtensionWelcomeNotification::ExpireWelcomeNotification);
}
}
void ExtensionWelcomeNotification::StopExpirationTimer() {
if (expiration_timer_) {
expiration_timer_->Stop();
expiration_timer_.reset();
}
}
void ExtensionWelcomeNotification::ExpireWelcomeNotification() {
DCHECK(IsWelcomeNotificationExpired());
profile_->GetPrefs()->SetBoolean(
prefs::kWelcomeNotificationDismissedLocal, true);
HideWelcomeNotification();
}
base::Time ExtensionWelcomeNotification::GetExpirationTimestamp() const {
PrefService* const pref_service = profile_->GetPrefs();
const int64 expiration_timestamp =
pref_service->GetInt64(prefs::kWelcomeNotificationExpirationTimestamp);
return (expiration_timestamp == 0)
? base::Time()
: base::Time::FromInternalValue(expiration_timestamp);
}
void ExtensionWelcomeNotification::SetExpirationTimestampFromNow() {
PrefService* const pref_service = profile_->GetPrefs();
pref_service->SetInt64(
prefs::kWelcomeNotificationExpirationTimestamp,
(delegate_->GetCurrentTime() +
base::TimeDelta::FromDays(kRequestedShowTimeDays)).ToInternalValue());
}
bool ExtensionWelcomeNotification::IsWelcomeNotificationExpired() const {
const base::Time expiration_timestamp = GetExpirationTimestamp();
return !expiration_timestamp.is_null() &&
(expiration_timestamp <= delegate_->GetCurrentTime());
}
| {
"content_hash": "8fe6da09e5c407030eb8ce1959c1a64c",
"timestamp": "",
"source": "github",
"line_count": 341,
"max_line_length": 80,
"avg_line_length": 35.49266862170088,
"alnum_prop": 0.7025530860117326,
"repo_name": "xin3liang/platform_external_chromium_org",
"id": "84019cef056a3dfabd9538679a94f191c22a03f5",
"size": "13272",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "chrome/browser/notifications/extension_welcome_notification.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Assembly",
"bytes": "53530"
},
{
"name": "Awk",
"bytes": "7721"
},
{
"name": "C",
"bytes": "35959480"
},
{
"name": "C++",
"bytes": "223698188"
},
{
"name": "CSS",
"bytes": "973752"
},
{
"name": "Java",
"bytes": "6804114"
},
{
"name": "JavaScript",
"bytes": "12537619"
},
{
"name": "Mercury",
"bytes": "9480"
},
{
"name": "Objective-C",
"bytes": "880662"
},
{
"name": "Objective-C++",
"bytes": "7094479"
},
{
"name": "PHP",
"bytes": "61320"
},
{
"name": "Perl",
"bytes": "644436"
},
{
"name": "Python",
"bytes": "10027001"
},
{
"name": "Shell",
"bytes": "1313358"
},
{
"name": "Standard ML",
"bytes": "4131"
},
{
"name": "Tcl",
"bytes": "277091"
},
{
"name": "XSLT",
"bytes": "12410"
},
{
"name": "nesC",
"bytes": "15206"
}
],
"symlink_target": ""
} |
public struct ItemId
{
private const string prefix = "MyObjectBuilder_";
private readonly string type;
private readonly string subtype;
public ItemId(VRage.ObjectBuilders.MyObjectBuilder_Base content)
{
var typeId = content.TypeId.ToString();
this.type = (typeId.IndexOf(prefix) == 0) ? typeId.Substring(prefix.Length) : "";
this.subtype = content.SubtypeName;
}
public string Type { get { return type; } }
public string Subtype { get { return subtype; } }
public override string ToString()
{
return string.Format("[{0}:{1}]", Type, Subtype);
}
}
| {
"content_hash": "2112ae19d8ff814c8985d874c301b5de",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 91,
"avg_line_length": 31.045454545454547,
"alnum_prop": 0.5915080527086384,
"repo_name": "Pharap/SpengyUtils",
"id": "425f7730c2a759e5be14c8e3093bc486392fb23b",
"size": "846",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Classes/ItemId.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "6541"
}
],
"symlink_target": ""
} |
import React from 'react'
const DragOverlay = () => (
<div className='drag-overlay'>
<span>
<i className='fa fa-cloud-upload fa-3x' />
<h3>Drag to Upload</h3>
</span>
</div>
)
export default DragOverlay
| {
"content_hash": "44981f481511d05a478d9e608a0f3400",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 48,
"avg_line_length": 19.083333333333332,
"alnum_prop": 0.6069868995633187,
"repo_name": "NebulousLabs/New-Sia-UI",
"id": "c4657bba24a1539bed3859a7c833a683a3ba241e",
"size": "229",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/Files/js/components/dragoverlay.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17137"
},
{
"name": "HTML",
"bytes": "15835"
},
{
"name": "JavaScript",
"bytes": "129419"
},
{
"name": "Shell",
"bytes": "2206"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package htmleditor.builders;
import htmleditor.HTMLEditor;
/**
*
* @author thn1069
*/
public interface Builder {
public void build(HTMLEditor editor);
}
| {
"content_hash": "6d71da7b1bdd5793feecbdee5b8699e1",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 79,
"avg_line_length": 22.6875,
"alnum_prop": 0.699724517906336,
"repo_name": "Hydral1k/HTMLEditor",
"id": "28c776f3df641a31a396df1caac56edde270736a",
"size": "363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "HTMLEditor/src/htmleditor/builders/Builder.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "115098"
},
{
"name": "HTML",
"bytes": "223"
},
{
"name": "Java",
"bytes": "130645"
}
],
"symlink_target": ""
} |
module Azure::Network::Mgmt::V2015_05_01_preview
module Models
#
# Contains ServiceProviderProperties in an ExpressRouteCircuit
#
class ExpressRouteCircuitServiceProviderProperties
include MsRestAzure
# @return [String] Gets or sets serviceProviderName.
attr_accessor :service_provider_name
# @return [String] Gets or sets peering location.
attr_accessor :peering_location
# @return [Integer] Gets or sets BandwidthInMbps.
attr_accessor :bandwidth_in_mbps
#
# Mapper for ExpressRouteCircuitServiceProviderProperties class as Ruby
# Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ExpressRouteCircuitServiceProviderProperties',
type: {
name: 'Composite',
class_name: 'ExpressRouteCircuitServiceProviderProperties',
model_properties: {
service_provider_name: {
client_side_validation: true,
required: false,
serialized_name: 'serviceProviderName',
type: {
name: 'String'
}
},
peering_location: {
client_side_validation: true,
required: false,
serialized_name: 'peeringLocation',
type: {
name: 'String'
}
},
bandwidth_in_mbps: {
client_side_validation: true,
required: false,
serialized_name: 'bandwidthInMbps',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| {
"content_hash": "40d9f281f88b36b441a5937144414d54",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 77,
"avg_line_length": 29.125,
"alnum_prop": 0.5284334763948498,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "2d65a53201e9cc6bda4e4813c6800195323be3d2",
"size": "2028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_network/lib/2015-05-01-preview/generated/azure_mgmt_network/models/express_route_circuit_service_provider_properties.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
This is a ROS package for integrating the `ros_control` controller architecture
with the [Gazebo](http://gazebosim.org/) simulator.
This package provides a Gazebo plugin which instantiates a ros_control
controller manager and connects it to a Gazebo model.
[Documentation](http://gazebosim.org/wiki/Tutorials/1.9/ROS_Control_with_Gazebo) is provided on Gazebo's website.
## Future Direction
- Implement transmissions
| {
"content_hash": "170b9ba3fcc20e76d72e7e98abdce417",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 113,
"avg_line_length": 38.45454545454545,
"alnum_prop": 0.7919621749408984,
"repo_name": "Aridane/underwater_map_construction",
"id": "01ccb59351ec9fd2b2cca8fe9b009908bc9ceca6",
"size": "456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gazebo_ros_pkgs/gazebo_ros_control/README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "23593"
},
{
"name": "C++",
"bytes": "750131"
},
{
"name": "CMake",
"bytes": "37549"
},
{
"name": "Python",
"bytes": "61891"
},
{
"name": "Shell",
"bytes": "4569"
}
],
"symlink_target": ""
} |
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
[assembly: TypeForwardedTo(typeof(ImmutableStack))]
#else
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Validation;
namespace System.Collections.Immutable
{
/// <summary>
/// A set of initialization methods for instances of <see cref="ImmutableStack{T}"/>.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public static class ImmutableStack
{
/// <summary>
/// Returns an empty collection.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <returns>The immutable collection.</returns>
[Pure]
public static ImmutableStack<T> Create<T>()
{
return ImmutableStack<T>.Empty;
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified item.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <param name="item">The item to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public static ImmutableStack<T> Create<T>(T item)
{
return ImmutableStack<T>.Empty.Push(item);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public static ImmutableStack<T> CreateRange<T>(IEnumerable<T> items)
{
Requires.NotNull(items, "items");
var stack = ImmutableStack<T>.Empty;
foreach (var item in items)
{
stack = stack.Push(item);
}
return stack;
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="T">The type of items stored by the collection.</typeparam>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[Pure]
public static ImmutableStack<T> Create<T>(params T[] items)
{
Requires.NotNull(items, "items");
var stack = ImmutableStack<T>.Empty;
foreach (var item in items)
{
stack = stack.Push(item);
}
return stack;
}
/// <summary>
/// Pops the top element off the stack.
/// </summary>
/// <typeparam name="T">The type of values contained in the stack.</typeparam>
/// <param name="stack">The stack to modify.</param>
/// <param name="value">The value that was removed from the stack.</param>
/// <returns>
/// A stack; never <c>null</c>
/// </returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")]
[Pure]
public static IImmutableStack<T> Pop<T>(this IImmutableStack<T> stack, out T value)
{
Requires.NotNull(stack, "stack");
Contract.Ensures(Contract.Result<IImmutableStack<T>>() != null);
value = stack.Peek();
return stack.Pop();
}
}
}
#endif
| {
"content_hash": "d5db4a1e6cdd275b11fec462ac1f2b75",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 101,
"avg_line_length": 35.236363636363635,
"alnum_prop": 0.5949432404540763,
"repo_name": "tunnelvisionlabs/dotnet-collections",
"id": "356a0df0afe829c3370721742cf1219a1c7a03c3",
"size": "3891",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1739812"
},
{
"name": "PowerShell",
"bytes": "4201"
}
],
"symlink_target": ""
} |
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'simplecov'
SimpleCov.start
require 'opsworks_rolling_deploy'
| {
"content_hash": "e256f9a78ad378cf742bc2bcc5397d3a",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 58,
"avg_line_length": 32.25,
"alnum_prop": 0.7286821705426356,
"repo_name": "truckpad/opsworks_rolling_deploy",
"id": "0ca8d848ba87bfddc996e99ff3b55a1bf906cc68",
"size": "129",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "15382"
}
],
"symlink_target": ""
} |
package org.ofbiz.widget.model;
import org.ofbiz.widget.model.AbstractModelCondition.And;
import org.ofbiz.widget.model.AbstractModelCondition.IfCompare;
import org.ofbiz.widget.model.AbstractModelCondition.IfCompareField;
import org.ofbiz.widget.model.AbstractModelCondition.IfComponent;
import org.ofbiz.widget.model.AbstractModelCondition.IfEmpty;
import org.ofbiz.widget.model.AbstractModelCondition.IfEntity;
import org.ofbiz.widget.model.AbstractModelCondition.IfEntityPermission;
import org.ofbiz.widget.model.AbstractModelCondition.IfHasPermission;
import org.ofbiz.widget.model.AbstractModelCondition.IfRegexp;
import org.ofbiz.widget.model.AbstractModelCondition.IfService;
import org.ofbiz.widget.model.AbstractModelCondition.IfServicePermission;
import org.ofbiz.widget.model.AbstractModelCondition.IfValidateMethod;
import org.ofbiz.widget.model.AbstractModelCondition.Not;
import org.ofbiz.widget.model.AbstractModelCondition.Or;
import org.ofbiz.widget.model.AbstractModelCondition.Xor;
import org.ofbiz.widget.model.ModelScreenCondition.IfEmptySection;
/**
* A <code>ModelCondition</code> visitor.
*/
public interface ModelConditionVisitor {
void visit(And and) throws Exception;
void visit(IfCompare ifCompare) throws Exception;
void visit(IfCompareField ifCompareField) throws Exception;
void visit(IfEmpty ifEmpty) throws Exception;
void visit(IfEntityPermission ifEntityPermission) throws Exception;
void visit(IfHasPermission ifHasPermission) throws Exception;
void visit(IfRegexp ifRegexp) throws Exception;
void visit(IfServicePermission ifServicePermission) throws Exception;
void visit(IfValidateMethod ifValidateMethod) throws Exception;
void visit(Not not) throws Exception;
void visit(Or or) throws Exception;
void visit(Xor xor) throws Exception;
void visit(ModelMenuCondition modelMenuCondition) throws Exception;
void visit(ModelTreeCondition modelTreeCondition) throws Exception;
void visit(IfEmptySection ifEmptySection) throws Exception;
void visit(IfComponent ifComponent) throws Exception; // SCIPIO
void visit(IfEntity ifEntity) throws Exception; // SCIPIO
void visit(IfService ifService) throws Exception; // SCIPIO
}
| {
"content_hash": "4af8b0bf523dbeccc85cbdd237275611",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 73,
"avg_line_length": 36.91803278688525,
"alnum_prop": 0.8174955595026643,
"repo_name": "ilscipio/scipio-erp",
"id": "a1a5cc9434627ae8d427c8058f259251896d8258",
"size": "3231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/widget/src/org/ofbiz/widget/model/ModelConditionVisitor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "15540"
},
{
"name": "CSS",
"bytes": "533213"
},
{
"name": "FreeMarker",
"bytes": "6482124"
},
{
"name": "Groovy",
"bytes": "2254105"
},
{
"name": "HTML",
"bytes": "4409922"
},
{
"name": "Java",
"bytes": "23079876"
},
{
"name": "JavaScript",
"bytes": "1106310"
},
{
"name": "Ruby",
"bytes": "2377"
},
{
"name": "SCSS",
"bytes": "514759"
},
{
"name": "Shell",
"bytes": "66335"
},
{
"name": "XSLT",
"bytes": "1712"
}
],
"symlink_target": ""
} |
package de.gishmo.module0812.gwt.client.resource;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
public interface ImageResources
extends ClientBundle {
ImageResources INSTANCE = (ImageResources) GWT.create(ImageResources.class);
@Source("Gwt-logo.png")
ImageResource gwtLogo();
}
| {
"content_hash": "9957dc8c7309a61174c5fee3bd7477ae",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 78,
"avg_line_length": 26.4,
"alnum_prop": 0.7878787878787878,
"repo_name": "FrankHossfeld/Training",
"id": "330087019c3959fc41286f5f72626debfa437e01",
"size": "396",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GWT-OLD/Module0812/src/de/gishmo/module0812/gwt/client/resource/ImageResources.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "227738"
},
{
"name": "HTML",
"bytes": "73644"
},
{
"name": "Java",
"bytes": "1092442"
},
{
"name": "JavaScript",
"bytes": "9896"
}
],
"symlink_target": ""
} |
package com.invisiblecollector.model.serialization;
import com.invisiblecollector.exceptions.IcRuntimeException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringUtils {
/** Follows ISO 8601 cropped to day without timezones. */
public static final String DATE_FORMAT =
"yyyy-MM-dd"; // https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html?is-external=true
public static String dateToString(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
return formatter.format(date);
}
public static Date parseDateString(String dateString) {
if (dateString == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
try {
return formatter.parse(dateString);
} catch (ParseException e) {
throw new IcRuntimeException(e);
}
}
}
| {
"content_hash": "b63345c03b0ea73f1fa39e20fb037a1e",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 113,
"avg_line_length": 28.6,
"alnum_prop": 0.6993006993006993,
"repo_name": "invisiblecloud/invoice-capture-client",
"id": "483337a02c35b997803466f082f12d02d9e82694",
"size": "1001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/invisiblecollector/model/serialization/StringUtils.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "167388"
}
],
"symlink_target": ""
} |
package com.applandeo.viewmodels;
import android.app.Activity;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableList;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.annimon.stream.Stream;
import com.applandeo.adapters.FileAdapter;
import com.applandeo.comparators.SortingOptions;
import com.applandeo.filepicker.BR;
import com.applandeo.listeners.OnRecyclerViewRowClick;
import com.applandeo.listeners.OnSelectFileListener;
import com.applandeo.utils.FileUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;
import static com.applandeo.constants.FileType.DIRECTORY;
/**
* This class represents a view model of the file picker dialog
* <p>
* Created by Mateusz Kornakiewicz on 29.08.2017.
*/
public class PickerDialogViewModel extends BaseObservable implements OnRecyclerViewRowClick {
private static final String DEFAULT_DIR
= Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS;
private Activity mActivity;
private final OnSelectFileListener mOnSelectFileListener;
private AlertDialog mAlertDialog;
private File mCurrentFile;
private File mMainDirectory = Environment.getExternalStorageDirectory();
private boolean mHideFiles;
private String mFilesType;
private ObservableList<FileRowViewModel> mFilesList = new ObservableArrayList<>();
private FileAdapter mAdapter = new FileAdapter(mFilesList);
private List<Integer> mPositions = new ArrayList<>();
private int mCurrentListPosition;
private int mListPosition;
public PickerDialogViewModel(Activity activity, String path, OnSelectFileListener onSelectFileListener,
boolean hideFiles, String mainDirectory, String filesType) {
mActivity = activity;
mOnSelectFileListener = onSelectFileListener;
mAdapter.setOnRecycleViewRowClick(this);
mHideFiles = hideFiles;
mFilesType = filesType;
if (path == null) {
path = DEFAULT_DIR;
}
File file = new File(path);
if (!file.exists()) {
file = new File(DEFAULT_DIR);
}
setMainDirectory(path, mainDirectory);
openDirectory(file, 0);
}
private void setMainDirectory(String path, String mainDirectory) {
if (mainDirectory != null) {
if (path.length() < mainDirectory.length()) {
mMainDirectory = mCurrentFile;
} else {
File mainDir = new File(mainDirectory);
if (mainDir.exists()) {
mMainDirectory = mainDir;
}
}
}
}
/**
* Listener to handle toolbar's navigation button click
*/
public final View.OnClickListener onToolbarIconClickListener = v -> {
File parent = mCurrentFile.getParentFile();
if (mCurrentFile.equals(mMainDirectory)) {
mAlertDialog.cancel();
return;
}
if (parent != null) {
int position = 0;
if (!mPositions.isEmpty()) {
position = mPositions.get(mPositions.size() - 1);
mPositions.remove(mPositions.size() - 1);
}
openDirectory(parent, position);
}
};
public void setAlertDialog(AlertDialog alertDialog) {
mAlertDialog = alertDialog;
}
@Bindable
public File getCurrentFile() {
return mCurrentFile;
}
private void setCurrentFile(File currentFile) {
mCurrentFile = currentFile;
notifyPropertyChanged(BR.currentFile);
}
@Bindable
public File getParentDirectory() {
return mMainDirectory;
}
@Bindable
public ObservableList<FileRowViewModel> getFileList() {
return mFilesList;
}
@Bindable
public FileAdapter getAdapter() {
return mAdapter;
}
@Bindable
public int getPosition() {
return mListPosition;
}
private void setListPosition(int position) {
mListPosition = position;
notifyPropertyChanged(BR.position);
}
public void onCancel() {
mAlertDialog.cancel();
}
public void onSelect() {
mAlertDialog.cancel();
mOnSelectFileListener.onSelect(mCurrentFile);
}
/**
* ScrollListener needed to get current list position
*/
public final RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == SCROLL_STATE_IDLE) {
mCurrentListPosition = ((LinearLayoutManager) recyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
}
};
/**
* Asynchronous method to getting files list
*
* @param directory An instance of parent File object
* @param position Position of the files list
*/
private void openDirectory(File directory, int position) {
Single<List<FileRowViewModel>> filesList = Single.create(emitter -> {
try {
List<FileRowViewModel> list = getFiles(directory);
emitter.onSuccess(list);
} catch (Exception e) {
emitter.onError(e);
}
});
filesList.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(fileRowViewModels -> {
setCurrentFile(directory);
mFilesList.clear();
mFilesList.addAll(fileRowViewModels);
setListPosition(position);
});
}
/**
* This method is used to getting files list
*
* @param directory An instance of parent File object
* @return A list of FileRowViewModels which contain an instance of File object
*/
private List<FileRowViewModel> getFiles(File directory) {
List<FileRowViewModel> list = new ArrayList<>();
File[] files = directory.listFiles();
if (files != null) {
List<File> filteredList = Stream.of(files)
.filter(File::exists)
.filter(file -> !file.isHidden()).toList();
if (mHideFiles) {
filteredList = Stream.of(filteredList).filter(File::isDirectory).toList();
}
if (mFilesType != null) {
filteredList = Stream.of(filteredList)
.filter(file -> (FileUtils.getType(mActivity, Uri.fromFile(file)).equals(mFilesType)
|| FileUtils.getType(mActivity, Uri.fromFile(file)).equals(DIRECTORY))).toList();
}
Stream.of(filteredList)
.sorted(SortingOptions.SortByNameAscendingFolderFirst)
.forEach(file -> list.add(new FileRowViewModel(mActivity, file)));
}
return list;
}
/**
* Listener to handle files list row click
*
* @param file Clicked file
*/
@Override
public void onClick(File file) {
if (file.isDirectory()) {
mPositions.add(mCurrentListPosition);
openDirectory(file, 0);
return;
}
mAlertDialog.cancel();
mOnSelectFileListener.onSelect(file);
}
}
| {
"content_hash": "0151151f096b46fc95eaa7c05e1115eb",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 113,
"avg_line_length": 31.15234375,
"alnum_prop": 0.6331034482758621,
"repo_name": "Applandeo/Material-File-Picker",
"id": "b31372d9ba0b03a6b5b665a1b74d6270b8988f98",
"size": "7975",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/src/main/java/com/applandeo/viewmodels/PickerDialogViewModel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "33125"
}
],
"symlink_target": ""
} |
<?php namespace URFBattleground\Managers\LolApi\Traits;
trait AutoRepeatingOnLimitTrait {
/** @var bool */
private $autoRepeat = false;
/** @var int */
private $repeatAttempts;
/**
* @param bool|int $attempts - int to set repeat attempts or empty to make requests until limit passes
* @return $this
*/
public function autoRepeatOnLimitExceed($attempts = null)
{
$this->autoRepeat = true;
$this->repeatAttempts = (is_int($attempts) ? $attempts : null);
return $this;
}
/**
* @return $this
*/
public function throwOnLimitExceed()
{
$this->autoRepeat = false;
return $this;
}
/**
* @return bool
*/
public function isAutoRepeat()
{
return $this->autoRepeat;
}
/**
* @return bool
*/
public function isRepeatUntilNotPass()
{
return empty($this->repeatAttempts) && $this->autoRepeat;
}
/**
* @return int
*/
public function getRepeatAttempts()
{
return $this->repeatAttempts;
}
}
| {
"content_hash": "9d4d64bd393780bbe1a4f4f3356b9cc5",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 103,
"avg_line_length": 16.857142857142858,
"alnum_prop": 0.6567796610169492,
"repo_name": "likerRr/urf-battleground",
"id": "d32d8fcb2ad410d65aa991b477e7123e0e0a4c93",
"size": "944",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Managers/LolApi/Traits/AutoRepeatingOnLimitTrait.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "503"
},
{
"name": "PHP",
"bytes": "113457"
}
],
"symlink_target": ""
} |
package com.lightbend.lagom.scaladsl.api.transport
import com.lightbend.lagom.scaladsl.api.security.ServicePrincipal
import play.api.http.HeaderNames
import scala.collection.immutable
/**
* Filter for headers.
*
* This is used to transform transport and protocol headers according to various strategies for protocol and version
* negotiation, as well as authentication.
*/
trait HeaderFilter {
/**
* Transform the given client request.
*
* This will be invoked on all requests outgoing from the client.
*
* @param request The client request header.
* @return The transformed client request header.
*/
def transformClientRequest(request: RequestHeader): RequestHeader
/**
* Transform the given server request.
*
* This will be invoked on all requests incoming to the server.
*
* @param request The server request header.
* @return The transformed server request header.
*/
def transformServerRequest(request: RequestHeader): RequestHeader
/**
* Transform the given server response.
*
* This will be invoked on all responses outgoing from the server.
*
* @param response The server response.
* @param request The transformed server request. Useful for when the response transformation requires information
* from the client.
* @return The transformed server response header.
*/
def transformServerResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader
/**
* Transform the given client response.
*
* This will be invoked on all responses incoming to the client.
*
* @param response The client response.
* @param request The client request. Useful for when the response transformation requires information from the
* client request.
* @return The transformed client response header.
*/
def transformClientResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader
}
object HeaderFilter {
/**
* A noop header transformer, used to deconfigure specific transformers.
*/
val NoHeaderFilter: HeaderFilter = new HeaderFilter() {
override def transformClientRequest(request: RequestHeader): RequestHeader = request
override def transformServerRequest(request: RequestHeader): RequestHeader = request
override def transformServerResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader = response
override def transformClientResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader = response
}
/**
* Create a composite header filter from multiple header filters.
*
* The order that the filters are applied are forward for headers being sent over the wire, and in reverse for
* headers that are received from the wire.
*
* @param filters The filters to create the composite filter from.
* @return The composite filter.
*/
def composite(filters: HeaderFilter*): HeaderFilter = new Composite(filters.toIndexedSeq)
/**
* A composite header filter.
*
* The order that the filters are applied are forward for headers being sent over the wire, and in reverse for
* headers that are received from the wire.
*/
final class Composite(headerFilters: immutable.Seq[HeaderFilter]) extends HeaderFilter {
private val filters: immutable.Seq[HeaderFilter] = headerFilters.flatMap {
case composite: Composite => composite.filters
case other => immutable.Seq(other)
}
def transformClientRequest(request: RequestHeader): RequestHeader = {
filters.foldLeft(request)((req, filter) => filter.transformClientRequest(req))
}
def transformServerRequest(request: RequestHeader): RequestHeader = {
filters.foldRight(request)((filter, req) => filter.transformServerRequest(req))
}
def transformServerResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader = {
filters.foldLeft(response)((resp, filter) => filter.transformServerResponse(resp, request))
}
def transformClientResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader = {
filters.foldRight(response)((filter, resp) => filter.transformClientResponse(response, request))
}
}
}
/**
* Transfers service principal information via the `User-Agent` header.
*
* If using this on a service that serves requests from the outside world, it would be a good idea to block the
* `User-Agent` header in the web facing load balancer/proxy.
*/
//#user-agent-header-filter
object UserAgentHeaderFilter extends HeaderFilter {
override def transformClientRequest(request: RequestHeader): RequestHeader = {
request.principal match {
case Some(principal: ServicePrincipal) =>
request.withHeader(HeaderNames.USER_AGENT, principal.serviceName)
case _ => request
}
}
override def transformServerRequest(request: RequestHeader): RequestHeader = {
request.getHeader(HeaderNames.USER_AGENT) match {
case Some(userAgent) =>
request.withPrincipal(ServicePrincipal.forServiceNamed(userAgent))
case _ =>
request
}
}
override def transformServerResponse(
response: ResponseHeader,
request: RequestHeader
): ResponseHeader = response
override def transformClientResponse(
response: ResponseHeader,
request: RequestHeader
): ResponseHeader = response
}
//#user-agent-header-filter
| {
"content_hash": "5eb9878beb3dd8818c4800a2928e55d1",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 117,
"avg_line_length": 36.078947368421055,
"alnum_prop": 0.7233770970094822,
"repo_name": "rcavalcanti/lagom",
"id": "470ea653fcb5ce9b6097b25eb40fae9abf340989",
"size": "5560",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "service/scaladsl/api/src/main/scala/com/lightbend/lagom/scaladsl/api/transport/HeaderFilter.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "348"
},
{
"name": "HTML",
"bytes": "559"
},
{
"name": "Java",
"bytes": "676881"
},
{
"name": "JavaScript",
"bytes": "48"
},
{
"name": "Protocol Buffer",
"bytes": "1082"
},
{
"name": "Roff",
"bytes": "6976"
},
{
"name": "Scala",
"bytes": "1467678"
},
{
"name": "Shell",
"bytes": "1350"
}
],
"symlink_target": ""
} |
/**
* Module dependencies.
*/
var utils = require('../../utils')
, eyes = require('eyes')
, async = require('async')
, _ = require('lodash');
var EventEmitter = require('events').EventEmitter;
var Device = require('../device');
var Warehouse = require('../../warehouse');
var Container = require('../../container');
/*
Quarry.io - reception
---------------------
*/
module.exports = function(job){
job.prepare = function(done){
/*
this assigns the endpoints we use for the reception server
*/
var reception_endpoints = {
front:job.getaddress('quarry'),
back:job.getaddress('quarry')
}
var stuff = {};
async.series([
function(next){
stuff.receptionserver = Device('reception.server', _.extend({
name:'Reception server: ' + job.id,
id:job.id
}, reception_endpoints));
stuff.receptionserver.on('route', function(message){
console.log('-------------------------------------------');
console.log('reception route:');
eyes.inspect(message);
})
stuff.receptionserver.on('error', function(message){
console.log('-------------------------------------------');
console.log('reception error:');
eyes.inspect(message);
})
stuff.receptionserver.plugin(function(){
reception_endpoints.wireids = stuff.receptionserver.wireids;
next();
})
},
function(next){
job.get_reception_front(function(error, receptionfront){
stuff.receptionfront = receptionfront;
next();
})
},
/*
function(next){
_.each(job.container.attr('middleware') || [], function(middlewareconfig){
var modulename = middlewareconfig.module.replace(/^quarry\./, '').replace(/\./g, '/');
var Module = require('./reception/' + modulename);
var fn = Module(middlewareconfig, {
receptionfront:stuff.receptionfront
})
stuff.receptionserver.use(fn);
})
next();
},
*/
function(next){
job.register_dns(function(){
return reception_endpoints;
})
next();
}
], done)
}
return job;
} | {
"content_hash": "caabe8ac22ad0f269d34d1556bfd46f6",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 96,
"avg_line_length": 22.904761904761905,
"alnum_prop": 0.5002079002079002,
"repo_name": "binocarlos/quarry.io",
"id": "51e5fcee6c8de273a18021523c561f230d37b731",
"size": "3516",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/network/workers/reception.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2457630"
},
{
"name": "Shell",
"bytes": "80"
}
],
"symlink_target": ""
} |
#include <assert.h>
#include "config/aom_config.h"
#include "aom/aom_codec.h"
#include "aom_dsp/bitreader_buffer.h"
#include "aom_ports/mem_ops.h"
#include "av1/common/common.h"
#include "av1/common/obu_util.h"
#include "av1/common/timing.h"
#include "av1/decoder/decoder.h"
#include "av1/decoder/decodeframe.h"
#include "av1/decoder/obu.h"
// Picture prediction structures (0-12 are predefined) in scalability metadata.
typedef enum {
SCALABILITY_L1T2 = 0,
SCALABILITY_L1T3 = 1,
SCALABILITY_L2T1 = 2,
SCALABILITY_L2T2 = 3,
SCALABILITY_L2T3 = 4,
SCALABILITY_S2T1 = 5,
SCALABILITY_S2T2 = 6,
SCALABILITY_S2T3 = 7,
SCALABILITY_L2T1h = 8,
SCALABILITY_L2T2h = 9,
SCALABILITY_L2T3h = 10,
SCALABILITY_S2T1h = 11,
SCALABILITY_S2T2h = 12,
SCALABILITY_S2T3h = 13,
SCALABILITY_SS = 14
} SCALABILITY_STRUCTURES;
aom_codec_err_t aom_get_num_layers_from_operating_point_idc(
int operating_point_idc, unsigned int *number_spatial_layers,
unsigned int *number_temporal_layers) {
// derive number of spatial/temporal layers from operating_point_idc
if (!number_spatial_layers || !number_temporal_layers)
return AOM_CODEC_INVALID_PARAM;
if (operating_point_idc == 0) {
*number_temporal_layers = 1;
*number_spatial_layers = 1;
} else {
*number_spatial_layers = 0;
*number_temporal_layers = 0;
for (int j = 0; j < MAX_NUM_SPATIAL_LAYERS; j++) {
*number_spatial_layers +=
(operating_point_idc >> (j + MAX_NUM_TEMPORAL_LAYERS)) & 0x1;
}
for (int j = 0; j < MAX_NUM_TEMPORAL_LAYERS; j++) {
*number_temporal_layers += (operating_point_idc >> j) & 0x1;
}
}
return AOM_CODEC_OK;
}
static int is_obu_in_current_operating_point(AV1Decoder *pbi,
ObuHeader obu_header) {
if (!pbi->current_operating_point) {
return 1;
}
if ((pbi->current_operating_point >> obu_header.temporal_layer_id) & 0x1 &&
(pbi->current_operating_point >> (obu_header.spatial_layer_id + 8)) &
0x1) {
return 1;
}
return 0;
}
static int byte_alignment(AV1_COMMON *const cm,
struct aom_read_bit_buffer *const rb) {
while (rb->bit_offset & 7) {
if (aom_rb_read_bit(rb)) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
}
return 0;
}
static uint32_t read_temporal_delimiter_obu() { return 0; }
// Returns a boolean that indicates success.
static int read_bitstream_level(BitstreamLevel *bl,
struct aom_read_bit_buffer *rb) {
const uint8_t seq_level_idx = aom_rb_read_literal(rb, LEVEL_BITS);
if (!is_valid_seq_level_idx(seq_level_idx)) return 0;
bl->major = (seq_level_idx >> LEVEL_MINOR_BITS) + LEVEL_MAJOR_MIN;
bl->minor = seq_level_idx & ((1 << LEVEL_MINOR_BITS) - 1);
return 1;
}
// Returns whether two sequence headers are consistent with each other.
// TODO(huisu,wtc@google.com): make sure the code matches the spec exactly.
static int are_seq_headers_consistent(const SequenceHeader *seq_params_old,
const SequenceHeader *seq_params_new) {
return !memcmp(seq_params_old, seq_params_new, sizeof(SequenceHeader));
}
// On success, sets pbi->sequence_header_ready to 1 and returns the number of
// bytes read from 'rb'.
// On failure, sets pbi->common.error.error_code and returns 0.
static uint32_t read_sequence_header_obu(AV1Decoder *pbi,
struct aom_read_bit_buffer *rb) {
AV1_COMMON *const cm = &pbi->common;
const uint32_t saved_bit_offset = rb->bit_offset;
// Verify rb has been configured to report errors.
assert(rb->error_handler);
// Use a local variable to store the information as we decode. At the end,
// if no errors have occurred, cm->seq_params is updated.
SequenceHeader sh = cm->seq_params;
SequenceHeader *const seq_params = &sh;
seq_params->profile = av1_read_profile(rb);
if (seq_params->profile > CONFIG_MAX_DECODE_PROFILE) {
cm->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
return 0;
}
// Still picture or not
seq_params->still_picture = aom_rb_read_bit(rb);
seq_params->reduced_still_picture_hdr = aom_rb_read_bit(rb);
// Video must have reduced_still_picture_hdr = 0
if (!seq_params->still_picture && seq_params->reduced_still_picture_hdr) {
cm->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
return 0;
}
if (seq_params->reduced_still_picture_hdr) {
cm->timing_info_present = 0;
seq_params->decoder_model_info_present_flag = 0;
seq_params->display_model_info_present_flag = 0;
seq_params->operating_points_cnt_minus_1 = 0;
seq_params->operating_point_idc[0] = 0;
if (!read_bitstream_level(&seq_params->level[0], rb)) {
cm->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
return 0;
}
seq_params->tier[0] = 0;
cm->op_params[0].decoder_model_param_present_flag = 0;
cm->op_params[0].display_model_param_present_flag = 0;
} else {
cm->timing_info_present = aom_rb_read_bit(rb); // timing_info_present_flag
if (cm->timing_info_present) {
av1_read_timing_info_header(cm, rb);
seq_params->decoder_model_info_present_flag = aom_rb_read_bit(rb);
if (seq_params->decoder_model_info_present_flag)
av1_read_decoder_model_info(cm, rb);
} else {
seq_params->decoder_model_info_present_flag = 0;
}
seq_params->display_model_info_present_flag = aom_rb_read_bit(rb);
seq_params->operating_points_cnt_minus_1 =
aom_rb_read_literal(rb, OP_POINTS_CNT_MINUS_1_BITS);
for (int i = 0; i < seq_params->operating_points_cnt_minus_1 + 1; i++) {
seq_params->operating_point_idc[i] =
aom_rb_read_literal(rb, OP_POINTS_IDC_BITS);
if (!read_bitstream_level(&seq_params->level[i], rb)) {
cm->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
return 0;
}
// This is the seq_level_idx[i] > 7 check in the spec. seq_level_idx 7
// is equivalent to level 3.3.
if (seq_params->level[i].major > 3)
seq_params->tier[i] = aom_rb_read_bit(rb);
else
seq_params->tier[i] = 0;
if (seq_params->decoder_model_info_present_flag) {
cm->op_params[i].decoder_model_param_present_flag = aom_rb_read_bit(rb);
if (cm->op_params[i].decoder_model_param_present_flag)
av1_read_op_parameters_info(cm, rb, i);
} else {
cm->op_params[i].decoder_model_param_present_flag = 0;
}
if (cm->timing_info_present &&
(cm->timing_info.equal_picture_interval ||
cm->op_params[i].decoder_model_param_present_flag)) {
cm->op_params[i].bitrate = max_level_bitrate(
seq_params->profile,
major_minor_to_seq_level_idx(seq_params->level[i]),
seq_params->tier[i]);
// Level with seq_level_idx = 31 returns a high "dummy" bitrate to pass
// the check
if (cm->op_params[i].bitrate == 0)
aom_internal_error(&cm->error, AOM_CODEC_UNSUP_BITSTREAM,
"AV1 does not support this combination of "
"profile, level, and tier.");
// Buffer size in bits/s is bitrate in bits/s * 1 s
cm->op_params[i].buffer_size = cm->op_params[i].bitrate;
}
if (cm->timing_info_present && cm->timing_info.equal_picture_interval &&
!cm->op_params[i].decoder_model_param_present_flag) {
// When the decoder_model_parameters are not sent for this op, set
// the default ones that can be used with the resource availability mode
cm->op_params[i].decoder_buffer_delay = 70000;
cm->op_params[i].encoder_buffer_delay = 20000;
cm->op_params[i].low_delay_mode_flag = 0;
}
if (seq_params->display_model_info_present_flag) {
cm->op_params[i].display_model_param_present_flag = aom_rb_read_bit(rb);
if (cm->op_params[i].display_model_param_present_flag) {
cm->op_params[i].initial_display_delay =
aom_rb_read_literal(rb, 4) + 1;
if (cm->op_params[i].initial_display_delay > 10)
aom_internal_error(
&cm->error, AOM_CODEC_UNSUP_BITSTREAM,
"AV1 does not support more than 10 decoded frames delay");
} else {
cm->op_params[i].initial_display_delay = 10;
}
} else {
cm->op_params[i].display_model_param_present_flag = 0;
cm->op_params[i].initial_display_delay = 10;
}
}
}
// This decoder supports all levels. Choose operating point provided by
// external means
int operating_point = pbi->operating_point;
if (operating_point < 0 ||
operating_point > seq_params->operating_points_cnt_minus_1)
operating_point = 0;
pbi->current_operating_point =
seq_params->operating_point_idc[operating_point];
if (aom_get_num_layers_from_operating_point_idc(
pbi->current_operating_point, &cm->number_spatial_layers,
&cm->number_temporal_layers) != AOM_CODEC_OK) {
cm->error.error_code = AOM_CODEC_ERROR;
return 0;
}
av1_read_sequence_header(cm, rb, seq_params);
av1_read_color_config(rb, pbi->allow_lowbitdepth, seq_params, &cm->error);
if (!(seq_params->subsampling_x == 0 && seq_params->subsampling_y == 0) &&
!(seq_params->subsampling_x == 1 && seq_params->subsampling_y == 1) &&
!(seq_params->subsampling_x == 1 && seq_params->subsampling_y == 0)) {
aom_internal_error(&cm->error, AOM_CODEC_UNSUP_BITSTREAM,
"Only 4:4:4, 4:2:2 and 4:2:0 are currently supported, "
"%d %d subsampling is not supported.\n",
seq_params->subsampling_x, seq_params->subsampling_y);
}
seq_params->film_grain_params_present = aom_rb_read_bit(rb);
if (av1_check_trailing_bits(pbi, rb) != 0) {
// cm->error.error_code is already set.
return 0;
}
// If a sequence header has been decoded before, we check if the new
// one is consistent with the old one.
if (pbi->sequence_header_ready) {
if (!are_seq_headers_consistent(&cm->seq_params, seq_params))
pbi->sequence_header_changed = 1;
}
cm->seq_params = *seq_params;
pbi->sequence_header_ready = 1;
return ((rb->bit_offset - saved_bit_offset + 7) >> 3);
}
// On success, returns the frame header size. On failure, calls
// aom_internal_error and does not return.
static uint32_t read_frame_header_obu(AV1Decoder *pbi,
struct aom_read_bit_buffer *rb,
const uint8_t *data,
const uint8_t **p_data_end,
int trailing_bits_present) {
return av1_decode_frame_headers_and_setup(pbi, rb, data, p_data_end,
trailing_bits_present);
}
static int32_t read_tile_group_header(AV1Decoder *pbi,
struct aom_read_bit_buffer *rb,
int *start_tile, int *end_tile,
int tile_start_implicit) {
AV1_COMMON *const cm = &pbi->common;
uint32_t saved_bit_offset = rb->bit_offset;
int tile_start_and_end_present_flag = 0;
const int num_tiles = pbi->common.tile_rows * pbi->common.tile_cols;
if (!pbi->common.large_scale_tile && num_tiles > 1) {
tile_start_and_end_present_flag = aom_rb_read_bit(rb);
}
if (pbi->common.large_scale_tile || num_tiles == 1 ||
!tile_start_and_end_present_flag) {
*start_tile = 0;
*end_tile = num_tiles - 1;
return ((rb->bit_offset - saved_bit_offset + 7) >> 3);
}
if (tile_start_implicit && tile_start_and_end_present_flag) {
aom_internal_error(
&cm->error, AOM_CODEC_UNSUP_BITSTREAM,
"For OBU_FRAME type obu tile_start_and_end_present_flag must be 0");
return -1;
}
*start_tile =
aom_rb_read_literal(rb, cm->log2_tile_rows + cm->log2_tile_cols);
*end_tile = aom_rb_read_literal(rb, cm->log2_tile_rows + cm->log2_tile_cols);
return ((rb->bit_offset - saved_bit_offset + 7) >> 3);
}
static uint32_t read_one_tile_group_obu(
AV1Decoder *pbi, struct aom_read_bit_buffer *rb, int is_first_tg,
const uint8_t *data, const uint8_t *data_end, const uint8_t **p_data_end,
int *is_last_tg, int tile_start_implicit) {
AV1_COMMON *const cm = &pbi->common;
int start_tile, end_tile;
int32_t header_size, tg_payload_size;
assert((rb->bit_offset & 7) == 0);
assert(rb->bit_buffer + aom_rb_bytes_read(rb) == data);
header_size = read_tile_group_header(pbi, rb, &start_tile, &end_tile,
tile_start_implicit);
if (header_size == -1 || byte_alignment(cm, rb)) return 0;
if (start_tile > end_tile) return header_size;
data += header_size;
av1_decode_tg_tiles_and_wrapup(pbi, data, data_end, p_data_end, start_tile,
end_tile, is_first_tg);
tg_payload_size = (uint32_t)(*p_data_end - data);
// TODO(shan): For now, assume all tile groups received in order
*is_last_tg = end_tile == cm->tile_rows * cm->tile_cols - 1;
return header_size + tg_payload_size;
}
static void alloc_tile_list_buffer(AV1Decoder *pbi) {
// TODO(yunqing): for now, copy each tile's decoded YUV data directly to the
// output buffer. This needs to be modified according to the application
// requirement.
AV1_COMMON *const cm = &pbi->common;
const int tile_width_in_pixels = cm->tile_width * MI_SIZE;
const int tile_height_in_pixels = cm->tile_height * MI_SIZE;
const int ssy = cm->seq_params.subsampling_y;
const int ssx = cm->seq_params.subsampling_x;
const int num_planes = av1_num_planes(cm);
const size_t yplane_tile_size = tile_height_in_pixels * tile_width_in_pixels;
const size_t uvplane_tile_size =
(num_planes > 1)
? (tile_height_in_pixels >> ssy) * (tile_width_in_pixels >> ssx)
: 0;
const size_t tile_size = (cm->seq_params.use_highbitdepth ? 2 : 1) *
(yplane_tile_size + 2 * uvplane_tile_size);
pbi->tile_list_size = tile_size * (pbi->tile_count_minus_1 + 1);
if (pbi->tile_list_size > pbi->buffer_sz) {
if (pbi->tile_list_output != NULL) aom_free(pbi->tile_list_output);
pbi->tile_list_output = NULL;
pbi->tile_list_output = (uint8_t *)aom_memalign(32, pbi->tile_list_size);
if (pbi->tile_list_output == NULL)
aom_internal_error(&cm->error, AOM_CODEC_MEM_ERROR,
"Failed to allocate the tile list output buffer");
pbi->buffer_sz = pbi->tile_list_size;
}
}
static void copy_decoded_tile_to_tile_list_buffer(AV1Decoder *pbi,
uint8_t **output) {
AV1_COMMON *const cm = &pbi->common;
const int tile_width_in_pixels = cm->tile_width * MI_SIZE;
const int tile_height_in_pixels = cm->tile_height * MI_SIZE;
const int ssy = cm->seq_params.subsampling_y;
const int ssx = cm->seq_params.subsampling_x;
const int num_planes = av1_num_planes(cm);
// Copy decoded tile to the tile list output buffer.
YV12_BUFFER_CONFIG *cur_frame = get_frame_new_buffer(cm);
const int mi_row = pbi->dec_tile_row * cm->tile_height;
const int mi_col = pbi->dec_tile_col * cm->tile_width;
const int is_hbd = (cur_frame->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0;
uint8_t *bufs[MAX_MB_PLANE] = { NULL, NULL, NULL };
int strides[MAX_MB_PLANE] = { 0, 0, 0 };
int plane;
for (plane = 0; plane < num_planes; ++plane) {
int shift_x = plane > 0 ? ssx : 0;
int shift_y = plane > 0 ? ssy : 0;
bufs[plane] = cur_frame->buffers[plane];
strides[plane] =
(plane > 0) ? cur_frame->strides[1] : cur_frame->strides[0];
bufs[plane] += mi_row * (MI_SIZE >> shift_y) * strides[plane] +
mi_col * (MI_SIZE >> shift_x);
if (is_hbd) {
bufs[plane] = (uint8_t *)CONVERT_TO_SHORTPTR(bufs[plane]);
strides[plane] *= 2;
}
int w, h;
w = (plane > 0 && shift_x > 0) ? ((tile_width_in_pixels + 1) >> shift_x)
: tile_width_in_pixels;
w *= (1 + is_hbd);
h = (plane > 0 && shift_y > 0) ? ((tile_height_in_pixels + 1) >> shift_y)
: tile_height_in_pixels;
int j;
for (j = 0; j < h; ++j) {
memcpy(*output, bufs[plane], w);
bufs[plane] += strides[plane];
*output += w;
}
}
}
// Only called while large_scale_tile = 1.
static uint32_t read_and_decode_one_tile_list(AV1Decoder *pbi,
struct aom_read_bit_buffer *rb,
const uint8_t *data,
const uint8_t *data_end,
const uint8_t **p_data_end,
int *frame_decoding_finished) {
AV1_COMMON *const cm = &pbi->common;
uint32_t tile_list_payload_size = 0;
const int num_tiles = cm->tile_cols * cm->tile_rows;
const int start_tile = 0;
const int end_tile = num_tiles - 1;
int i = 0;
// Process the tile list info.
pbi->output_frame_width_in_tiles_minus_1 = aom_rb_read_literal(rb, 8);
pbi->output_frame_height_in_tiles_minus_1 = aom_rb_read_literal(rb, 8);
pbi->tile_count_minus_1 = aom_rb_read_literal(rb, 16);
if (pbi->tile_count_minus_1 > MAX_TILES - 1) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return 0;
}
// Allocate output frame buffer for the tile list.
alloc_tile_list_buffer(pbi);
uint32_t tile_list_info_bytes = 4;
tile_list_payload_size += tile_list_info_bytes;
data += tile_list_info_bytes;
uint8_t *output = pbi->tile_list_output;
for (i = 0; i <= pbi->tile_count_minus_1; i++) {
// Process 1 tile.
// Reset the bit reader.
rb->bit_offset = 0;
rb->bit_buffer = data;
// Read out the tile info.
uint32_t tile_info_bytes = 5;
// Set reference for each tile.
int ref_idx = aom_rb_read_literal(rb, 8);
if (ref_idx >= MAX_EXTERNAL_REFERENCES) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return 0;
}
av1_set_reference_dec(cm, 0, 1, &pbi->ext_refs.refs[ref_idx]);
pbi->dec_tile_row = aom_rb_read_literal(rb, 8);
pbi->dec_tile_col = aom_rb_read_literal(rb, 8);
if (pbi->dec_tile_row < 0 || pbi->dec_tile_col < 0 ||
pbi->dec_tile_row >= cm->tile_rows ||
pbi->dec_tile_col >= cm->tile_cols) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return 0;
}
pbi->coded_tile_data_size = aom_rb_read_literal(rb, 16) + 1;
data += tile_info_bytes;
if ((size_t)(data_end - data) < pbi->coded_tile_data_size) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return 0;
}
av1_decode_tg_tiles_and_wrapup(pbi, data, data + pbi->coded_tile_data_size,
p_data_end, start_tile, end_tile, 0);
uint32_t tile_payload_size = (uint32_t)(*p_data_end - data);
tile_list_payload_size += tile_info_bytes + tile_payload_size;
// Update data ptr for next tile decoding.
data = *p_data_end;
assert(data <= data_end);
// Copy the decoded tile to the tile list output buffer.
copy_decoded_tile_to_tile_list_buffer(pbi, &output);
}
*frame_decoding_finished = 1;
return tile_list_payload_size;
}
static void read_metadata_itut_t35(const uint8_t *data, size_t sz) {
struct aom_read_bit_buffer rb = { data, data + sz, 0, NULL, NULL };
for (size_t i = 0; i < sz; i++) {
aom_rb_read_literal(&rb, 8);
}
}
static void read_metadata_hdr_cll(const uint8_t *data, size_t sz) {
struct aom_read_bit_buffer rb = { data, data + sz, 0, NULL, NULL };
aom_rb_read_literal(&rb, 16); // max_cll
aom_rb_read_literal(&rb, 16); // max_fall
}
static void read_metadata_hdr_mdcv(const uint8_t *data, size_t sz) {
struct aom_read_bit_buffer rb = { data, data + sz, 0, NULL, NULL };
for (int i = 0; i < 3; i++) {
aom_rb_read_literal(&rb, 16); // primary_i_chromaticity_x
aom_rb_read_literal(&rb, 16); // primary_i_chromaticity_y
}
aom_rb_read_literal(&rb, 16); // white_point_chromaticity_x
aom_rb_read_literal(&rb, 16); // white_point_chromaticity_y
aom_rb_read_unsigned_literal(&rb, 32); // luminance_max
aom_rb_read_unsigned_literal(&rb, 32); // luminance_min
}
static void scalability_structure(struct aom_read_bit_buffer *rb) {
int spatial_layers_cnt = aom_rb_read_literal(rb, 2);
int spatial_layer_dimensions_present_flag = aom_rb_read_bit(rb);
int spatial_layer_description_present_flag = aom_rb_read_bit(rb);
int temporal_group_description_present_flag = aom_rb_read_bit(rb);
aom_rb_read_literal(rb, 3); // reserved
if (spatial_layer_dimensions_present_flag) {
int i;
for (i = 0; i < spatial_layers_cnt + 1; i++) {
aom_rb_read_literal(rb, 16);
aom_rb_read_literal(rb, 16);
}
}
if (spatial_layer_description_present_flag) {
int i;
for (i = 0; i < spatial_layers_cnt + 1; i++) {
aom_rb_read_literal(rb, 8);
}
}
if (temporal_group_description_present_flag) {
int i, j, temporal_group_size;
temporal_group_size = aom_rb_read_literal(rb, 8);
for (i = 0; i < temporal_group_size; i++) {
aom_rb_read_literal(rb, 3);
aom_rb_read_bit(rb);
aom_rb_read_bit(rb);
int temporal_group_ref_cnt = aom_rb_read_literal(rb, 3);
for (j = 0; j < temporal_group_ref_cnt; j++) {
aom_rb_read_literal(rb, 8);
}
}
}
}
static void read_metadata_scalability(const uint8_t *data, size_t sz) {
struct aom_read_bit_buffer rb = { data, data + sz, 0, NULL, NULL };
int scalability_mode_idc = aom_rb_read_literal(&rb, 8);
if (scalability_mode_idc == SCALABILITY_SS) {
scalability_structure(&rb);
}
}
static void read_metadata_timecode(const uint8_t *data, size_t sz) {
struct aom_read_bit_buffer rb = { data, data + sz, 0, NULL, NULL };
aom_rb_read_literal(&rb, 5); // counting_type f(5)
int full_timestamp_flag = aom_rb_read_bit(&rb); // full_timestamp_flag f(1)
aom_rb_read_bit(&rb); // discontinuity_flag (f1)
aom_rb_read_bit(&rb); // cnt_dropped_flag f(1)
aom_rb_read_literal(&rb, 9); // n_frames f(9)
if (full_timestamp_flag) {
aom_rb_read_literal(&rb, 6); // seconds_value f(6)
aom_rb_read_literal(&rb, 6); // minutes_value f(6)
aom_rb_read_literal(&rb, 5); // hours_value f(5)
} else {
int seconds_flag = aom_rb_read_bit(&rb); // seconds_flag f(1)
if (seconds_flag) {
aom_rb_read_literal(&rb, 6); // seconds_value f(6)
int minutes_flag = aom_rb_read_bit(&rb); // minutes_flag f(1)
if (minutes_flag) {
aom_rb_read_literal(&rb, 6); // minutes_value f(6)
int hours_flag = aom_rb_read_bit(&rb); // hours_flag f(1)
if (hours_flag) {
aom_rb_read_literal(&rb, 5); // hours_value f(5)
}
}
}
}
// time_offset_length f(5)
int time_offset_length = aom_rb_read_literal(&rb, 5);
if (time_offset_length) {
aom_rb_read_literal(&rb, time_offset_length); // f(time_offset_length)
}
}
static size_t read_metadata(const uint8_t *data, size_t sz) {
size_t type_length;
uint64_t type_value;
OBU_METADATA_TYPE metadata_type;
if (aom_uleb_decode(data, sz, &type_value, &type_length) < 0) {
return sz;
}
metadata_type = (OBU_METADATA_TYPE)type_value;
if (metadata_type == OBU_METADATA_TYPE_ITUT_T35) {
read_metadata_itut_t35(data + type_length, sz - type_length);
} else if (metadata_type == OBU_METADATA_TYPE_HDR_CLL) {
read_metadata_hdr_cll(data + type_length, sz - type_length);
} else if (metadata_type == OBU_METADATA_TYPE_HDR_MDCV) {
read_metadata_hdr_mdcv(data + type_length, sz - type_length);
} else if (metadata_type == OBU_METADATA_TYPE_SCALABILITY) {
read_metadata_scalability(data + type_length, sz - type_length);
} else if (metadata_type == OBU_METADATA_TYPE_TIMECODE) {
read_metadata_timecode(data + type_length, sz - type_length);
}
return sz;
}
// On success, returns a boolean that indicates whether the decoding of the
// current frame is finished. On failure, sets cm->error.error_code and
// returns -1.
int aom_decode_frame_from_obus(struct AV1Decoder *pbi, const uint8_t *data,
const uint8_t *data_end,
const uint8_t **p_data_end) {
AV1_COMMON *const cm = &pbi->common;
int frame_decoding_finished = 0;
int is_first_tg_obu_received = 1;
uint32_t frame_header_size = 0;
ObuHeader obu_header;
memset(&obu_header, 0, sizeof(obu_header));
pbi->seen_frame_header = 0;
if (data_end < data) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
// Reset pbi->camera_frame_header_ready to 0 if cm->large_scale_tile = 0.
if (!cm->large_scale_tile) pbi->camera_frame_header_ready = 0;
// decode frame as a series of OBUs
while (!frame_decoding_finished && !cm->error.error_code) {
struct aom_read_bit_buffer rb;
size_t payload_size = 0;
size_t decoded_payload_size = 0;
size_t obu_payload_offset = 0;
size_t bytes_read = 0;
const size_t bytes_available = data_end - data;
if (bytes_available == 0 && !pbi->seen_frame_header) {
*p_data_end = data;
cm->error.error_code = AOM_CODEC_OK;
break;
}
aom_codec_err_t status =
aom_read_obu_header_and_size(data, bytes_available, cm->is_annexb,
&obu_header, &payload_size, &bytes_read);
if (status != AOM_CODEC_OK) {
cm->error.error_code = status;
return -1;
}
// Record obu size header information.
pbi->obu_size_hdr.data = data + obu_header.size;
pbi->obu_size_hdr.size = bytes_read - obu_header.size;
// Note: aom_read_obu_header_and_size() takes care of checking that this
// doesn't cause 'data' to advance past 'data_end'.
data += bytes_read;
if ((size_t)(data_end - data) < payload_size) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
cm->temporal_layer_id = obu_header.temporal_layer_id;
cm->spatial_layer_id = obu_header.spatial_layer_id;
if (obu_header.type != OBU_TEMPORAL_DELIMITER &&
obu_header.type != OBU_SEQUENCE_HEADER &&
obu_header.type != OBU_PADDING) {
// don't decode obu if it's not in current operating mode
if (!is_obu_in_current_operating_point(pbi, obu_header)) {
data += payload_size;
continue;
}
}
av1_init_read_bit_buffer(pbi, &rb, data, data + payload_size);
switch (obu_header.type) {
case OBU_TEMPORAL_DELIMITER:
decoded_payload_size = read_temporal_delimiter_obu();
pbi->seen_frame_header = 0;
break;
case OBU_SEQUENCE_HEADER:
decoded_payload_size = read_sequence_header_obu(pbi, &rb);
if (cm->error.error_code != AOM_CODEC_OK) return -1;
break;
case OBU_FRAME_HEADER:
case OBU_REDUNDANT_FRAME_HEADER:
case OBU_FRAME:
// Only decode first frame header received
if (!pbi->seen_frame_header ||
(cm->large_scale_tile && !pbi->camera_frame_header_ready)) {
frame_header_size = read_frame_header_obu(
pbi, &rb, data, p_data_end, obu_header.type != OBU_FRAME);
pbi->seen_frame_header = 1;
if (!pbi->ext_tile_debug && cm->large_scale_tile)
pbi->camera_frame_header_ready = 1;
} else {
// TODO(wtc): Verify that the frame_header_obu is identical to the
// original frame_header_obu. For now just skip frame_header_size
// bytes in the bit buffer.
if (frame_header_size > payload_size) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
assert(rb.bit_offset == 0);
rb.bit_offset = 8 * frame_header_size;
}
decoded_payload_size = frame_header_size;
pbi->frame_header_size = frame_header_size;
if (cm->show_existing_frame) {
if (obu_header.type == OBU_FRAME) {
cm->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
return -1;
}
frame_decoding_finished = 1;
pbi->seen_frame_header = 0;
break;
}
// In large scale tile coding, decode the common camera frame header
// before any tile list OBU.
if (!pbi->ext_tile_debug && pbi->camera_frame_header_ready) {
frame_decoding_finished = 1;
// Skip the rest of the frame data.
decoded_payload_size = payload_size;
// Update data_end.
*p_data_end = data_end;
break;
}
if (obu_header.type != OBU_FRAME) break;
obu_payload_offset = frame_header_size;
// Byte align the reader before reading the tile group.
if (byte_alignment(cm, &rb)) return -1;
AOM_FALLTHROUGH_INTENDED; // fall through to read tile group.
case OBU_TILE_GROUP:
if (!pbi->seen_frame_header) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
if (obu_payload_offset > payload_size) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
decoded_payload_size += read_one_tile_group_obu(
pbi, &rb, is_first_tg_obu_received, data + obu_payload_offset,
data + payload_size, p_data_end, &frame_decoding_finished,
obu_header.type == OBU_FRAME);
is_first_tg_obu_received = 0;
if (frame_decoding_finished) pbi->seen_frame_header = 0;
break;
case OBU_METADATA:
decoded_payload_size = read_metadata(data, payload_size);
break;
case OBU_TILE_LIST:
if (CONFIG_NORMAL_TILE_MODE) {
cm->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
return -1;
}
// This OBU type is purely for the large scale tile coding mode.
// The common camera frame header has to be already decoded.
if (!pbi->camera_frame_header_ready) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
cm->large_scale_tile = 1;
av1_set_single_tile_decoding_mode(cm);
decoded_payload_size =
read_and_decode_one_tile_list(pbi, &rb, data, data + payload_size,
p_data_end, &frame_decoding_finished);
if (cm->error.error_code != AOM_CODEC_OK) return -1;
break;
case OBU_PADDING:
default:
// Skip unrecognized OBUs
decoded_payload_size = payload_size;
break;
}
// Check that the signalled OBU size matches the actual amount of data read
if (decoded_payload_size > payload_size) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
// If there are extra padding bytes, they should all be zero
while (decoded_payload_size < payload_size) {
uint8_t padding_byte = data[decoded_payload_size++];
if (padding_byte != 0) {
cm->error.error_code = AOM_CODEC_CORRUPT_FRAME;
return -1;
}
}
data += payload_size;
}
return frame_decoding_finished;
}
| {
"content_hash": "111031334044c658cee2542909ee03eb",
"timestamp": "",
"source": "github",
"line_count": 830,
"max_line_length": 80,
"avg_line_length": 37.80843373493976,
"alnum_prop": 0.6008412733819827,
"repo_name": "GrokImageCompression/aom",
"id": "44ecf818e7c8de4495b69e4a50cf0a98a2d235e5",
"size": "31909",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "av1/decoder/obu.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "663387"
},
{
"name": "C",
"bytes": "11856562"
},
{
"name": "C++",
"bytes": "1731046"
},
{
"name": "CMake",
"bytes": "203322"
},
{
"name": "Makefile",
"bytes": "122220"
},
{
"name": "Objective-C",
"bytes": "398959"
},
{
"name": "Perl",
"bytes": "73243"
},
{
"name": "Perl 6",
"bytes": "101675"
},
{
"name": "Python",
"bytes": "5034"
},
{
"name": "Shell",
"bytes": "128937"
}
],
"symlink_target": ""
} |
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Md2Module } from 'md2';
import { AppComponent } from './app.component';
import { RawDataComponent } from './components/rawdata/rawdata.component';
import { StatusComponent } from './components/status/status.component';
import { ReversePipe } from './pipes/reverse.pipe';
import { MQTTService } from './services/mqtt';
import { ConfigService } from './services/config/config.service';
@NgModule({
declarations: [
AppComponent,
RawDataComponent,
StatusComponent,
ReversePipe
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule,
Md2Module,
BrowserAnimationsModule
],
providers: [
MQTTService,
ConfigService],
bootstrap: [AppComponent]
})
export class AppModule { }
| {
"content_hash": "51e8a1299774cf6f3dc87f6685b5eacc",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 79,
"avg_line_length": 31.5,
"alnum_prop": 0.6772486772486772,
"repo_name": "Franco-Poveda/test-mqtt-ng2",
"id": "4b5119edefe053013df777f7b6ddd4311b0d944c",
"size": "1134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/app.module.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "754"
},
{
"name": "HTML",
"bytes": "3562"
},
{
"name": "JavaScript",
"bytes": "1996"
},
{
"name": "TypeScript",
"bytes": "24385"
}
],
"symlink_target": ""
} |
/* Smartresize.js - https://gist.github.com/randylien/5683851*/
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize'); | {
"content_hash": "eb66a429a097d27c656d1ec911e9a604",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 101,
"avg_line_length": 29.551724137931036,
"alnum_prop": 0.5647607934655776,
"repo_name": "teamgivn/givnapp",
"id": "f346824a6a7ddbddacefddfc61b2787a3b2c7546",
"size": "857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/static/js/vendor/smartresize.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "210090"
},
{
"name": "JavaScript",
"bytes": "560673"
},
{
"name": "Python",
"bytes": "18897"
},
{
"name": "Shell",
"bytes": "2557"
}
],
"symlink_target": ""
} |
#pragma once
#include <functional>
#include <iostream>
#include <string>
#include <vector>
#include <initializer_list>
class TestRunner
{
public:
TestRunner(std::initializer_list<std::function<void ()>> functions);
~TestRunner(){}
static int runTests(const std::string& name = "");
static void registerTests(std::initializer_list<std::function<void ()>> functions);
static void incrementAssertionCount();
static void incrementFailedAssertions();
private:
int internalRunTests(const std::string& name);
void internalRegisterTests(std::initializer_list<std::function<void ()>> functions);
void internalIncrementAssertionCount();
void internalIncrementFailedAssertions();
static TestRunner& testRunner();
std::vector<std::function<void ()>> testFunctions;
size_t failedAssertions;
size_t totalAssertions;
void resetAssertionCounts();
};
inline TestRunner::TestRunner(std::initializer_list<std::function<void ()>> functions)
: failedAssertions(0), totalAssertions(0)
{
registerTests(functions);
}
inline int TestRunner::runTests(const std::string& name)
{
return testRunner().internalRunTests(name);
}
inline int TestRunner::internalRunTests(const std::string& name)
{
resetAssertionCounts();
size_t failed = 0;
size_t counter = 0;
const size_t total = testFunctions.size();
for(auto&& function : testFunctions)
{
function();
++counter;
if(failedAssertions > 0)
{
std::cout << "Test Function FAILED in test "
<< counter << std::endl << std::endl;
++failed;
}
resetAssertionCounts();
}
std::cout << total - failed << " tests passed out of " << total << " tests in "
<< name << "." << std::endl;
return (int)failed;
}
inline void TestRunner::registerTests(std::initializer_list<std::function<void ()>> functions)
{
testRunner().internalRegisterTests(functions);
}
inline void TestRunner::internalRegisterTests(std::initializer_list<std::function<void ()>> functions)
{
for(auto&& function : functions)
testFunctions.push_back(function);
}
inline void TestRunner::incrementAssertionCount()
{
testRunner().internalIncrementAssertionCount();
}
inline void TestRunner::internalIncrementAssertionCount()
{
++totalAssertions;
}
inline void TestRunner::incrementFailedAssertions()
{
testRunner().internalIncrementFailedAssertions();
}
inline void TestRunner::internalIncrementFailedAssertions()
{
++failedAssertions;
}
inline void TestRunner::resetAssertionCounts()
{
totalAssertions = 0;
failedAssertions = 0;
}
inline TestRunner& TestRunner::testRunner()
{
static TestRunner singleton({});
return singleton;
}
#ifdef assertTrue
#undef assertTrue
#endif
#define assertTrue(expression) \
if(!(expression)) \
{ \
std::cout << "Assertion failed: " << #expression << "." << std::endl \
<< " Expected true but was false (" << (expression) << ")" \
<< std::endl << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef assertFalse
#undef assertFalse
#endif
#define assertFalse(expression) \
if(expression) \
{ \
std::cout << "Assertion failed: " << #expression << "." << std::endl \
<< " Expected false but was true (" << (expression) << ")" \
<< std::endl << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef assertEqual
#undef assertEqual
#endif
#define assertEqual(lhs, rhs) \
if(!((lhs) == (rhs))) \
{ \
std::cout << "Assertion failed: " << #lhs << " == " << #rhs << "." << std::endl \
<< " Expected equal but were unequal (" << (lhs) << ", " << (rhs) << ")" \
<< std::endl << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef assertNotEqual
#undef assertNotEqual
#endif
#define assertNotEqual(lhs, rhs) \
if(!((lhs) != (rhs))) \
{ \
std::cout << "Assertion failed: " << #lhs << " != " << #rhs \
<< ". Expected not equal but were equal (" << (lhs) << ", " << (rhs) << ")" << std::endl; \
std::cout << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef assertNotNull
#undef assertNotNull
#endif
#define assertNotNull(expression) \
assertFalse(nullptr == (expression))
#ifdef assertNull
#undef assertNull
#endif
#define assertNull(expression) \
assertTrue(nullptr == (expression))
#ifdef assertGreaterThan
#undef assertGreaterThan
#endif
#define assertGreaterThan(lhs, rhs) \
if(!((lhs) > (rhs))) \
{ \
std::cout << "Assertion failed: " << #lhs << " > " #rhs \
<< ". Expected greater than but was not (" << (lhs) << ", " << (rhs) << ")" << std::endl; \
std::cout << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef assertLessThan
#undef assertLessThan
#endif
#define assertLessThan(lhs, rhs) \
if(!((lhs) < (rhs))) \
{ \
std::cout << "Assertion failed: " << #lhs << " < " #rhs \
<< ". Expected less than but was not (" << (lhs) << ", " << (rhs) << ")" << std::endl; \
std::cout << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef assertGreaterThanOrEqual
#undef assertGreaterThanOrEqual
#endif
#define assertGreaterThanOrEqual(lhs, rhs) \
if(!((lhs) >= (rhs))) \
{ \
std::cout << "Assertion failed: " << #lhs << " >= " #rhs \
<< ". Expected greater or equal than but was not (" << (lhs) << ", " << (rhs) << ")" << std::endl; \
std::cout << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef assertLessThanOrEqual
#undef assertLessThanOrEqual
#endif
#define assertLessThanOrEqual(lhs, rhs) \
if(!((lhs) <= (rhs))) \
{ \
std::cout << "Assertion failed: " << #lhs << " <= " #rhs \
<< ". Expected less than or equal but was not (" << (lhs) << ", " << (rhs) << ")" << std::endl; \
std::cout << " At: " << __FILE_NAME << " " << __LINE_NUMBER << std::endl; \
TestRunner::incrementFailedAssertions(); \
} \
TestRunner::incrementAssertionCount();
#ifdef __LINE_NUMBER
#undef __LINE_NUMBER
#endif
#define __LINE_NUMBER \
__LINE__
#ifdef __FILE_NAME
#undef __FILE_NAME
#endif
#define __FILE_NAME \
__FILE__
#ifdef DEFINE_TEST_FUNCTION
#undef DEFINE_TEST_FUNCTION
#endif
#define DEFINE_TEST_FUNCTION(...) \
REGISTER_TEST_FUNCTIONS( \
[]() \
{ \
__VA_ARGS__ \
} \
)
#ifdef __EXPANDED_LINE_NUMBER
#undef __EXPANDED_LINE_NUMBER
#endif
#define __EXPANDED_LINE_NUMBER(x) \
__zz_ ## x
#ifdef ___EXPANDED_LINE_NUMBER
#undef ___EXPANDED_LINE_NUMBER
#endif
#define ___EXPANDED_LINE_NUMBER(x) \
__EXPANDED_LINE_NUMBER(x)
#ifdef REGISTER_TEST_FUNCTIONS
#undef REGISTER_TEST_FUNCTIONS
#endif
#define REGISTER_TEST_FUNCTIONS(...) \
static const TestRunner ___EXPANDED_LINE_NUMBER(__LINE__) ## _zzStaticTestRunner \
= TestRunner({__VA_ARGS__});
#ifdef RUN_TESTS_MAIN
#undef RUN_TESTS_MAIN
#endif
#define RUN_TESTS_MAIN(name) \
int main(int argc, char* argv[]) \
{ \
return TestRunner::runTests(name); \
} | {
"content_hash": "3d602171dee660bbbfe9032edc85c980",
"timestamp": "",
"source": "github",
"line_count": 281,
"max_line_length": 112,
"avg_line_length": 29.558718861209965,
"alnum_prop": 0.5762099686973272,
"repo_name": "wallstop/SlimTest-",
"id": "e2eb8c5af303fd0fe2f3e036983ee85526b5884b",
"size": "9480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SlimTest.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "25865"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_11) on Thu Sep 05 22:51:04 CEST 2013 -->
<title>groovy.text (Groovy 2.1.7)</title>
<meta name="date" content="2013-09-05">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../groovy/text/package-summary.html" target="classFrame">groovy.text</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="Template.html" title="interface in groovy.text" target="classFrame"><i>Template</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="GStringTemplateEngine.html" title="class in groovy.text" target="classFrame">GStringTemplateEngine</a></li>
<li><a href="SimpleTemplateEngine.html" title="class in groovy.text" target="classFrame">SimpleTemplateEngine</a></li>
<li><a href="TemplateEngine.html" title="class in groovy.text" target="classFrame">TemplateEngine</a></li>
<li><a href="XmlTemplateEngine.html" title="class in groovy.text" target="classFrame">XmlTemplateEngine</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "c49b03359460b7bdc2dbf7cd5b4da354",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 120,
"avg_line_length": 48.38461538461539,
"alnum_prop": 0.7019077901430842,
"repo_name": "Selventa/model-builder",
"id": "341f35d52ba91e7a3c6d0b0af5a7e0beb64ea720",
"size": "1258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/groovy/doc/html/api/groovy/text/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "225777"
},
{
"name": "Java",
"bytes": "27977"
},
{
"name": "Shell",
"bytes": "8715"
}
],
"symlink_target": ""
} |
{% extends "common/selection.html" %}
{% load staticfiles %}
{% block addon_js %}
<script src="{% static 'home/js/selection.js' %}"></script>
{% endblock %}
{% block middle_column %}
{% if segment_list %}
<!-- segment list -->
<div class="col-md-12 panel panel-primary">
<div class="panel-body">
<h4>Sequence segments</h4>
{% if position_type == 'site_residue' %}
{% include 'common/selection_segments_sitesearch.html' %}
{% elif position_type == 'gprotein' %}
{% include 'common/selection_segments_gproteins.html' %}
{% elif position_type == 'arrestin' %}
{% include 'common/selection_segments_arrestin.html' %}
{% else %}
{% include 'common/selection_segments.html' %}
{% endif %}
</div>
</div>
{% endif %}
{% if structure_upload %}
<!-- structure upload -->
{% include 'common/selection_pdb_upload.html' %}
{% endif %}
{% if rsets %}
<h4>Predefined sets of residues</h4>
<div class="col-md-12 panel panel-primary">
<div class="panel-body">
<div>
{% include 'common/segmentselection_predefined.html' %}
</div>
</div>
</div>
{% endif %}
{% endblock %}
| {
"content_hash": "8cedc1f2411996409fbbe97403f66493",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 83,
"avg_line_length": 39.21951219512195,
"alnum_prop": 0.4284825870646766,
"repo_name": "fosfataza/protwis",
"id": "743096e0d81b81bbb636a767cd0b66e84a957765",
"size": "1608",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/templates/common/segmentselection.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "104739"
},
{
"name": "HTML",
"bytes": "1426027"
},
{
"name": "JavaScript",
"bytes": "1127392"
},
{
"name": "Python",
"bytes": "2593740"
},
{
"name": "Shell",
"bytes": "386"
}
],
"symlink_target": ""
} |
import Vue from 'vue';
import Vuex from 'vuex';
import playground from './components/playground/vuex/store';
import shaderEditor from './components/shader-editor/vuex/store';
import ogmEditor from './components/ogm-editor/vuex/store';
import lightingEditor from './components/lighting-editor/vuex/store';
import particlesEditor from './components/particles-editor/vuex/store';
Vue.use(Vuex);
const MainStore = new Vuex.Store({
modules: {
playground,
shaderEditor,
lightingEditor,
particlesEditor,
ogmEditor
}
});
window.vuex = {
getState: () => MainStore.state,
getStore: () => MainStore
};
export default MainStore;
| {
"content_hash": "74f4d38d460122c0cd51184353aece1c",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 71,
"avg_line_length": 24.96153846153846,
"alnum_prop": 0.7288135593220338,
"repo_name": "nixegend/material-editor",
"id": "e2505fa8679cf50567893ccba1836469d2abd3e2",
"size": "649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main-store.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "52226"
},
{
"name": "HTML",
"bytes": "372"
},
{
"name": "JavaScript",
"bytes": "91967"
},
{
"name": "Vue",
"bytes": "139463"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.simpleemail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Represents a request to add or update a sending authorization policy for an identity. Sending authorization is an
* Amazon SES feature that enables you to authorize other senders to use your identities. For information, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer
* Guide</a>.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/PutIdentityPolicy" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PutIdentityPolicyRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The identity that the policy will apply to. You can specify an identity by using its name or by using its Amazon
* Resource Name (ARN). Examples: <code>user@example.com</code>, <code>example.com</code>,
* <code>arn:aws:ses:us-east-1:123456789012:identity/example.com</code>.
* </p>
* <p>
* To successfully call this API, you must own the identity.
* </p>
*/
private String identity;
/**
* <p>
* The name of the policy.
* </p>
* <p>
* The policy name cannot exceed 64 characters and can only include alphanumeric characters, dashes, and
* underscores.
* </p>
*/
private String policyName;
/**
* <p>
* The text of the policy in JSON format. The policy cannot exceed 4 KB.
* </p>
* <p>
* For information about the syntax of sending authorization policies, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES
* Developer Guide</a>.
* </p>
*/
private String policy;
/**
* <p>
* The identity that the policy will apply to. You can specify an identity by using its name or by using its Amazon
* Resource Name (ARN). Examples: <code>user@example.com</code>, <code>example.com</code>,
* <code>arn:aws:ses:us-east-1:123456789012:identity/example.com</code>.
* </p>
* <p>
* To successfully call this API, you must own the identity.
* </p>
*
* @param identity
* The identity that the policy will apply to. You can specify an identity by using its name or by using its
* Amazon Resource Name (ARN). Examples: <code>user@example.com</code>, <code>example.com</code>,
* <code>arn:aws:ses:us-east-1:123456789012:identity/example.com</code>.</p>
* <p>
* To successfully call this API, you must own the identity.
*/
public void setIdentity(String identity) {
this.identity = identity;
}
/**
* <p>
* The identity that the policy will apply to. You can specify an identity by using its name or by using its Amazon
* Resource Name (ARN). Examples: <code>user@example.com</code>, <code>example.com</code>,
* <code>arn:aws:ses:us-east-1:123456789012:identity/example.com</code>.
* </p>
* <p>
* To successfully call this API, you must own the identity.
* </p>
*
* @return The identity that the policy will apply to. You can specify an identity by using its name or by using its
* Amazon Resource Name (ARN). Examples: <code>user@example.com</code>, <code>example.com</code>,
* <code>arn:aws:ses:us-east-1:123456789012:identity/example.com</code>.</p>
* <p>
* To successfully call this API, you must own the identity.
*/
public String getIdentity() {
return this.identity;
}
/**
* <p>
* The identity that the policy will apply to. You can specify an identity by using its name or by using its Amazon
* Resource Name (ARN). Examples: <code>user@example.com</code>, <code>example.com</code>,
* <code>arn:aws:ses:us-east-1:123456789012:identity/example.com</code>.
* </p>
* <p>
* To successfully call this API, you must own the identity.
* </p>
*
* @param identity
* The identity that the policy will apply to. You can specify an identity by using its name or by using its
* Amazon Resource Name (ARN). Examples: <code>user@example.com</code>, <code>example.com</code>,
* <code>arn:aws:ses:us-east-1:123456789012:identity/example.com</code>.</p>
* <p>
* To successfully call this API, you must own the identity.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutIdentityPolicyRequest withIdentity(String identity) {
setIdentity(identity);
return this;
}
/**
* <p>
* The name of the policy.
* </p>
* <p>
* The policy name cannot exceed 64 characters and can only include alphanumeric characters, dashes, and
* underscores.
* </p>
*
* @param policyName
* The name of the policy.</p>
* <p>
* The policy name cannot exceed 64 characters and can only include alphanumeric characters, dashes, and
* underscores.
*/
public void setPolicyName(String policyName) {
this.policyName = policyName;
}
/**
* <p>
* The name of the policy.
* </p>
* <p>
* The policy name cannot exceed 64 characters and can only include alphanumeric characters, dashes, and
* underscores.
* </p>
*
* @return The name of the policy.</p>
* <p>
* The policy name cannot exceed 64 characters and can only include alphanumeric characters, dashes, and
* underscores.
*/
public String getPolicyName() {
return this.policyName;
}
/**
* <p>
* The name of the policy.
* </p>
* <p>
* The policy name cannot exceed 64 characters and can only include alphanumeric characters, dashes, and
* underscores.
* </p>
*
* @param policyName
* The name of the policy.</p>
* <p>
* The policy name cannot exceed 64 characters and can only include alphanumeric characters, dashes, and
* underscores.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutIdentityPolicyRequest withPolicyName(String policyName) {
setPolicyName(policyName);
return this;
}
/**
* <p>
* The text of the policy in JSON format. The policy cannot exceed 4 KB.
* </p>
* <p>
* For information about the syntax of sending authorization policies, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES
* Developer Guide</a>.
* </p>
*
* @param policy
* The text of the policy in JSON format. The policy cannot exceed 4 KB.</p>
* <p>
* For information about the syntax of sending authorization policies, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon
* SES Developer Guide</a>.
*/
public void setPolicy(String policy) {
this.policy = policy;
}
/**
* <p>
* The text of the policy in JSON format. The policy cannot exceed 4 KB.
* </p>
* <p>
* For information about the syntax of sending authorization policies, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES
* Developer Guide</a>.
* </p>
*
* @return The text of the policy in JSON format. The policy cannot exceed 4 KB.</p>
* <p>
* For information about the syntax of sending authorization policies, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon
* SES Developer Guide</a>.
*/
public String getPolicy() {
return this.policy;
}
/**
* <p>
* The text of the policy in JSON format. The policy cannot exceed 4 KB.
* </p>
* <p>
* For information about the syntax of sending authorization policies, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES
* Developer Guide</a>.
* </p>
*
* @param policy
* The text of the policy in JSON format. The policy cannot exceed 4 KB.</p>
* <p>
* For information about the syntax of sending authorization policies, see the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon
* SES Developer Guide</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PutIdentityPolicyRequest withPolicy(String policy) {
setPolicy(policy);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getIdentity() != null)
sb.append("Identity: ").append(getIdentity()).append(",");
if (getPolicyName() != null)
sb.append("PolicyName: ").append(getPolicyName()).append(",");
if (getPolicy() != null)
sb.append("Policy: ").append(getPolicy());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof PutIdentityPolicyRequest == false)
return false;
PutIdentityPolicyRequest other = (PutIdentityPolicyRequest) obj;
if (other.getIdentity() == null ^ this.getIdentity() == null)
return false;
if (other.getIdentity() != null && other.getIdentity().equals(this.getIdentity()) == false)
return false;
if (other.getPolicyName() == null ^ this.getPolicyName() == null)
return false;
if (other.getPolicyName() != null && other.getPolicyName().equals(this.getPolicyName()) == false)
return false;
if (other.getPolicy() == null ^ this.getPolicy() == null)
return false;
if (other.getPolicy() != null && other.getPolicy().equals(this.getPolicy()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getIdentity() == null) ? 0 : getIdentity().hashCode());
hashCode = prime * hashCode + ((getPolicyName() == null) ? 0 : getPolicyName().hashCode());
hashCode = prime * hashCode + ((getPolicy() == null) ? 0 : getPolicy().hashCode());
return hashCode;
}
@Override
public PutIdentityPolicyRequest clone() {
return (PutIdentityPolicyRequest) super.clone();
}
}
| {
"content_hash": "b7834723accc6582f10ff4da10227994",
"timestamp": "",
"source": "github",
"line_count": 314,
"max_line_length": 120,
"avg_line_length": 36.99363057324841,
"alnum_prop": 0.6142389807162535,
"repo_name": "aws/aws-sdk-java",
"id": "82cd77ff099e8553a52924b7f73175ea0cf725d5",
"size": "12196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/PutIdentityPolicyRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
layout: post
title: "Jekyll Sites"
date: 2014-11-16 16:46:37 -0500
comments: true
categories:
- web development
- programming
tags: [jekyll]
---
Without further comment for now, here are some Jekyll website designs I'm
currently working on. (These are still works in progress.)
[Jekyll Golden] is a responsive, mobile-first Jekyll blogging theme in which the
layout and typography are based on the [Golden Ratio] of 1:1.618. You can view
the [codebase here](https://github.com/mjohnq3/jekyll-golden "Jekyll Golden codebase")
and the [gh-pages code](https://github.com/mjohnq3/jekyll-golden/tree/gh-pages
"Jekyll Golden gh-pages code") generated after the site is built locally then
deployed to GitHub.
[Jekyll Writer] is a simple Jekyll blogging theme with a responsive, mobile-first
layout, stylish monochromatic design, and easy to read typography. You can view
the [codebase here](https://github.com/mjohnq3/jekyll-writer "Jekyll Writer codebase")
and the [gh-pages code](https://github.com/mjohnq3/jekyll-writer/tree/gh-pages
"Jekyll Writer gh-pages code") generated after the site is built locally then
deployed to GitHub.
If you'd like to see the steps involved in creating these sites you can view my
[Jekyll Website Board] on [Trello].
[Jekyll Golden]: http://mjohnq3.github.io/jekyll-golden/ "Jekyll Golden"
[Golden Ratio]: http://en.wikipedia.org/wiki/Golden_ratio "Golden Ratio"
[Jekyll Writer]: http://mjohnq3.github.io/jekyll-writer/ "Jekyll Writer"
[Trello]: https://trello.com/ "Trello"
[Jekyll Website Board]: https://trello.com/b/bOzLDA01/jekyll-website "Trello Jekyll Board"
| {
"content_hash": "c5195023feb8cba4d4e9cd1720470b6d",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 90,
"avg_line_length": 43.351351351351354,
"alnum_prop": 0.7680798004987531,
"repo_name": "mjohnq3/jekyll-mjohnq3",
"id": "ac32ebb9a03ee3bcb287af2faadade93e4b1b164",
"size": "1608",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2014-11-16-jekyll-sites.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "36474"
},
{
"name": "HTML",
"bytes": "9808"
},
{
"name": "Ruby",
"bytes": "11593"
}
],
"symlink_target": ""
} |
Call Your Mom is an improv group. They have this site.
## :computer: Local development
**Note:** All the instructions assume a unix-like terminal (Mac OS X, Linux, etc). It'll probably break badly on windows, unless you have Cygwin maybe? I don't know, I didn't test it.
You'll need to clone this repository and [install Hugo](http://gohugo.io/overview/installing/).
From the project root, running `hugo server` will spin up a local dev server, which you can access at `localhost:1313`.
This server will watch for changes, and live reload any changes you make.
All files relevant to the project are kept in `themes/xgonna`.
Check out the [Hugo documentation](http://gohugo.io/overview/introduction/) for more info on how Hugo does it's thing.
## :tv: Adding shows
You'll need to have a local development environment setup (see above).
Once that's done, change into the project root and run `hugo add show/[name-of-show-file].md`, where `[name-of-show-file].md` is the name of your show file...but you're smart; I didn't need to tell you that, right?
That will create a new [markdown](http://daringfireball.net/projects/markdown/basics) file, and output the path it saved it at. The file will have some boilerplate added to the top, in the form of meta data. This meta data is wrapped in `+++` at the top and bottom.
You will need to update the meta data to suit the event's needs. Below is an explanation of each item, and how to use it. More technical information keeps people reading, right?
### :calendar: date
This is the date of the show, in the format of `[year]-[month]-[day]T[hour]:[minute]:[second]-[timezone]`, e.g. `2016-04-14T21:00:00-05:00`. The date will be formatted when output in the frontend, but this more computer-friendly format needs to be adhered to for the time being. Update it like a Time Lord.
### :page_facing_up: title
The title of the event. It will appear wherever titles appear, like they should. No funny business, I swear.
### :sunrise: header_image
Not in use currently. _Delete this line_.
### :+1: facebook_link
The URL to the facebook event for this show. _If you don't have an event, delete this line, or else a link that goes somewhere shitty will appear on the site!_
### :house_with_garden: venue
The name of the venue where the show is taking place. Just like it seems like. See? You figured it out.
Eventually I'd like to link this to Google maps or something like that, but for now that does _not_ happen. Pretty cool, huh?
### :speech_balloon: content
Okay, so `content` isn't part of the meta data. It's actually the shit you write below the last line of `+++`. Write it in markdown, be cool, and party down.
## :shipit: Deploying
The site is hosted on github pages, and there is a rather complex git process involed to put everything in the right place. Fortunately, all this has been automated.
Simply run: `./deploy.sh` from the project root, and all will be taken care of.
| {
"content_hash": "36443dc2a58d50fdda33d9fea2888b8e",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 306,
"avg_line_length": 52.69642857142857,
"alnum_prop": 0.7421213148085395,
"repo_name": "bronzehedwick/callyourmom",
"id": "4e6d81b1216bed2db31ad668d0aad05bffc9bde6",
"size": "2968",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "29947"
},
{
"name": "CSS",
"bytes": "4058"
},
{
"name": "GCC Machine Description",
"bytes": "8"
},
{
"name": "HTML",
"bytes": "67369"
},
{
"name": "PHP",
"bytes": "1216"
},
{
"name": "Shell",
"bytes": "378"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Admin, :type => :model do
it { should have_attribute(:account_id).with(:type => :integer, :null => false) }
end | {
"content_hash": "1f308ef80188437806c739ef6a4ebd8d",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 83,
"avg_line_length": 29,
"alnum_prop": 0.6758620689655173,
"repo_name": "sujoyg/admin_engine",
"id": "b5e51a31945465220fed28f3e536647c67cb4989",
"size": "145",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/models/admin_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "546"
},
{
"name": "HTML",
"bytes": "2386"
},
{
"name": "JavaScript",
"bytes": "641"
},
{
"name": "Ruby",
"bytes": "24700"
}
],
"symlink_target": ""
} |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="40dp"
android:height="40dp"
android:viewportWidth="40"
android:viewportHeight="40"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M4.208,32.458V7.542H35.792V32.458Z"/>
</vector>
| {
"content_hash": "50dfebf587d6c9695053bd9346fdc59d",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 66,
"avg_line_length": 35.3,
"alnum_prop": 0.7053824362606232,
"repo_name": "google/material-design-icons",
"id": "06f9df37314c92b886cde56b3346c076701e893d",
"size": "353",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "symbols/android/rectangle/materialsymbolsoutlined/rectangle_wght300gradN25fill1_40px.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace TlAssetsBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
class InstallGulpCommand extends ContainerAwareCommand
{
protected function configure()
{
$this->setName('tlassets:install:gulp')
->setDescription('Install Gulp and his dependencies')
->addOption('nodebug', null, InputOption::VALUE_NONE, 'Do not show any log');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$hideLog = $input->getOption('nodebug');
$rootDir = $this->getContainer()->get('kernel')->getRootDir()."/../";
$gulpSrcFolder = $rootDir.'vendor/electrotiti/tlassets-bundle/src/TlAssetsBundle/Compiler/Gulp/';
$config = $this->getContainer()->getParameter('tl_assets.config');
$return = $this->_installGulp($rootDir, $gulpSrcFolder, $config['node_folder'],$hideLog);
if($return == 0) {
if(!$hideLog) {
$output->writeln('<info>Gulp and dependencies successfully installed.</info>');
}
} else {
$output->writeln('<error>Some errors occurred during installation, please check logs.</error>');
}
}
private function _installGulp($rootDir, $gulpSrcFolder, $destNodeFolder, $hideLog = false)
{
// Build the command line
$command = 'cd '.$rootDir.' && npm install '.$gulpSrcFolder.' --prefix '.$destNodeFolder;
if($hideLog) {
$command .= ' 2>&1';
}
// Command execution
exec ($command,$result,$return);
return $return;
}
} | {
"content_hash": "b4e9bd266fd1e55a4811891b263104ec",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 108,
"avg_line_length": 33.7037037037037,
"alnum_prop": 0.6406593406593407,
"repo_name": "electrotiti/tlassets-bundle",
"id": "2f2d3a89fa2fd5e959b20839c0ef272bd2fddd95",
"size": "1820",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/TlAssetsBundle/Command/InstallGulpCommand.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "174"
},
{
"name": "JavaScript",
"bytes": "3605"
},
{
"name": "PHP",
"bytes": "38338"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.