repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
clinical-meteor/meteor-on-fhir | cordova-build-release/www/application/packages/clinical_accounts-oauth.js | 10784 | //////////////////////////////////////////////////////////////////////////
// //
// This is a generated file. You can view the original //
// source in your browser if your browser supports source maps. //
// Source maps are supported by all recent versions of Chrome, Safari, //
// and Firefox, and by Internet Explorer 11. //
// //
//////////////////////////////////////////////////////////////////////////
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var global = Package.meteor.global;
var meteorEnv = Package.meteor.meteorEnv;
var _ = Package.underscore._;
var Random = Package.random.Random;
var check = Package.check.check;
var Match = Package.check.Match;
var Accounts = Package['accounts-base'].Accounts;
var OAuth = Package['clinical:oauth'].OAuth;
var WebApp = Package.webapp.WebApp;
var Log = Package.logging.Log;
var Tracker = Package.deps.Tracker;
var Deps = Package.deps.Deps;
var Session = Package.session.Session;
var DDP = Package['ddp-client'].DDP;
var Mongo = Package.mongo.Mongo;
var Blaze = Package.ui.Blaze;
var UI = Package.ui.UI;
var Handlebars = Package.ui.Handlebars;
var Spacebars = Package.spacebars.Spacebars;
var Template = Package['templating-runtime'].Template;
var $ = Package.jquery.$;
var jQuery = Package.jquery.jQuery;
var EJSON = Package.ejson.EJSON;
var FastClick = Package.fastclick.FastClick;
var LaunchScreen = Package['launch-screen'].LaunchScreen;
var meteorInstall = Package.modules.meteorInstall;
var meteorBabelHelpers = Package['babel-runtime'].meteorBabelHelpers;
var Promise = Package.promise.Promise;
var HTML = Package.htmljs.HTML;
var Symbol = Package['ecmascript-runtime-client'].Symbol;
var Map = Package['ecmascript-runtime-client'].Map;
var Set = Package['ecmascript-runtime-client'].Set;
var require = meteorInstall({"node_modules":{"meteor":{"clinical:accounts-oauth":{"oauth_common.js":function(require,exports,module){
//////////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/clinical_accounts-oauth/oauth_common.js //
// //
//////////////////////////////////////////////////////////////////////////////////////////////////
//
var get;
module.link("lodash", {
get: function (v) {
get = v;
}
}, 0);
Accounts.oauth = {};
var services = {}; // Helper for registering OAuth based accounts packages.
// On the server, adds an index to the user collection.
Accounts.oauth.registerService = function (name) {
if (get(Meteor, 'settings.public.logging') === "debug") {
console.log('C3 Registering OAuth service in active server memory: ', name);
}
if (_.has(services, name)) throw new Error("Duplicate service: " + name);
services[name] = true;
if (Meteor.server) {
// Accounts.updateOrCreateUserFromExternalService does a lookup by this id,
// so this should be a unique index. You might want to add indexes for other
// fields returned by your service (eg services.github.login) but you can do
// that in your app.
Meteor.users._ensureIndex('services.' + name + '.id', {
unique: 1,
sparse: 1
});
}
}; // Removes a previously registered service.
// This will disable logging in with this service, and serviceNames() will not
// contain it.
// It's worth noting that already logged in users will remain logged in unless
// you manually expire their sessions.
Accounts.oauth.unregisterService = function (name) {
if (!_.has(services, name)) throw new Error("Service not found: " + name);
delete services[name];
};
Accounts.oauth.serviceNames = function () {
return _.keys(services);
};
//////////////////////////////////////////////////////////////////////////////////////////////////
},"oauth_client.js":function(require,exports,module){
//////////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/clinical_accounts-oauth/oauth_client.js //
// //
//////////////////////////////////////////////////////////////////////////////////////////////////
//
var get;
module.link("lodash", {
get: function (v) {
get = v;
}
}, 0);
// Documentation for Meteor.loginWithExternalService
/**
* @name loginWith<ExternalService>
* @memberOf Meteor
* @function
* @summary Log the user in using an external service.
* @locus Client
* @param {Object} [options]
* @param {String[]} options.requestPermissions A list of permissions to request from the user.
* @param {Boolean} options.requestOfflineToken If true, asks the user for permission to act on their behalf when offline. This stores an additional offline token in the `services` field of the user document. Currently only supported with Google.
* @param {Object} options.loginUrlParameters Provide additional parameters to the authentication URI. Currently only supported with Google. See [Google Identity Platform documentation](https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters).
* @param {String} options.loginHint An email address that the external service will use to pre-fill the login prompt. Currently only supported with Meteor developer accounts and Google accounts. If used with Google, the Google User ID can also be passed.
* @param {String} options.loginStyle Login style ("popup" or "redirect", defaults to the login service configuration). The "popup" style opens the login page in a separate popup window, which is generally preferred because the Meteor application doesn't need to be reloaded. The "redirect" style redirects the Meteor application's window to the login page, and the login service provider redirects back to the Meteor application which is then reloaded. The "redirect" style can be used in situations where a popup window can't be opened, such as in a mobile UIWebView. The "redirect" style however relies on session storage which isn't available in Safari private mode, so the "popup" style will be forced if session storage can't be used.
* @param {String} options.redirectUrl If using "redirect" login style, the user will be returned to this URL after authorisation has been completed.
* @param {Function} [callback] Optional callback. Called with no arguments on success, or with a single `Error` argument on failure. The callback cannot be called if you are using the "redirect" `loginStyle`, because the app will have reloaded in the meantime; try using [client-side login hooks](#accounts_onlogin) instead.
* @importFromPackage meteor
*/
// Allow server to specify a specify subclass of errors. We should come
// up with a more generic way to do this!
var convertError = function (err) {
if (err && err instanceof Meteor.Error && err.error === Accounts.LoginCancelledError.numericError) return new Accounts.LoginCancelledError(err.reason);else return err;
}; // For the redirect login flow, the final step is that we're
// redirected back to the application. The credentialToken for this
// login attempt is stored in the reload migration data, and the
// credentialSecret for a successful login is stored in session
// storage.
Meteor.startup(function () {
var oauth = OAuth.getDataAfterRedirect();
if (!oauth) return; // We'll only have the credentialSecret if the login completed
// successfully. However we still call the login method anyway to
// retrieve the error if the login was unsuccessful.
var methodName = 'login';
var methodArguments = [{
oauth: _.pick(oauth, 'credentialToken', 'credentialSecret')
}];
if (get(Meteor, 'settings.public.logging') === "debug") {
console.log('Meteor.startup()');
}
var newLoginMethod = {
methodArguments: methodArguments,
userCallback: function (err) {
// The redirect login flow is complete. Construct an
// `attemptInfo` object with the login result, and report back
// to the code which initiated the login attempt
// (e.g. accounts-ui, when that package is being used).
err = convertError(err);
Accounts._pageLoadLogin({
type: oauth.loginService,
allowed: !err,
error: err,
methodName: methodName,
methodArguments: methodArguments
});
}
};
if (get(Meteor, 'settings.public.logging') === "debug") {
console.log('Meteor.startup().newLoginMethod', newLoginMethod);
}
Accounts.callLoginMethod(newLoginMethod);
}); // Send an OAuth login method to the server. If the user authorized
// access in the popup this should log the user in, otherwise
// nothing should happen.
Accounts.oauth.tryLoginAfterPopupClosed = function (credentialToken, callback) {
if (get(Meteor, 'settings.public.logging') === "debug") {
console.log('C9. Trying login now that the popup is closed.', credentialToken);
}
var credentialSecret = OAuth._retrieveCredentialSecret(credentialToken) || null;
Accounts.callLoginMethod({
methodArguments: [{
oauth: {
credentialToken: credentialToken,
credentialSecret: credentialSecret
}
}],
userCallback: callback && function (err) {
callback(convertError(err));
}
});
};
Accounts.oauth.credentialRequestCompleteHandler = function (callback) {
if (get(Meteor, 'settings.public.logging') === "debug") {
console.log('C4. Attempting to handle credetial request completion.');
}
return function (credentialTokenOrError) {
if (credentialTokenOrError && credentialTokenOrError instanceof Error) {
callback && callback(credentialTokenOrError);
} else {
Accounts.oauth.tryLoginAfterPopupClosed(credentialTokenOrError, callback);
}
};
};
//////////////////////////////////////////////////////////////////////////////////////////////////
}}}}},{
"extensions": [
".js",
".json"
]
});
require("/node_modules/meteor/clinical:accounts-oauth/oauth_common.js");
require("/node_modules/meteor/clinical:accounts-oauth/oauth_client.js");
/* Exports */
Package._define("clinical:accounts-oauth");
})();
| agpl-3.0 |
diputacioBCN/decidim-diba | db/migrate/20220203073236_add_followable_counter_cache_to_users.decidim.rb | 503 | # frozen_string_literal: true
# This migration comes from decidim (originally 20210310120640)
class AddFollowableCounterCacheToUsers < ActiveRecord::Migration[5.2]
def change
add_column :decidim_users, :follows_count, :integer, null: false, default: 0, index: true
reversible do |dir|
dir.up do
Decidim::User.reset_column_information
Decidim::User.find_each do |record|
record.class.reset_counters(record.id, :follows)
end
end
end
end
end
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/forms/booktheatreslot/BaseLogic.java | 9878 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.forms.booktheatreslot;
public abstract class BaseLogic extends Handlers
{
public final Class getDomainInterface() throws ClassNotFoundException
{
return ims.RefMan.domain.BookTheatreSlot.class;
}
public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.RefMan.domain.BookTheatreSlot domain)
{
setContext(engine, form);
this.domain = domain;
}
protected final void oncmbAnaesTypeValueSet(Object value)
{
java.util.ArrayList listOfValues = this.form.lyr1().tabSearch().cmbAnaesType().getValues();
if(value == null)
{
if(listOfValues != null && listOfValues.size() > 0)
{
for(int x = 0; x < listOfValues.size(); x++)
{
ims.clinical.vo.lookups.AnaestheticType existingInstance = (ims.clinical.vo.lookups.AnaestheticType)listOfValues.get(x);
if(!existingInstance.isActive())
{
bindcmbAnaesTypeLookup();
return;
}
}
}
}
else if(value instanceof ims.clinical.vo.lookups.AnaestheticType)
{
ims.clinical.vo.lookups.AnaestheticType instance = (ims.clinical.vo.lookups.AnaestheticType)value;
if(listOfValues != null)
{
if(listOfValues.size() == 0)
bindcmbAnaesTypeLookup();
for(int x = 0; x < listOfValues.size(); x++)
{
ims.clinical.vo.lookups.AnaestheticType existingInstance = (ims.clinical.vo.lookups.AnaestheticType)listOfValues.get(x);
if(existingInstance.equals(instance))
return;
}
}
this.form.lyr1().tabSearch().cmbAnaesType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor());
}
}
protected final void bindcmbAnaesTypeLookup()
{
this.form.lyr1().tabSearch().cmbAnaesType().clear();
ims.clinical.vo.lookups.AnaestheticTypeCollection lookupCollection = ims.clinical.vo.lookups.LookupHelper.getAnaestheticType(this.domain.getLookupService());
for(int x = 0; x < lookupCollection.size(); x++)
{
this.form.lyr1().tabSearch().cmbAnaesType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor());
}
}
protected final void setcmbAnaesTypeLookupValue(int id)
{
ims.clinical.vo.lookups.AnaestheticType instance = ims.clinical.vo.lookups.LookupHelper.getAnaestheticTypeInstance(this.domain.getLookupService(), id);
if(instance != null)
this.form.lyr1().tabSearch().cmbAnaesType().setValue(instance);
}
protected final void defaultcmbAnaesTypeLookupValue()
{
this.form.lyr1().tabSearch().cmbAnaesType().setValue((ims.clinical.vo.lookups.AnaestheticType)domain.getLookupService().getDefaultInstance(ims.clinical.vo.lookups.AnaestheticType.class, engine.getFormName().getID(), ims.clinical.vo.lookups.AnaestheticType.TYPE_ID));
}
protected final void oncmbListTypeValueSet(Object value)
{
java.util.ArrayList listOfValues = this.form.lyr1().tabSearch().cmbListType().getValues();
if(value == null)
{
if(listOfValues != null && listOfValues.size() > 0)
{
for(int x = 0; x < listOfValues.size(); x++)
{
ims.scheduling.vo.lookups.ProfileListType existingInstance = (ims.scheduling.vo.lookups.ProfileListType)listOfValues.get(x);
if(!existingInstance.isActive())
{
bindcmbListTypeLookup();
return;
}
}
}
}
else if(value instanceof ims.scheduling.vo.lookups.ProfileListType)
{
ims.scheduling.vo.lookups.ProfileListType instance = (ims.scheduling.vo.lookups.ProfileListType)value;
if(listOfValues != null)
{
if(listOfValues.size() == 0)
bindcmbListTypeLookup();
for(int x = 0; x < listOfValues.size(); x++)
{
ims.scheduling.vo.lookups.ProfileListType existingInstance = (ims.scheduling.vo.lookups.ProfileListType)listOfValues.get(x);
if(existingInstance.equals(instance))
return;
}
}
this.form.lyr1().tabSearch().cmbListType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor());
}
}
protected final void bindcmbListTypeLookup()
{
this.form.lyr1().tabSearch().cmbListType().clear();
ims.scheduling.vo.lookups.ProfileListTypeCollection lookupCollection = ims.scheduling.vo.lookups.LookupHelper.getProfileListType(this.domain.getLookupService());
for(int x = 0; x < lookupCollection.size(); x++)
{
this.form.lyr1().tabSearch().cmbListType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor());
}
}
protected final void setcmbListTypeLookupValue(int id)
{
ims.scheduling.vo.lookups.ProfileListType instance = ims.scheduling.vo.lookups.LookupHelper.getProfileListTypeInstance(this.domain.getLookupService(), id);
if(instance != null)
this.form.lyr1().tabSearch().cmbListType().setValue(instance);
}
protected final void defaultcmbListTypeLookupValue()
{
this.form.lyr1().tabSearch().cmbListType().setValue((ims.scheduling.vo.lookups.ProfileListType)domain.getLookupService().getDefaultInstance(ims.scheduling.vo.lookups.ProfileListType.class, engine.getFormName().getID(), ims.scheduling.vo.lookups.ProfileListType.TYPE_ID));
}
protected final void oncmbTheatreTypeValueSet(Object value)
{
java.util.ArrayList listOfValues = this.form.lyr1().tabSearch().cmbTheatreType().getValues();
if(value == null)
{
if(listOfValues != null && listOfValues.size() > 0)
{
for(int x = 0; x < listOfValues.size(); x++)
{
ims.scheduling.vo.lookups.TheatreType existingInstance = (ims.scheduling.vo.lookups.TheatreType)listOfValues.get(x);
if(!existingInstance.isActive())
{
bindcmbTheatreTypeLookup();
return;
}
}
}
}
else if(value instanceof ims.scheduling.vo.lookups.TheatreType)
{
ims.scheduling.vo.lookups.TheatreType instance = (ims.scheduling.vo.lookups.TheatreType)value;
if(listOfValues != null)
{
if(listOfValues.size() == 0)
bindcmbTheatreTypeLookup();
for(int x = 0; x < listOfValues.size(); x++)
{
ims.scheduling.vo.lookups.TheatreType existingInstance = (ims.scheduling.vo.lookups.TheatreType)listOfValues.get(x);
if(existingInstance.equals(instance))
return;
}
}
this.form.lyr1().tabSearch().cmbTheatreType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor());
}
}
protected final void bindcmbTheatreTypeLookup()
{
this.form.lyr1().tabSearch().cmbTheatreType().clear();
ims.scheduling.vo.lookups.TheatreTypeCollection lookupCollection = ims.scheduling.vo.lookups.LookupHelper.getTheatreType(this.domain.getLookupService());
for(int x = 0; x < lookupCollection.size(); x++)
{
this.form.lyr1().tabSearch().cmbTheatreType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor());
}
}
protected final void setcmbTheatreTypeLookupValue(int id)
{
ims.scheduling.vo.lookups.TheatreType instance = ims.scheduling.vo.lookups.LookupHelper.getTheatreTypeInstance(this.domain.getLookupService(), id);
if(instance != null)
this.form.lyr1().tabSearch().cmbTheatreType().setValue(instance);
}
protected final void defaultcmbTheatreTypeLookupValue()
{
this.form.lyr1().tabSearch().cmbTheatreType().setValue((ims.scheduling.vo.lookups.TheatreType)domain.getLookupService().getDefaultInstance(ims.scheduling.vo.lookups.TheatreType.class, engine.getFormName().getID(), ims.scheduling.vo.lookups.TheatreType.TYPE_ID));
}
public final void free()
{
super.free();
domain = null;
}
protected ims.RefMan.domain.BookTheatreSlot domain;
}
| agpl-3.0 |
cnedDI/AccessiDys | app/scripts/services/tagsService.js | 1918 | /*File: tagsService.js
*
* Copyright (c) 2013-2016
* Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
* ([email protected])
*
* GNU Affero General Public License (AGPL) version 3.0 or later version
*
* This file is part of a program which is free software: you can
* redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
'use strict';
angular.module('cnedApp').service('tagsService', function ($http, $uibModal, CacheProvider, configuration) {
this.getTags = function () {
return $http.get(configuration.BASE_URL + '/readTags').then(function (result) {
return CacheProvider.setItem(result.data, 'listTags').then(function () {
return result.data;
});
}, function () {
return CacheProvider.getItem('listTags');
});
};
this.openEditModal = function (mode, tag) {
return $uibModal.open({
templateUrl: 'views/tag/edit-tag.modal.html',
controller: 'EditTagModalCtrl',
size: 'lg',
resolve: {
mode: function () {
return mode;
},
tag: function () {
return tag;
}
}
}).result;
};
});
| agpl-3.0 |
JavierPeris/kunagi | src/main/java/scrum/server/css/CssServlet.java | 2099 | /*
* Copyright 2011 Witoslaw Koczewsi <[email protected]>, Artjom Kochtchi
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package scrum.server.css;
import ilarkesto.core.logging.Log;
import ilarkesto.io.DynamicClassLoader;
import ilarkesto.ui.web.CssBuilder;
import ilarkesto.webapp.RequestWrapper;
import java.io.IOException;
import scrum.server.ScrumWebApplication;
import scrum.server.WebSession;
import scrum.server.common.AKunagiServlet;
public class CssServlet extends AKunagiServlet {
private static final Log LOG = Log.get(CssServlet.class);
private static final long serialVersionUID = 1;
private transient final KunagiCssBuilder screenCssBuilder = new KunagiCssBuilder();
@Override
protected void onRequest(RequestWrapper<WebSession> req) throws IOException {
req.setContentTypeCss();
CssBuilder css = new CssBuilder(req.getWriter());
ICssBuilder builder = getCssBuilder();
builder.buildCss(css);
css.flush();
// LOG.debug(builder);
}
private ICssBuilder getCssBuilder() {
if (ScrumWebApplication.get().isDevelopmentMode()) {
ClassLoader loader = new DynamicClassLoader(getClass().getClassLoader(), KunagiCssBuilder.class.getName());
Class<? extends ICssBuilder> type;
try {
type = (Class<? extends ICssBuilder>) loader.loadClass(KunagiCssBuilder.class.getName());
return type.newInstance();
} catch (Throwable ex) {
LOG.fatal(ex);
throw new RuntimeException(ex);
}
} else {
return screenCssBuilder;
}
}
}
| agpl-3.0 |
UCSolarCarTeam/Recruit-Resources | Recruit-Training/Advanced-Recruit-Training/Viscomm-Teaser/Viscomm-Teaser-Training/src/InformationParser.cpp | 164 | #include "InformationParser.h"
InformationParser::InformationParser()
{
}
bool InformationParser::readJSON()
{
//Place Function Code Here
return true;
}
| agpl-3.0 |
qcri-social/Crisis-Computing | aidr-db-manager/src/test/java/qa/qcri/aidr/dbmanager/ejb/remote/facade/imp/TestDocumentNominalLabelResourceFacadeImp.java | 15577 | /*
* 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 qa.qcri.aidr.dbmanager.ejb.remote.facade.imp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import qa.qcri.aidr.common.exception.PropertyNotSetException;
import qa.qcri.aidr.dbmanager.dto.CollectionDTO;
import qa.qcri.aidr.dbmanager.dto.CrisisTypeDTO;
import qa.qcri.aidr.dbmanager.dto.DocumentDTO;
import qa.qcri.aidr.dbmanager.dto.DocumentNominalLabelDTO;
import qa.qcri.aidr.dbmanager.dto.DocumentNominalLabelIdDTO;
import qa.qcri.aidr.dbmanager.dto.UsersDTO;
/**
*
* @author nalemadi
*/
public class TestDocumentNominalLabelResourceFacadeImp {
static DocumentNominalLabelResourceFacadeImp documentNominalLabelResourceFacadeImp;
static DocumentResourceFacadeImp documentResourceFacadeImp;
static EntityManager entityManager;
static CrisisTypeResourceFacadeImp crisisTypeResourceFacadeImp;
static UsersResourceFacadeImp userResourceFacadeImp;
static CollectionResourceFacadeImp crisisResourceFacadeImp;
static DocumentDTO document;
static CollectionDTO crisis;
static UsersDTO user;
static DocumentNominalLabelDTO documentNominalLabel;
static NominalLabelResourceFacadeImp nominalLabelResourceFacadeImp;
private static Logger logger = Logger.getLogger("db-manager-log");
@BeforeClass
public static void setUpClass() {
documentNominalLabelResourceFacadeImp = new DocumentNominalLabelResourceFacadeImp();
documentResourceFacadeImp = new DocumentResourceFacadeImp();
entityManager = Persistence.createEntityManagerFactory(
"ProjectDBManagerTest-ejbPU").createEntityManager();
documentNominalLabelResourceFacadeImp.setEntityManager(entityManager);
documentResourceFacadeImp.setEntityManager(entityManager);
crisisTypeResourceFacadeImp = new CrisisTypeResourceFacadeImp();
userResourceFacadeImp = new UsersResourceFacadeImp();
crisisResourceFacadeImp = new CollectionResourceFacadeImp();
crisisResourceFacadeImp.setEntityManager(entityManager);
crisisTypeResourceFacadeImp.setEntityManager(entityManager);
userResourceFacadeImp.setEntityManager(entityManager);
nominalLabelResourceFacadeImp = new NominalLabelResourceFacadeImp();
nominalLabelResourceFacadeImp.setEntityManager(entityManager);
document = addDocument();
}
@AfterClass
public static void tearDownClass() {
if (document != null) {
entityManager.getTransaction().begin();
documentResourceFacadeImp.deleteDocument(document);
entityManager.getTransaction().commit();
if (crisis != null) {
entityManager.getTransaction().begin();
try {
crisisResourceFacadeImp.deleteCrisis(crisis);
} catch (PropertyNotSetException e) {
e.printStackTrace();
}
entityManager.getTransaction().commit();
}
}
try {
if (user != null) {
entityManager.getTransaction().begin();
user = userResourceFacadeImp.getUserByName(user.getName());
userResourceFacadeImp.deleteUser(user.getUserID());
entityManager.getTransaction().commit();
}
}catch (PropertyNotSetException e) {
logger.error("PropertyNotSetException while deleting user "+e.getMessage());
}
documentNominalLabelResourceFacadeImp.getEntityManager().close();
}
@Before
public void setUp() {
try {
documentNominalLabel = getDocumentNominalLabel();
documentNominalLabel = documentNominalLabelResourceFacadeImp
.addDocument(documentNominalLabel);
} catch (PropertyNotSetException e) {
logger.error("PropertyNotSetException while adding document nominal label "+e.getMessage());
}
}
@After
public void tearDown() {
if (documentNominalLabel != null) {
documentNominalLabelResourceFacadeImp
.deleteDocument(documentNominalLabel);
}
}
private static DocumentNominalLabelDTO getDocumentNominalLabel() {
DocumentNominalLabelDTO documentNominalLabel = new DocumentNominalLabelDTO();
DocumentNominalLabelIdDTO idDTO = new DocumentNominalLabelIdDTO();
idDTO.setUserId(1L);
idDTO.setDocumentId(document.getDocumentID());
idDTO.setNominalLabelId(1L);
documentNominalLabel.setIdDTO(idDTO);
return documentNominalLabel;
}
private static DocumentDTO addDocument() {
DocumentDTO documentDTO = new DocumentDTO();
CrisisTypeDTO crisisTypeDTO = crisisTypeResourceFacadeImp.findCrisisTypeByID(1100L);
user = new UsersDTO("userDBTest"+new Date(), "normal"+new Date());
entityManager.getTransaction().begin();
user = userResourceFacadeImp.addUser(user);
entityManager.getTransaction().commit();
CollectionDTO crisisDTO = new CollectionDTO("testCrisisName"+new Date(), "testCrisisCode"+new Date(), false, false, crisisTypeDTO, user, user);
entityManager.getTransaction().begin();
crisis = crisisResourceFacadeImp.addCrisis(crisisDTO);
entityManager.getTransaction().commit();
String tweet = "\"filter_level\":\"medium\",\"retweeted\":false,\"in_reply_to_screen_name\":null,\"possibly_sensitive\":false,\"truncated\":false,\"lang\":\"en\",\"in_reply_to_status_id_str\":null,"
+ "\"id\":445125937915387905,\"in_reply_to_user_id_str\":null,\"in_reply_to_status_id\":null,\"created_at\":\"Sun Mar 16 09:14:28 +0000 2014\",\"favorite_count\":0,\"place\":null,\"coordinates\":null,"
+ "\"text\":\"'Those in the #cockpit' behind #missing #flight? http://t.co/OYHvM1t0CT\",\"contributors\":null,\"geo\":null,\"entities\":{\"hashtags\":[{\"text\":\"cockpit\",\"indices\":[14,22]},{\"text\":\"missing\","
+ "\"indices\":[31,39]},{\"text\":\"flight\",\"indices\":[40,47]}],\"symbols\":[],\"urls\":[{\"expanded_url\":\"http://www.cnn.com/2014/03/15/world/asia/malaysia-airlines-plane/index.html\""
+ ",\"indices\":[49,71],\"display_url\":\"cnn.com/2014/03/15/wor\u2026\",\"url\":\"http://t.co/OYHvM1t0CT\"}],\"user_mentions\":[]},\"aidr\":{\"crisis_code\":\"2014-03-mh370\""
+ ",\"doctype\":\"twitter\",\"crisis_name\":\"Malaysia Airlines flight #MH370\"},\"source\":\"\",\"favorited\":false,"
+ "\"retweet_count\":0,\"in_reply_to_user_id\":null,\"id_str\":\"445125937915387905\",\"user\":{\"location\":\"Mexico, Distrito Federal. \",\"default_profile\":true,\"statuses_count\":1033,"
+ "\"profile_background_tile\":false,\"lang\":\"en\",\"profile_link_color\":\"0084B4\",\"profile_banner_url\":\"https://pbs.twimg.com/profile_banners/135306436/1394809176\",\"id\":135306436,\"following\":null,"
+ "\"favourites_count\":6,\"protected\":false,\"profile_text_color\":\"333333\",\"description\":\"Licenciado en derecho, he ocupado cargos dentro de la industria privada as\u00ED como dentro de la Administraci\u00F3n P\u00FAblica, tanto local (GDF), como Federal.\","
+ "\"verified\":false,\"contributors_enabled\":false,\"profile_sidebar_border_color\":\"C0DEED\",\"name\":\"Leonardo Larraga\",\"profile_background_color\":\"C0DEED\",\"created_at\":\"Tue Apr 20 23:12:25 +0000 2010\","
+ "\"is_translation_enabled\":false,\"default_profile_image\":false,\"followers_count\":726,\"profile_image_url_https\":\"https://pbs.twimg.com/profile_images/440767007290429441/GkHsYcJj_normal.jpeg\","
+ "\"geo_enabled\":false,\"profile_background_image_url\":\"http://abs.twimg.com/images/themes/theme1/bg.png\",\"profile_background_image_url_https\":\"https://abs.twimg.com/images/themes/theme1/bg.png\","
+ "\"follow_request_sent\":null,\"url\":\"http://instagram.com/larraga_ld\",\"utc_offset\":-21600,\"time_zone\":\"Mexico City\",\"notifications\":null,\"friends_count\":150,\"profile_use_background_image\":true,"
+ "\"profile_sidebar_fill_color\":\"DDEEF6\",\"screen_name\":\"larraga_ld\",\"id_str\":\"135306436\",\"profile_image_url\":\"http://pbs.twimg.com/profile_images/440767007290429441/GkHsYcJj_normal.jpeg\","
+ "\"is_translator\":false,\"listed_count\":0}}";
String word = "{\"words\":[\"#prayformh370\"]}";
documentDTO.setCrisisDTO(crisis);
documentDTO.setHasHumanLabels(false);
documentDTO.setIsEvaluationSet(true);
documentDTO.setReceivedAt(new Date());
documentDTO.setLanguage("en");
documentDTO.setDoctype("Tweet");
documentDTO.setData(tweet);
documentDTO.setWordFeatures(word);
documentDTO.setValueAsTrainingSample(0.5);
entityManager.getTransaction().begin();
documentDTO = documentResourceFacadeImp.addDocument(documentDTO);
entityManager.getTransaction().commit();
return documentDTO;
}
/**
* Test of saveDocumentNominalLabel method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
/*
* @Test public void testSaveDocumentNominalLabel() throws Exception {
* DocumentNominalLabelDTO
* documentNominalLabel = new DocumentNominalLabelDTO();
* documentNominalLabel.setDocumentDTO(document);
*
* DocumentNominalLabelIdDTO documentNominalLabelIdDTO = new
* DocumentNominalLabelIdDTO(); documentNominalLabelIdDTO.setUserId(1L);
* documentNominalLabelIdDTO.setDocumentId(document.getDocumentID());
* documentNominalLabelIdDTO.setNominalLabelId(1L);
* documentNominalLabel.setNominalLabelDTO
* (nominalLabelResourceFacadeImp.getNominalLabelByID(1L));
* documentNominalLabelResourceFacadeImp
* .saveDocumentNominalLabel(documentNominalLabel); }
*/
/**
* Test of foundDuplicate method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
/*
* @Test public void testFoundDuplicate() { try {
* DocumentNominalLabelDTO
* documentNominalLabel =
* documentNominalLabelResourceFacadeImp.getAllDocuments().get(0); boolean
* result =
* documentNominalLabelResourceFacadeImp.foundDuplicate(documentNominalLabel
* ); assertEquals(false, result); } catch (PropertyNotSetException ex) {
* fail("foundDuplicate failed");
* //Logger.getLogger(DocumentNominalLabelResourceFacadeImpTest
* .class.getName()).log(Level.SEVERE, null, ex); } }
*/
/**
* Test of addDocument method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testAddDocument() throws Exception {
assertEquals(document.getDocumentID(), documentNominalLabel.getIdDTO()
.getDocumentId());
}
/**
* Test of editDocument method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
/*
* @Test public void testEditDocument() throws Exception {
* documentNominalLabel =
* getDocumentNominalLabel(); entityManager.getTransaction().begin();
* documentNominalLabel =
* documentNominalLabelResourceFacadeImp.addDocument(documentNominalLabel);
* entityManager.getTransaction().commit(); Date date = new Date();
* documentNominalLabel.setTimestamp(date);
* entityManager.getTransaction().begin(); documentNominalLabel =
* documentNominalLabelResourceFacadeImp.editDocument(documentNominalLabel);
* entityManager.getTransaction().commit(); assertEquals(date,
* documentNominalLabel.getTimestamp()); }
*/
/**
* Test of deleteDocument method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testDeleteDocument() throws Exception {
Integer result = documentNominalLabelResourceFacadeImp
.deleteDocument(documentNominalLabel);
assertEquals(Integer.valueOf(1), result);
documentNominalLabel = null;
}
/**
* Test of findByCriteria method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testFindByCriteria() {
try {
String columnName = "id.documentId";
Long value = documentNominalLabel.getIdDTO().getDocumentId();
List<DocumentNominalLabelDTO> result = documentNominalLabelResourceFacadeImp
.findByCriteria(columnName, value);
assertNotNull(result);
assertEquals(value, result.get(0).getIdDTO().getDocumentId());
} catch (PropertyNotSetException ex) {
logger.error("PropertyNotSetException while finding document nominal label by criteria "+ex.getMessage());
fail("findByCriteria failed");
}
}
/**
* Test of findDocumentByPrimaryKey method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testFindDocumentByPrimaryKey() {
try {
DocumentNominalLabelDTO result = documentNominalLabelResourceFacadeImp
.findDocumentByPrimaryKey(documentNominalLabel.getIdDTO());
assertEquals(documentNominalLabel.getIdDTO().getDocumentId(),
result.getDocumentDTO().getDocumentID());
} catch (PropertyNotSetException ex) {
logger.error("PropertyNotSetException while finding document nominal label by primary key "+ex.getMessage());
fail("findDocumentByPrimaryKey failed");
}
}
/**
* Test of isDocumentExists method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testIsDocumentExists_DocumentNominalLabelIdDTO()
throws Exception {
boolean result = documentNominalLabelResourceFacadeImp
.isDocumentExists(documentNominalLabel.getIdDTO());
assertEquals(true, result);
}
/**
* Test of isDocumentExists method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testIsDocumentExists_Long() throws Exception {
boolean result = documentNominalLabelResourceFacadeImp
.isDocumentExists(documentNominalLabel.getIdDTO());
assertEquals(true, result);
boolean result2 = documentNominalLabelResourceFacadeImp
.isDocumentExists(documentNominalLabel.getIdDTO()
.getDocumentId());
assertEquals(true, result2);
}
/**
* Test of getAllDocuments method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testGetAllDocuments() {
try {
List<DocumentNominalLabelDTO> result = documentNominalLabelResourceFacadeImp
.getAllDocuments();
assertNotNull(result);
assertTrue(result.size() >= 1);
} catch (PropertyNotSetException ex) {
logger.error("PropertyNotSetException while fetching all document nominal label "+ex.getMessage());
fail("getAllDocuments failed");
}
}
/**
* Test of findLabeledDocumentByID method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testFindLabeledDocumentByID() {
try {
DocumentNominalLabelDTO result = documentNominalLabelResourceFacadeImp
.findLabeledDocumentByID(documentNominalLabel.getIdDTO()
.getDocumentId());
assertEquals(documentNominalLabel.getIdDTO().getDocumentId(),
result.getDocumentDTO().getDocumentID());
} catch (PropertyNotSetException ex) {
logger.error("PropertyNotSetException while finding labelled documents by id "+ex.getMessage());
fail("findLabeledDocumentByID failed");
}
}
/**
* Test of getLabeledDocumentCollectionForNominalLabel method, of class
* DocumentNominalLabelResourceFacadeImp.
*/
@Test
public void testGetLabeledDocumentCollectionForNominalLabel()
throws Exception {
List<DocumentNominalLabelDTO> result = documentNominalLabelResourceFacadeImp
.getLabeledDocumentCollectionForNominalLabel(documentNominalLabel
.getIdDTO().getNominalLabelId().intValue());
assertNotNull(result);
assertTrue(result.size() >= 1);
}
}
| agpl-3.0 |
StanfordBioinformatics/loom | client/loomengine/run_label.py | 7876 | #!/usr/bin/env python
import argparse
import os
import sys
from loomengine import server
from loomengine import verify_has_connection_settings, \
get_server_url, verify_server_is_running, get_token
from loomengine_utils.connection import Connection
from loomengine_utils.exceptions import LoomengineUtilsError
class RunLabelAdd(object):
"""Add a new run labels
"""
def __init__(self, args=None, silent=False):
# Args may be given as an input argument for testing purposes
# or from the main parser.
# Otherwise get them from the parser.
if args is None:
args = self._get_args()
self.args = args
self.silent = silent
verify_has_connection_settings()
server_url = get_server_url()
verify_server_is_running(url=server_url)
self.connection = Connection(server_url, token=get_token())
def _get_args(self):
self.parser = self.get_parser()
return self.parser.parse_args()
@classmethod
def get_parser(cls, parser=None):
# If called from main, use the subparser provided.
# Otherwise create a top-level parser here.
if parser is None:
parser = argparse.ArgumentParser(__file__)
parser.add_argument(
'target',
metavar='TARGET',
help='identifier for run to be labeled')
parser.add_argument(
'label',
metavar='LABEL', help='label name to be added')
return parser
def run(self):
try:
runs = self.connection.get_run_index(
min=1, max=1,
query_string=self.args.target)
except LoomengineUtilsError as e:
raise SystemExit("ERROR! Failed to get run list: '%s'" % e)
label_data = {'label': self.args.label}
try:
label = self.connection.post_run_label(runs[0]['uuid'], label_data)
except LoomengineUtilsError as e:
raise SystemExit("ERROR! Failed to create label: '%s'" % e)
if not self.silent:
print 'Target "%s@%s" has been labeled as "%s"' % \
(runs[0].get('name'),
runs[0].get('uuid'),
label.get('label'))
class RunLabelRemove(object):
"""Remove a run label
"""
def __init__(self, args=None, silent=False):
if args is None:
args = self._get_args()
self.args = args
self.silent = silent
verify_has_connection_settings()
server_url = get_server_url()
verify_server_is_running(url=server_url)
self.connection = Connection(server_url, token=get_token())
def _get_args(self):
self.parser = self.get_parser()
return self.parser.parse_args()
@classmethod
def get_parser(cls, parser=None):
# If called from main, use the subparser provided.
# Otherwise create a top-level parser here.
if parser is None:
parser = argparse.ArgumentParser(__file__)
parser.add_argument(
'target',
metavar='TARGET',
help='identifier for run to be unlabeled')
parser.add_argument(
'label',
metavar='LABEL', help='label name to be removed')
return parser
def run(self):
try:
runs = self.connection.get_run_index(
min=1, max=1,
query_string=self.args.target)
except LoomengineUtilsError as e:
raise SystemExit("ERROR! Failed to get run list: '%s'" % e)
label_data = {'label': self.args.label}
try:
label = self.connection.remove_run_label(
runs[0]['uuid'], label_data)
except LoomengineUtilsError as e:
raise SystemExit("ERROR! Failed to remove label: '%s'" % e)
if not self.silent:
print 'Label %s has been removed from run "%s@%s"' % \
(label.get('label'),
runs[0].get('name'),
runs[0].get('uuid'))
class RunLabelList(object):
def __init__(self, args=None, silent=False):
if args is None:
args = self._get_args()
self.args = args
self.silent = silent
verify_has_connection_settings()
server_url = get_server_url()
verify_server_is_running(url=server_url)
self.connection = Connection(server_url, token=get_token())
def _get_args(self):
self.parser = self.get_parser()
return self.parser.parse_args()
@classmethod
def get_parser(cls, parser=None):
# If called from main, use the subparser provided.
# Otherwise create a top-level parser here.
if parser is None:
parser = argparse.ArgumentParser(__file__)
parser.add_argument(
'target',
metavar='TARGET',
nargs='?',
help='show labels only for the specified run')
return parser
def run(self):
if self.args.target:
try:
runs = self.connection.get_run_index(
min=1, max=1,
query_string=self.args.target)
except LoomengineUtilsError as e:
raise SystemExit("ERROR! Failed to get run list: '%s'" % e)
try:
label_data = self.connection.list_run_labels(runs[0]['uuid'])
except LoomengineUtilsError as e:
raise SystemExit("ERROR! Failed to get label list: '%s'" % e)
labels = label_data.get('labels', [])
if not self.silent:
print '[showing %s labels]' % len(labels)
for label in labels:
print label
else:
try:
label_list = self.connection.get_run_label_index()
except LoomengineUtilsError as e:
raise SystemExit("ERROR! Failed to get label list: '%s'" % e)
label_counts = {}
for item in label_list:
label_counts.setdefault(item.get('label'), 0)
label_counts[item.get('label')] += 1
if not self.silent:
print '[showing %s labels]' % len(label_counts)
for key in label_counts:
print "%s (%s)" % (key, label_counts[key])
class RunLabel(object):
"""Configures and executes subcommands under "label" on the parent parser.
"""
def __init__(self, args=None, silent=False):
if args is None:
args = self._get_args()
self.args = args
self.silent = silent
def _get_args(self):
parser = self.get_parser()
return parser.parse_args()
@classmethod
def get_parser(cls, parser=None):
# If called from main, a subparser should be provided.
# Otherwise we create a top-level parser here.
if parser is None:
parser = argparse.ArgumentParser(__file__)
subparsers = parser.add_subparsers()
add_subparser = subparsers.add_parser(
'add', help='add a run label')
RunLabelAdd.get_parser(add_subparser)
add_subparser.set_defaults(SubSubSubcommandClass=RunLabelAdd)
remove_subparser = subparsers.add_parser(
'remove', help='remove a run label')
RunLabelRemove.get_parser(remove_subparser)
remove_subparser.set_defaults(SubSubSubcommandClass=RunLabelRemove)
list_subparser = subparsers.add_parser(
'list', help='list run labels')
RunLabelList.get_parser(list_subparser)
list_subparser.set_defaults(SubSubSubcommandClass=RunLabelList)
return parser
def run(self):
return self.args.SubSubSubcommandClass(
self.args, silent=self.silent).run()
if __name__ == '__main__':
response = RunLabel().run()
| agpl-3.0 |
ClearCorp/odoo-clearcorp | TODO-9.0/budget/stock.py | 3050 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class stock_picking(osv.osv):
_inherit = 'stock.picking'
def action_invoice_create(self, cr, uid, ids, journal_id=False,
group=False, type='out_invoice', context=None):
obj_bud_mov = self.pool.get('budget.move')
obj_bud_line = self.pool.get('budget.move.line')
purchase_line_obj = self.pool.get('purchase.order.line')
invoice_obj = self.pool.get('account.invoice')
purchase_obj = self.pool.get('purchase.order')
invoice_line_obj = self.pool.get('account.invoice.line')
invoices= super(stock_picking, self).action_invoice_create(cr, uid, ids, journal_id=journal_id, group=group, type=type, context=context)
res = {}
res= {'res':invoices,}
for picking in res.keys():
invoice_id = res[picking]
invoice = invoice_obj.browse(cr, uid, invoice_id, context=context)
for invoice_line in invoice.invoice_line:
#purchase_order_line_invoice_rel
cr.execute('''SELECT order_line_id FROM purchase_order_line_invoice_rel \
WHERE invoice_id = %s''',(invoice_line.id,))
count = cr.fetchall()
for po_line_id in count:
po_line = purchase_line_obj.browse(cr, uid, [po_line_id[0]], context=context)
asoc_bud_line_id = obj_bud_line.search(cr, uid, [('po_line_id','=',po_line.id), ])[0]
obj_bud_line.write(cr, uid, [asoc_bud_line_id],{'inv_line_id': invoice_line.id}, context=context)
move_id = po_line.order_id.budget_move_id.id
invoice_obj.write(cr, uid, invoice_id, {'budget_move_id': move_id, 'from_order':True}, context=context)
obj_bud_mov.signal_workflow(cr, uid, [move_id], 'button_execute', context=context)
return invoices
| agpl-3.0 |
jameinel/juju | core/constraints/constraints_test.go | 29572 | // Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package constraints_test
import (
"encoding/json"
"fmt"
"strings"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
goyaml "gopkg.in/yaml.v2"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/instance"
)
type ConstraintsSuite struct{}
var _ = gc.Suite(&ConstraintsSuite{})
var parseConstraintsTests = []struct {
summary string
args []string
err string
result *constraints.Value
}{
// Simple errors.
{
summary: "nothing at all",
}, {
summary: "empty",
args: []string{" "},
}, {
summary: "complete nonsense",
args: []string{"cheese"},
err: `malformed constraint "cheese"`,
}, {
summary: "missing name",
args: []string{"=cheese"},
err: `malformed constraint "=cheese"`,
}, {
summary: "unknown constraint",
args: []string{"cheese=edam"},
err: `unknown constraint "cheese"`,
},
// "container" in detail.
{
summary: "set container empty",
args: []string{"container="},
}, {
summary: "set container to none",
args: []string{"container=none"},
}, {
summary: "set container lxd",
args: []string{"container=lxd"},
}, {
summary: "set nonsense container",
args: []string{"container=foo"},
err: `bad "container" constraint: invalid container type "foo"`,
}, {
summary: "double set container together",
args: []string{"container=lxd container=lxd"},
err: `bad "container" constraint: already set`,
}, {
summary: "double set container separately",
args: []string{"container=lxd", "container="},
err: `bad "container" constraint: already set`,
},
// "arch" in detail.
{
summary: "set arch empty",
args: []string{"arch="},
}, {
summary: "set arch amd64",
args: []string{"arch=amd64"},
}, {
summary: "set arch i386",
args: []string{"arch=i386"},
}, {
summary: "set arch armhf",
args: []string{"arch=armhf"},
}, {
summary: "set nonsense arch 1",
args: []string{"arch=cheese"},
err: `bad "arch" constraint: "cheese" not recognized`,
}, {
summary: "set nonsense arch 2",
args: []string{"arch=123.45"},
err: `bad "arch" constraint: "123.45" not recognized`,
}, {
summary: "double set arch together",
args: []string{"arch=amd64 arch=amd64"},
err: `bad "arch" constraint: already set`,
}, {
summary: "double set arch separately",
args: []string{"arch=armhf", "arch="},
err: `bad "arch" constraint: already set`,
},
// "cores" in detail.
{
summary: "set cores empty",
args: []string{"cores="},
}, {
summary: "set cores zero",
args: []string{"cores=0"},
}, {
summary: "set cores",
args: []string{"cores=4"},
}, {
summary: "set nonsense cores 1",
args: []string{"cores=cheese"},
err: `bad "cores" constraint: must be a non-negative integer`,
}, {
summary: "set nonsense cores 2",
args: []string{"cores=-1"},
err: `bad "cores" constraint: must be a non-negative integer`,
}, {
summary: "set nonsense cores 3",
args: []string{"cores=123.45"},
err: `bad "cores" constraint: must be a non-negative integer`,
}, {
summary: "double set cores together",
args: []string{"cores=128 cores=1"},
err: `bad "cores" constraint: already set`,
}, {
summary: "double set cores separately",
args: []string{"cores=128", "cores=1"},
err: `bad "cores" constraint: already set`,
},
// "cpu-cores"
{
summary: "set cpu-cores",
args: []string{"cpu-cores=4"},
},
// "cpu-power" in detail.
{
summary: "set cpu-power empty",
args: []string{"cpu-power="},
}, {
summary: "set cpu-power zero",
args: []string{"cpu-power=0"},
}, {
summary: "set cpu-power",
args: []string{"cpu-power=44"},
}, {
summary: "set nonsense cpu-power 1",
args: []string{"cpu-power=cheese"},
err: `bad "cpu-power" constraint: must be a non-negative integer`,
}, {
summary: "set nonsense cpu-power 2",
args: []string{"cpu-power=-1"},
err: `bad "cpu-power" constraint: must be a non-negative integer`,
}, {
summary: "double set cpu-power together",
args: []string{" cpu-power=300 cpu-power=1700 "},
err: `bad "cpu-power" constraint: already set`,
}, {
summary: "double set cpu-power separately",
args: []string{"cpu-power=300 ", " cpu-power=1700"},
err: `bad "cpu-power" constraint: already set`,
},
// "mem" in detail.
{
summary: "set mem empty",
args: []string{"mem="},
}, {
summary: "set mem zero",
args: []string{"mem=0"},
}, {
summary: "set mem without suffix",
args: []string{"mem=512"},
}, {
summary: "set mem with M suffix",
args: []string{"mem=512M"},
}, {
summary: "set mem with G suffix",
args: []string{"mem=1.5G"},
}, {
summary: "set mem with T suffix",
args: []string{"mem=36.2T"},
}, {
summary: "set mem with P suffix",
args: []string{"mem=18.9P"},
}, {
summary: "set nonsense mem 1",
args: []string{"mem=cheese"},
err: `bad "mem" constraint: must be a non-negative float with optional M/G/T/P suffix`,
}, {
summary: "set nonsense mem 2",
args: []string{"mem=-1"},
err: `bad "mem" constraint: must be a non-negative float with optional M/G/T/P suffix`,
}, {
summary: "set nonsense mem 3",
args: []string{"mem=32Y"},
err: `bad "mem" constraint: must be a non-negative float with optional M/G/T/P suffix`,
}, {
summary: "double set mem together",
args: []string{"mem=1G mem=2G"},
err: `bad "mem" constraint: already set`,
}, {
summary: "double set mem separately",
args: []string{"mem=1G", "mem=2G"},
err: `bad "mem" constraint: already set`,
},
// "root-disk" in detail.
{
summary: "set root-disk empty",
args: []string{"root-disk="},
}, {
summary: "set root-disk zero",
args: []string{"root-disk=0"},
}, {
summary: "set root-disk without suffix",
args: []string{"root-disk=512"},
}, {
summary: "set root-disk with M suffix",
args: []string{"root-disk=512M"},
}, {
summary: "set root-disk with G suffix",
args: []string{"root-disk=1.5G"},
}, {
summary: "set root-disk with T suffix",
args: []string{"root-disk=36.2T"},
}, {
summary: "set root-disk with P suffix",
args: []string{"root-disk=18.9P"},
}, {
summary: "set nonsense root-disk 1",
args: []string{"root-disk=cheese"},
err: `bad "root-disk" constraint: must be a non-negative float with optional M/G/T/P suffix`,
}, {
summary: "set nonsense root-disk 2",
args: []string{"root-disk=-1"},
err: `bad "root-disk" constraint: must be a non-negative float with optional M/G/T/P suffix`,
}, {
summary: "set nonsense root-disk 3",
args: []string{"root-disk=32Y"},
err: `bad "root-disk" constraint: must be a non-negative float with optional M/G/T/P suffix`,
}, {
summary: "double set root-disk together",
args: []string{"root-disk=1G root-disk=2G"},
err: `bad "root-disk" constraint: already set`,
}, {
summary: "double set root-disk separately",
args: []string{"root-disk=1G", "root-disk=2G"},
err: `bad "root-disk" constraint: already set`,
},
// root-disk-source in detail.
{
summary: "set root-disk-source empty",
args: []string{"root-disk-source="},
}, {
summary: "set root-disk-source to a value",
args: []string{"root-disk-source=sourcename"},
}, {
summary: "double set root-disk-source together",
args: []string{"root-disk-source=sourcename root-disk-source=somethingelse"},
err: `bad "root-disk-source" constraint: already set`,
}, {
summary: "double set root-disk-source separately",
args: []string{"root-disk-source=sourcename", "root-disk-source=somethingelse"},
err: `bad "root-disk-source" constraint: already set`,
},
// tags
{
summary: "single tag",
args: []string{"tags=foo"},
}, {
summary: "multiple tags",
args: []string{"tags=foo,bar"},
}, {
summary: "no tags",
args: []string{"tags="},
},
// spaces
{
summary: "single space",
args: []string{"spaces=space1"},
}, {
summary: "multiple spaces - positive",
args: []string{"spaces=space1,space2"},
}, {
summary: "multiple spaces - negative",
args: []string{"spaces=^dmz,^public"},
}, {
summary: "multiple spaces - positive and negative",
args: []string{"spaces=admin,^area52,dmz,^public"},
}, {
summary: "no spaces",
args: []string{"spaces="},
},
// instance roles
{
summary: "set instance role",
args: []string{"instance-role=foobarir"},
}, {
summary: "instance role empty",
args: []string{"instance-role="},
}, {
summary: "instance role auto",
args: []string{"instance-role=auto"},
},
// instance type
{
summary: "set instance type",
args: []string{"instance-type=foo"},
}, {
summary: "instance type empty",
args: []string{"instance-type="},
}, {
summary: "instance type with slash-escaped spaces",
args: []string{`instance-type=something\ with\ spaces`},
},
// "virt-type" in detail.
{
summary: "set virt-type empty",
args: []string{"virt-type="},
}, {
summary: "set virt-type kvm",
args: []string{"virt-type=kvm"},
}, {
summary: "set virt-type lxd",
args: []string{"virt-type=lxd"},
}, {
summary: "double set virt-type together",
args: []string{"virt-type=kvm virt-type=kvm"},
err: `bad "virt-type" constraint: already set`,
}, {
summary: "double set virt-type separately",
args: []string{"virt-type=kvm", "virt-type="},
err: `bad "virt-type" constraint: already set`,
},
// Zones
{
summary: "single zone",
args: []string{"zones=az1"},
}, {
summary: "multiple zones",
args: []string{"zones=az1,az2"},
}, {
summary: "zones with slash-escaped spaces",
args: []string{`zones=Availability\ zone\ 1`},
}, {
summary: "Multiple zones with slash-escaped spaces",
args: []string{`zones=Availability\ zone\ 1,Availability\ zone\ 2,az2`},
}, {
summary: "no zones",
args: []string{"zones="},
},
// AllocatePublicIP
{
summary: "set allocate-public-ip",
args: []string{"allocate-public-ip=true"},
}, {
summary: "set nonsense allocate-public-ip",
args: []string{"allocate-public-ip=fred"},
err: `bad "allocate-public-ip" constraint: must be 'true' or 'false'`,
}, {
summary: "try to set allocate-public-ip twice",
args: []string{"allocate-public-ip=true allocate-public-ip=false"},
err: `bad "allocate-public-ip" constraint: already set`,
},
// Everything at once.
{
summary: "kitchen sink together",
args: []string{
"root-disk=8G mem=2T arch=i386 cores=4096 cpu-power=9001 container=lxd " +
"tags=foo,bar spaces=space1,^space2 instance-type=foo " +
"instance-role=foo1",
"virt-type=kvm zones=az1,az2 allocate-public-ip=true root-disk-source=sourcename"},
result: &constraints.Value{
Arch: strp("i386"),
Container: (*instance.ContainerType)(strp("lxd")),
CpuCores: uint64p(4096),
CpuPower: uint64p(9001),
Mem: uint64p(2 * 1024 * 1024),
RootDisk: uint64p(8192),
RootDiskSource: strp("sourcename"),
Tags: &[]string{"foo", "bar"},
Spaces: &[]string{"space1", "^space2"},
InstanceRole: strp("foo1"),
InstanceType: strp("foo"),
VirtType: strp("kvm"),
Zones: &[]string{"az1", "az2"},
AllocatePublicIP: boolp(true),
},
}, {
summary: "kitchen sink separately",
args: []string{
"root-disk=8G", "mem=2T", "cores=4096", "cpu-power=9001", "arch=armhf",
"container=lxd", "tags=foo,bar", "spaces=space1,^space2",
"instance-type=foo", "virt-type=kvm", "zones=az1,az2", "allocate-public-ip=false",
"instance-role=foo2"},
result: &constraints.Value{
Arch: strp("armhf"),
Container: (*instance.ContainerType)(strp("lxd")),
CpuCores: uint64p(4096),
CpuPower: uint64p(9001),
Mem: uint64p(2 * 1024 * 1024),
RootDisk: uint64p(8192),
Tags: &[]string{"foo", "bar"},
Spaces: &[]string{"space1", "^space2"},
InstanceRole: strp("foo2"),
InstanceType: strp("foo"),
VirtType: strp("kvm"),
Zones: &[]string{"az1", "az2"},
AllocatePublicIP: boolp(false),
},
}, {
summary: "kitchen sink together with spaced zones",
args: []string{
`root-disk=8G mem=2T arch=i386 cores=4096 zones=Availability\ zone\ 1 cpu-power=9001 container=lxd ` +
"tags=foo,bar spaces=space1,^space2 instance-type=foo instance-role=foo3",
"virt-type=kvm"},
result: &constraints.Value{
Arch: strp("i386"),
Container: (*instance.ContainerType)(strp("lxd")),
CpuCores: uint64p(4096),
CpuPower: uint64p(9001),
Mem: uint64p(2 * 1024 * 1024),
RootDisk: uint64p(8192),
Tags: &[]string{"foo", "bar"},
Spaces: &[]string{"space1", "^space2"},
InstanceRole: strp("foo3"),
InstanceType: strp("foo"),
VirtType: strp("kvm"),
Zones: &[]string{"Availability zone 1"},
},
},
}
func (s *ConstraintsSuite) TestParseConstraints(c *gc.C) {
// TODO(dimitern): This test is inadequate and needs to check for
// more than just the reparsed output of String() matches the
// expected.
for i, t := range parseConstraintsTests {
c.Logf("test %d: %s", i, t.summary)
cons0, err := constraints.Parse(t.args...)
if t.err == "" {
c.Assert(err, jc.ErrorIsNil)
} else {
c.Assert(err, gc.ErrorMatches, t.err)
continue
}
if t.result != nil {
c.Check(cons0, gc.DeepEquals, *t.result)
}
cons1, err := constraints.Parse(cons0.String())
c.Check(err, jc.ErrorIsNil)
c.Check(cons1, gc.DeepEquals, cons0)
}
}
func (s *ConstraintsSuite) TestParseAliases(c *gc.C) {
v, aliases, err := constraints.ParseWithAliases("cpu-cores=5 arch=amd64")
c.Assert(err, jc.ErrorIsNil)
c.Assert(v, gc.DeepEquals, constraints.Value{
CpuCores: uint64p(5),
Arch: strp("amd64"),
})
c.Assert(aliases, gc.DeepEquals, map[string]string{
"cpu-cores": "cores",
})
}
func (s *ConstraintsSuite) TestMerge(c *gc.C) {
con1 := constraints.MustParse("arch=amd64 mem=4G")
con2 := constraints.MustParse("cores=42")
con3 := constraints.MustParse(
"root-disk=8G container=lxd spaces=space1,^space2",
)
merged, err := constraints.Merge(con1, con2)
c.Assert(err, jc.ErrorIsNil)
c.Assert(merged, jc.DeepEquals, constraints.MustParse("arch=amd64 mem=4G cores=42"))
merged, err = constraints.Merge(con1)
c.Assert(err, jc.ErrorIsNil)
c.Assert(merged, jc.DeepEquals, con1)
merged, err = constraints.Merge(con1, con2, con3)
c.Assert(err, jc.ErrorIsNil)
c.Assert(merged, jc.DeepEquals, constraints.
MustParse("arch=amd64 mem=4G cores=42 root-disk=8G container=lxd spaces=space1,^space2"),
)
merged, err = constraints.Merge()
c.Assert(err, jc.ErrorIsNil)
c.Assert(merged, jc.DeepEquals, constraints.Value{})
foo := "foo"
merged, err = constraints.Merge(constraints.Value{Arch: &foo}, con2)
c.Assert(err, gc.NotNil)
c.Assert(err, gc.ErrorMatches, `bad "arch" constraint: "foo" not recognized`)
c.Assert(merged, jc.DeepEquals, constraints.Value{})
merged, err = constraints.Merge(con1, con1)
c.Assert(err, gc.NotNil)
c.Assert(err, gc.ErrorMatches, `bad "arch" constraint: already set`)
c.Assert(merged, jc.DeepEquals, constraints.Value{})
}
func (s *ConstraintsSuite) TestParseInstanceTypeWithSpaces(c *gc.C) {
con := constraints.MustParse(
`arch=amd64 instance-type=with\ spaces cores=1`,
)
c.Assert(con.Arch, gc.Not(gc.IsNil))
c.Assert(con.InstanceType, gc.Not(gc.IsNil))
c.Assert(con.CpuCores, gc.Not(gc.IsNil))
c.Check(*con.Arch, gc.Equals, "amd64")
c.Check(*con.InstanceType, gc.Equals, "with spaces")
c.Check(*con.CpuCores, gc.Equals, uint64(1))
}
func (s *ConstraintsSuite) TestParseMissingTagsAndSpaces(c *gc.C) {
con := constraints.MustParse("arch=amd64 mem=4G cores=1 root-disk=8G")
c.Check(con.Tags, gc.IsNil)
c.Check(con.Spaces, gc.IsNil)
}
func (s *ConstraintsSuite) TestParseNoTagsNoSpaces(c *gc.C) {
con := constraints.MustParse(
"arch=amd64 mem=4G cores=1 root-disk=8G tags= spaces=",
)
c.Assert(con.Tags, gc.Not(gc.IsNil))
c.Assert(con.Spaces, gc.Not(gc.IsNil))
c.Check(*con.Tags, gc.HasLen, 0)
c.Check(*con.Spaces, gc.HasLen, 0)
}
func (s *ConstraintsSuite) TestIncludeExcludeAndHasSpaces(c *gc.C) {
con := constraints.MustParse("spaces=space1,^space2,space3,^space4")
c.Assert(con.Spaces, gc.Not(gc.IsNil))
c.Check(*con.Spaces, gc.HasLen, 4)
c.Check(con.IncludeSpaces(), jc.SameContents, []string{"space1", "space3"})
c.Check(con.ExcludeSpaces(), jc.SameContents, []string{"space2", "space4"})
c.Check(con.HasSpaces(), jc.IsTrue)
con = constraints.MustParse("mem=4G")
c.Check(con.HasSpaces(), jc.IsFalse)
con = constraints.MustParse("mem=4G spaces=space-foo,^space-bar")
c.Check(con.IncludeSpaces(), jc.SameContents, []string{"space-foo"})
c.Check(con.ExcludeSpaces(), jc.SameContents, []string{"space-bar"})
c.Check(con.HasSpaces(), jc.IsTrue)
}
func (s *ConstraintsSuite) TestInvalidSpaces(c *gc.C) {
invalidNames := []string{
"%$pace", "^foo#2", "+", "tcp:ip",
"^^myspace", "^^^^^^^^", "space^x",
"&-foo", "space/3", "^bar=4", "&#!",
}
for _, name := range invalidNames {
con, err := constraints.Parse("spaces=" + name)
expectName := strings.TrimPrefix(name, "^")
expectErr := fmt.Sprintf(`bad "spaces" constraint: %q is not a valid space name`, expectName)
c.Check(err, gc.NotNil)
c.Check(err.Error(), gc.Equals, expectErr)
c.Check(con, jc.DeepEquals, constraints.Value{})
}
}
func (s *ConstraintsSuite) TestHasZones(c *gc.C) {
con := constraints.MustParse("zones=az1,az2,az3")
c.Assert(con.Zones, gc.Not(gc.IsNil))
c.Check(*con.Zones, gc.HasLen, 3)
c.Check(con.HasZones(), jc.IsTrue)
con = constraints.MustParse("zones=")
c.Check(con.HasZones(), jc.IsFalse)
con = constraints.MustParse("spaces=space1,^space2")
c.Check(con.HasZones(), jc.IsFalse)
}
func (s *ConstraintsSuite) TestHasAllocatePublicIP(c *gc.C) {
con := constraints.MustParse("allocate-public-ip=true")
c.Assert(con.AllocatePublicIP, gc.Not(gc.IsNil))
c.Check(con.HasAllocatePublicIP(), jc.IsTrue)
con = constraints.MustParse("allocate-public-ip=")
c.Check(con.HasAllocatePublicIP(), jc.IsFalse)
con = constraints.MustParse("spaces=space1,^space2")
c.Check(con.HasAllocatePublicIP(), jc.IsFalse)
}
func (s *ConstraintsSuite) TestHasRootDiskSource(c *gc.C) {
con := constraints.MustParse("root-disk-source=pilgrim")
c.Check(con.HasRootDiskSource(), jc.IsTrue)
con = constraints.MustParse("root-disk-source=")
c.Check(con.HasRootDiskSource(), jc.IsFalse)
con = constraints.MustParse("root-disk=32G")
c.Check(con.HasRootDiskSource(), jc.IsFalse)
}
func (s *ConstraintsSuite) TestHasRootDisk(c *gc.C) {
con := constraints.MustParse("root-disk=32G")
c.Check(con.HasRootDisk(), jc.IsTrue)
con = constraints.MustParse("root-disk=")
c.Check(con.HasRootDisk(), jc.IsFalse)
con = constraints.MustParse("root-disk-source=pilgrim")
c.Check(con.HasRootDisk(), jc.IsFalse)
}
func (s *ConstraintsSuite) TestIsEmpty(c *gc.C) {
con := constraints.Value{}
c.Check(&con, jc.Satisfies, constraints.IsEmpty)
con = constraints.MustParse("arch=amd64")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("")
c.Check(&con, jc.Satisfies, constraints.IsEmpty)
con = constraints.MustParse("tags=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("spaces=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("mem=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("arch=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("root-disk=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("cpu-power=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("cores=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("container=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("instance-role=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("instance-type=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("zones=")
c.Check(&con, gc.Not(jc.Satisfies), constraints.IsEmpty)
con = constraints.MustParse("allocate-public-ip=")
c.Check(&con, jc.Satisfies, constraints.IsEmpty)
}
func boolp(b bool) *bool {
return &b
}
func uint64p(i uint64) *uint64 {
return &i
}
func strp(s string) *string {
return &s
}
func ctypep(ctype string) *instance.ContainerType {
res := instance.ContainerType(ctype)
return &res
}
type roundTrip struct {
Name string
Value constraints.Value
}
var constraintsRoundtripTests = []roundTrip{
{"empty", constraints.Value{}},
{"Arch1", constraints.Value{Arch: strp("")}},
{"Arch2", constraints.Value{Arch: strp("amd64")}},
{"Container1", constraints.Value{Container: ctypep("")}},
{"Container2", constraints.Value{Container: ctypep("lxd")}},
{"Container3", constraints.Value{Container: nil}},
{"CpuCores1", constraints.Value{CpuCores: nil}},
{"CpuCores2", constraints.Value{CpuCores: uint64p(0)}},
{"CpuCores3", constraints.Value{CpuCores: uint64p(128)}},
{"CpuPower1", constraints.Value{CpuPower: nil}},
{"CpuPower2", constraints.Value{CpuPower: uint64p(0)}},
{"CpuPower3", constraints.Value{CpuPower: uint64p(250)}},
{"Mem1", constraints.Value{Mem: nil}},
{"Mem2", constraints.Value{Mem: uint64p(0)}},
{"Mem3", constraints.Value{Mem: uint64p(98765)}},
{"RootDisk1", constraints.Value{RootDisk: nil}},
{"RootDisk2", constraints.Value{RootDisk: uint64p(0)}},
{"RootDisk2", constraints.Value{RootDisk: uint64p(109876)}},
{"RootDiskSource1", constraints.Value{RootDiskSource: nil}},
{"RootDiskSource2", constraints.Value{RootDiskSource: strp("identikit")}},
{"Tags1", constraints.Value{Tags: nil}},
{"Tags2", constraints.Value{Tags: &[]string{}}},
{"Tags3", constraints.Value{Tags: &[]string{"foo", "bar"}}},
{"Spaces1", constraints.Value{Spaces: nil}},
{"Spaces2", constraints.Value{Spaces: &[]string{}}},
{"Spaces3", constraints.Value{Spaces: &[]string{"space1", "^space2"}}},
{"InstanceRole1", constraints.Value{InstanceRole: strp("")}},
{"InstanceRole2", constraints.Value{InstanceRole: strp("foo")}},
{"InstanceType1", constraints.Value{InstanceType: strp("")}},
{"InstanceType2", constraints.Value{InstanceType: strp("foo")}},
{"Zones1", constraints.Value{Zones: nil}},
{"Zones2", constraints.Value{Zones: &[]string{}}},
{"Zones3", constraints.Value{Zones: &[]string{"az1", "az2"}}},
{"AllocatePublicIP1", constraints.Value{AllocatePublicIP: nil}},
{"AllocatePublicIP2", constraints.Value{AllocatePublicIP: boolp(true)}},
{"All", constraints.Value{
Arch: strp("i386"),
Container: ctypep("lxd"),
CpuCores: uint64p(4096),
CpuPower: uint64p(9001),
Mem: uint64p(18000000000),
RootDisk: uint64p(24000000000),
RootDiskSource: strp("cave"),
Tags: &[]string{"foo", "bar"},
Spaces: &[]string{"space1", "^space2"},
InstanceType: strp("foo"),
Zones: &[]string{"az1", "az2"},
AllocatePublicIP: boolp(true),
}},
}
func (s *ConstraintsSuite) TestRoundtripGnuflagValue(c *gc.C) {
for _, t := range constraintsRoundtripTests {
c.Logf("test %s", t.Name)
var cons constraints.Value
val := constraints.ConstraintsValue{&cons}
err := val.Set(t.Value.String())
c.Check(err, jc.ErrorIsNil)
c.Check(cons, jc.DeepEquals, t.Value)
}
}
func (s *ConstraintsSuite) TestRoundtripString(c *gc.C) {
for _, t := range constraintsRoundtripTests {
c.Logf("test %s", t.Name)
cons, err := constraints.Parse(t.Value.String())
c.Check(err, jc.ErrorIsNil)
c.Check(cons, jc.DeepEquals, t.Value)
}
}
func (s *ConstraintsSuite) TestRoundtripJson(c *gc.C) {
for _, t := range constraintsRoundtripTests {
c.Logf("test %s", t.Name)
data, err := json.Marshal(t.Value)
c.Assert(err, jc.ErrorIsNil)
var cons constraints.Value
err = json.Unmarshal(data, &cons)
c.Check(err, jc.ErrorIsNil)
c.Check(cons, jc.DeepEquals, t.Value)
}
}
func (s *ConstraintsSuite) TestRoundtripYaml(c *gc.C) {
for _, t := range constraintsRoundtripTests {
c.Logf("test %s", t.Name)
data, err := goyaml.Marshal(t.Value)
c.Assert(err, jc.ErrorIsNil)
var cons constraints.Value
err = goyaml.Unmarshal(data, &cons)
c.Check(err, jc.ErrorIsNil)
c.Check(cons, jc.DeepEquals, t.Value)
}
}
var hasContainerTests = []struct {
constraints string
hasContainer bool
}{
{
hasContainer: false,
}, {
constraints: "container=lxd",
hasContainer: true,
}, {
constraints: "container=none",
hasContainer: false,
},
}
func (s *ConstraintsSuite) TestHasContainer(c *gc.C) {
for i, t := range hasContainerTests {
c.Logf("test %d", i)
cons := constraints.MustParse(t.constraints)
c.Check(cons.HasContainer(), gc.Equals, t.hasContainer)
}
}
func (s *ConstraintsSuite) TestHasInstanceType(c *gc.C) {
cons := constraints.MustParse("arch=amd64")
c.Check(cons.HasInstanceType(), jc.IsFalse)
cons = constraints.MustParse("arch=amd64 instance-type=foo")
c.Check(cons.HasInstanceType(), jc.IsTrue)
}
const initialWithoutCons = "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4 spaces=space1,^space2 tags=foo " +
"container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true"
var withoutTests = []struct {
initial string
without []string
final string
}{{
initial: initialWithoutCons,
without: []string{"root-disk"},
final: "mem=4G arch=amd64 cpu-power=1000 cores=4 tags=foo spaces=space1,^space2 container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"mem"},
final: "root-disk=8G arch=amd64 cpu-power=1000 cores=4 tags=foo spaces=space1,^space2 container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"arch"},
final: "root-disk=8G mem=4G cpu-power=1000 cores=4 tags=foo spaces=space1,^space2 container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"cpu-power"},
final: "root-disk=8G mem=4G arch=amd64 cores=4 tags=foo spaces=space1,^space2 container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"cores"},
final: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 tags=foo spaces=space1,^space2 container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"tags"},
final: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4 spaces=space1,^space2 container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"spaces"},
final: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4 tags=foo container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"container"},
final: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4 tags=foo spaces=space1,^space2 instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"instance-type"},
final: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4 tags=foo spaces=space1,^space2 container=lxd zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"root-disk", "mem", "arch"},
final: "cpu-power=1000 cores=4 tags=foo spaces=space1,^space2 container=lxd instance-type=bar zones=az1,az2 allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"zones"},
final: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4 spaces=space1,^space2 tags=foo container=lxd instance-type=bar allocate-public-ip=true",
}, {
initial: initialWithoutCons,
without: []string{"allocate-public-ip"},
final: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4 spaces=space1,^space2 tags=foo container=lxd instance-type=bar zones=az1,az2",
}}
func (s *ConstraintsSuite) TestWithout(c *gc.C) {
for i, t := range withoutTests {
c.Logf("test %d", i)
initial := constraints.MustParse(t.initial)
final := constraints.Without(initial, t.without...)
c.Check(final, jc.DeepEquals, constraints.MustParse(t.final))
}
}
var hasAnyTests = []struct {
cons string
attrs []string
expected []string
}{
{
cons: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 spaces=space1,^space2 cores=4",
attrs: []string{"root-disk", "tags", "mem", "spaces"},
expected: []string{"root-disk", "mem", "spaces"},
},
{
cons: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4",
attrs: []string{"root-disk", "tags", "mem"},
expected: []string{"root-disk", "mem"},
},
{
cons: "root-disk=8G mem=4G arch=amd64 cpu-power=1000 cores=4",
attrs: []string{"tags", "spaces"},
expected: []string{},
},
}
func (s *ConstraintsSuite) TestHasAny(c *gc.C) {
for i, t := range hasAnyTests {
c.Logf("test %d", i)
cons := constraints.MustParse(t.cons)
obtained := constraints.HasAny(cons, t.attrs...)
c.Check(obtained, jc.DeepEquals, t.expected)
}
}
| agpl-3.0 |
FourthRome/fourtherescue | Workbench/up03/1/1/test.c | 464 | #include <stdio.h>
#include <stdlib.h>
enum { PARAMNUM = 4 };
int
main(int argc, char *argv[])
{
if (argc < PARAMNUM) {
return 1;
}
double sum = strtod(argv[1], NULL);
double dep = strtod(argv[2], NULL) / 100 + 1;
double cred = strtod(argv[3], NULL) / 100 + 1;
for (int i = PARAMNUM; i < argc; i++) {
sum += strtod(argv[i], NULL);
sum *= (sum > 0) ? dep : cred;
}
printf("%.10g\n", sum);
return 0;
} | agpl-3.0 |
ingmarschuster/MindResearchRepository | ojs-2.3.8/lib/pkp/classes/file/wrappers/HTTPFileWrapper.inc.php | 4336 | <?php
/**
* @file classes/file/wrappers/HTTPFileWrapper.inc.php
*
* Copyright (c) 2000-2012 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @package file.wrappers
* @ingroup file_wrappers
*
* Class providing a wrapper for the HTTP protocol.
* (for when allow_url_fopen is disabled).
*
* $Id$
*/
class HTTPFileWrapper extends FileWrapper {
var $headers;
var $defaultPort;
var $defaultHost;
var $defaultPath;
var $redirects;
var $proxyHost;
var $proxyPort;
var $proxyUsername;
var $proxyPassword;
function HTTPFileWrapper($url, &$info, $redirects = 5) {
parent::FileWrapper($url, $info);
$this->setDefaultPort(80);
$this->setDefaultHost('localhost');
$this->setDefaultPath('/');
$this->redirects = 5;
$this->proxyHost = Config::getVar('proxy', 'http_host');
$this->proxyPort = Config::getVar('proxy', 'http_port');
$this->proxyUsername = Config::getVar('proxy', 'proxy_username');
$this->proxyPassword = Config::getVar('proxy', 'proxy_password');
}
function setDefaultPort($port) {
$this->defaultPort = $port;
}
function setDefaultHost($host) {
$this->defaultHost = $host;
}
function setDefaultPath($path) {
$this->defaultPath = $path;
}
function addHeader($name, $value) {
if (!isset($this->headers)) {
$this->headers = array();
}
$this->headers[$name] = $value;
}
function open($mode = 'r') {
$realHost = $host = isset($this->info['host']) ? $this->info['host'] : $this->defaultHost;
$port = isset($this->info['port']) ? (int)$this->info['port'] : $this->defaultPort;
$path = isset($this->info['path']) ? $this->info['path'] : $this->defaultPath;
if (isset($this->info['query'])) $path .= '?' . $this->info['query'];
if (!empty($this->proxyHost)) {
$realHost = $host;
$host = $this->proxyHost;
$port = $this->proxyPort;
if (!empty($this->proxyUsername)) {
$this->headers['Proxy-Authorization'] = 'Basic ' . base64_encode($this->proxyUsername . ':' . $this->proxyPassword);
}
}
if (!($this->fp = fsockopen($host, $port, $errno, $errstr)))
return false;
$additionalHeadersString = '';
if (is_array($this->headers)) foreach ($this->headers as $name => $value) {
$additionalHeadersString .= "$name: $value\r\n";
}
$requestHost = preg_replace("!^.*://!", "", $realHost);
$request = 'GET ' . (empty($this->proxyHost)?$path:$this->url) . " HTTP/1.0\r\n" .
"Host: $requestHost\r\n" .
$additionalHeadersString .
"Connection: Close\r\n\r\n";
fwrite($this->fp, $request);
$response = fgets($this->fp, 4096);
$rc = 0;
sscanf($response, "HTTP/%*s %u %*[^\r\n]\r\n", $rc);
if ($rc == 200) {
while(fgets($this->fp, 4096) !== "\r\n");
return true;
}
if(preg_match('!^3\d\d$!', $rc) && $this->redirects >= 1) {
for($response = '', $time = time(); !feof($this->fp) && $time >= time() - 15; ) $response .= fgets($this->fp, 128);
if (preg_match('!^(?:(?:Location)|(?:URI)|(?:location)): ([^\s]+)[\r\n]!m', $response, $matches)) {
$this->close();
$location = $matches[1];
if (preg_match('!^[a-z]+://!', $location)) {
$this->url = $location;
} else {
$newPath = ($this->info['path'] !== '' && strpos($location, '/') !== 0 ? dirname($this->info['path']) . '/' : (strpos($location, '/') === 0 ? '' : '/')) . $location;
$this->info['path'] = $newPath;
$this->url = $this->glue_url($this->info);
}
$returner =& FileWrapper::wrapper($this->url);
$returner->redirects = $this->redirects - 1;
return $returner;
}
}
$this->close();
return false;
}
function glue_url ($parsed) {
// Thanks to php dot net at NOSPAM dot juamei dot com
// See http://www.php.net/manual/en/function.parse-url.php
if (! is_array($parsed)) return false;
$uri = isset($parsed['scheme']) ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
$uri .= isset($parsed['user']) ? $parsed['user'].($parsed['pass']? ':'.$parsed['pass']:'').'@':'';
$uri .= isset($parsed['host']) ? $parsed['host'] : '';
$uri .= isset($parsed['port']) ? ':'.$parsed['port'] : '';
$uri .= isset($parsed['path']) ? $parsed['path'] : '';
$uri .= isset($parsed['query']) ? '?'.$parsed['query'] : '';
$uri .= isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
return $uri;
}
}
?>
| agpl-3.0 |
opendatateam/udata | specs/plugins/markdown.specs.js | 6254 | describe('Markdown plugin', function() {
const Vue = require('vue');
Vue.use(require('plugins/markdown'));
Vue.config.async = false;
afterEach(function() {
fixture.cleanup();
});
/**
* Remove invisible nodes generated by Vue.js
*/
function strip(el) {
[...el.childNodes].forEach(function(node) {
const is_comment = node.nodeType === Node.COMMENT_NODE;
const is_empty_text = node.nodeType === Node.TEXT_NODE && !/\S/.test(node.nodeValue);
if (is_comment || is_empty_text) {
node.parentNode.removeChild(node);
}
});
return el;
}
describe('markdown filter', function() {
function el(text) {
const vm = new Vue({
el: fixture.set('<div>{{{text | markdown}}}</div>')[0],
replace: false,
data: {
text: text
}
});
return strip(vm.$el);
}
it('should render empty string as ""', function() {
expect(el('').childNodes).to.be.emtpy;
});
it('should render null value as ""', function() {
expect(el(null).childNodes).to.be.empty;
});
it('should render undefined value as ""', function() {
expect(el(undefined).childNodes).to.be.empty;
});
it('should markdown content', function() {
expect(el('**aaa**')).to.have.html('<p><strong>aaa</strong></p>');
});
});
describe('markdown directive', function() {
function el(text) {
const vm = new Vue({
el: fixture.set('<div v-markdown="text"></div>')[0],
data: {
'text': text
}
});
return strip(vm.$el);
}
it('should render empty string as ""', function() {
expect(el('').childNodes).to.be.emtpy;
});
it('should render null value as ""', function() {
expect(el(null).childNodes).to.be.empty;
});
it('should render undefined value as ""', function() {
expect(el(undefined).childNodes).to.be.empty;
});
it('should markdown content', function() {
expect(el('**aaa**')).to.have.html('<p><strong>aaa</strong></p>');
});
});
});
describe('Markdown backend compliance', function() {
const markdown = require('helpers/markdown').default;
/**
* An expect wrapper rendering the markdown
* and then allowing to perform chai-dom expectation on it
*/
function md(source) {
const div = document.createElement('div');
div.innerHTML = markdown(source);
return div;
}
it('should transform urls to anchors', function() {
const source = 'http://example.net/';
expect(md(source)).to.have.html('<p><a href="http://example.net/">http://example.net/</a></p>');
});
it('should handles autolink', function() {
const source = '<http://example.net/>';
expect(md(source)).to.have.html('<p><a href="http://example.net/">http://example.net/</a></p>');
});
it('should not transform emails to anchors', function() {
const source = '[email protected]';
expect(md(source)).to.have.html('<p>[email protected]</p>');
});
it('should not transform links within pre', function() {
const source = '<pre>http://example.net/</pre>';
expect(md(source)).to.have.html('<pre>http://example.net/</pre>');
});
it('should sanitize evil code', function() {
const source = 'an <script>evil()</script>';
expect(md(source)).to.have.html('<p>an <script>evil()</script></p>');
});
it('should handle soft breaks as <br/>', function() {
const source = 'line 1\nline 2';
expect(md(source)).to.have.html('<p>line 1<br>\nline 2</p>');
});
it('should properly render markdown tags not in allowed tags', function() {
const source = '### titre';
expect(md(source)).to.have.html('<h3>titre</h3>');
});
it('should render GFM tables (extension)', function() {
const source = [
'| first | second |',
'|-------|--------|',
'| value | value |',
].join('\n');
const expected = [
'<table>',
'<thead>',
'<tr>',
'<th>first</th>',
'<th>second</th>',
'</tr>',
'</thead>',
'<tbody>',
'<tr>',
'<td>value</td>',
'<td>value</td>',
'</tr>',
'</tbody>',
'</table>'
].join('\n');
expect(md(source)).to.have.html(expected);
});
it('should render GFM strikethrough (extension)', function() {
const source = 'Yay ~~Hi~~ Hello, world!';
const expected = '<p>Yay <del>Hi</del> Hello, world!</p>';
expect(md(source)).to.have.html(expected);
});
it('should handle GFM tagfilter extension', function() {
// Test extracted from https://github.github.com/gfm/#disallowed-raw-html-extension-
const source = [
'<strong> <title>My Title</title></strong>',
'<blockquote>',
' <xmp> is disallowed.</xmp> <XMP> is also disallowed.</XMP>',
'</blockquote>',
].join('\n')
const expected = [
'<p><strong> <title>My Title</title></strong></p>',
'<blockquote>',
' <xmp> is disallowed.</xmp> <XMP> is also disallowed.</XMP>',
'</blockquote>',
].join('\n')
expect(md(source)).to.have.html(expected)
});
it('should not filter legit markup', function() {
const source = [
'> This is a blockquote',
'> with <script>evil()</script> inside',
].join('\n');
const expected = [
'<blockquote>',
'<p>This is a blockquote<br>',
'with <script>evil()</script> inside</p>',
'</blockquote>',
].join('\n');
expect(md(source)).to.have.html(expected);
});
});
| agpl-3.0 |
freyes/juju | cmd/juju/machine/show_test.go | 7282 | // Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for info.
package machine_test
import (
"github.com/juju/cmd"
"github.com/juju/cmd/cmdtesting"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/juju/cmd/juju/machine"
"github.com/juju/juju/testing"
)
type MachineShowCommandSuite struct {
testing.FakeJujuXDGDataHomeSuite
}
var _ = gc.Suite(&MachineShowCommandSuite{})
func newMachineShowCommand() cmd.Command {
return machine.NewShowCommandForTest(&fakeStatusAPI{})
}
func (s *MachineShowCommandSuite) SetUpTest(c *gc.C) {
s.FakeJujuXDGDataHomeSuite.SetUpTest(c)
}
func (s *MachineShowCommandSuite) TestShowMachine(c *gc.C) {
context, err := cmdtesting.RunCommand(c, newMachineShowCommand())
c.Assert(err, jc.ErrorIsNil)
// TODO(macgreagoir) Spaces in dummyenv?
c.Assert(cmdtesting.Stdout(context), gc.Equals, ""+
"model: dummyenv\n"+
"machines:\n"+
" \"0\":\n"+
" juju-status:\n"+
" current: started\n"+
" dns-name: 10.0.0.1\n"+
" ip-addresses:\n"+
" - 10.0.0.1\n"+
" - 10.0.1.1\n"+
" instance-id: juju-badd06-0\n"+
" series: trusty\n"+
" network-interfaces:\n"+
" eth0:\n"+
" ip-addresses:\n"+
" - 10.0.0.1\n"+
" - 10.0.1.1\n"+
" mac-address: aa:bb:cc:dd:ee:ff\n"+
" is-up: true\n"+
" constraints: mem=3584M\n"+
" hardware: availability-zone=us-east-1\n"+
" \"1\":\n"+
" juju-status:\n"+
" current: started\n"+
" dns-name: 10.0.0.2\n"+
" ip-addresses:\n"+
" - 10.0.0.2\n"+
" - 10.0.1.2\n"+
" instance-id: juju-badd06-1\n"+
" series: trusty\n"+
" network-interfaces:\n"+
" eth0:\n"+
" ip-addresses:\n"+
" - 10.0.0.2\n"+
" - 10.0.1.2\n"+
" mac-address: aa:bb:cc:dd:ee:ff\n"+
" is-up: true\n"+
" containers:\n"+
" 1/lxd/0:\n"+
" juju-status:\n"+
" current: pending\n"+
" dns-name: 10.0.0.3\n"+
" ip-addresses:\n"+
" - 10.0.0.3\n"+
" - 10.0.1.3\n"+
" instance-id: juju-badd06-1-lxd-0\n"+
" series: trusty\n"+
" network-interfaces:\n"+
" eth0:\n"+
" ip-addresses:\n"+
" - 10.0.0.3\n"+
" - 10.0.1.3\n"+
" mac-address: aa:bb:cc:dd:ee:ff\n"+
" is-up: true\n"+
" lxd-profiles:\n"+
" lxd-profile-name:\n"+
" config:\n"+
" environment.http_proxy: \"\"\n"+
" description: lxd-profile description\n"+
" devices:\n"+
" tun:\n"+
" path: /dev/net/tun\n"+
" type: unix-char\n",
)
}
func (s *MachineShowCommandSuite) TestShowSingleMachine(c *gc.C) {
context, err := cmdtesting.RunCommand(c, newMachineShowCommand(), "0")
c.Assert(err, jc.ErrorIsNil)
// TODO(macgreagoir) Spaces in dummyenv?
c.Assert(cmdtesting.Stdout(context), gc.Equals, ""+
"model: dummyenv\n"+
"machines:\n"+
" \"0\":\n"+
" juju-status:\n"+
" current: started\n"+
" dns-name: 10.0.0.1\n"+
" ip-addresses:\n"+
" - 10.0.0.1\n"+
" - 10.0.1.1\n"+
" instance-id: juju-badd06-0\n"+
" series: trusty\n"+
" network-interfaces:\n"+
" eth0:\n"+
" ip-addresses:\n"+
" - 10.0.0.1\n"+
" - 10.0.1.1\n"+
" mac-address: aa:bb:cc:dd:ee:ff\n"+
" is-up: true\n"+
" constraints: mem=3584M\n"+
" hardware: availability-zone=us-east-1\n")
}
func (s *MachineShowCommandSuite) TestShowTabularMachine(c *gc.C) {
context, err := cmdtesting.RunCommand(c, newMachineShowCommand(), "--format", "tabular", "0", "1")
c.Assert(err, jc.ErrorIsNil)
c.Assert(cmdtesting.Stdout(context), gc.Equals, ""+
"Machine State DNS Inst id Series AZ Message\n"+
"0 started 10.0.0.1 juju-badd06-0 trusty us-east-1 \n"+
"1 started 10.0.0.2 juju-badd06-1 trusty \n"+
"1/lxd/0 pending 10.0.0.3 juju-badd06-1-lxd-0 trusty \n"+
"\n")
}
func (s *MachineShowCommandSuite) TestShowJsonMachine(c *gc.C) {
context, err := cmdtesting.RunCommand(c, newMachineShowCommand(), "--format", "json", "0", "1")
c.Assert(err, jc.ErrorIsNil)
// TODO(macgreagoir) Spaces in dummyenv?
// Make the test more readable by putting all the JSON in a expanded form.
// Then to test it, marshal it back into json, so that map equality ordering
// doesn't matter.
expectedJSON, err := unmarshalStringAsJSON("" +
"{" +
" \"model\":\"dummyenv\"," +
" \"machines\":{" +
" \"0\":{" +
" \"juju-status\":{" +
" \"current\":\"started\"" +
" }," +
" \"dns-name\":\"10.0.0.1\"," +
" \"ip-addresses\":[" +
" \"10.0.0.1\"," +
" \"10.0.1.1\"" +
" ]," +
" \"instance-id\":\"juju-badd06-0\"," +
" \"machine-status\":{}," +
" \"modification-status\":{}," +
" \"series\":\"trusty\"," +
" \"network-interfaces\":{" +
" \"eth0\":{" +
" \"ip-addresses\":[" +
" \"10.0.0.1\"," +
" \"10.0.1.1\"" +
" ]," +
" \"mac-address\":\"aa:bb:cc:dd:ee:ff\"," +
" \"is-up\":true" +
" }" +
" }," +
" \"constraints\":\"mem=3584M\"," +
" \"hardware\":\"availability-zone=us-east-1\"" +
" }," +
" \"1\":{" +
" \"juju-status\":{" +
" \"current\":\"started\"" +
" }," +
" \"dns-name\":\"10.0.0.2\"," +
" \"ip-addresses\":[" +
" \"10.0.0.2\"," +
" \"10.0.1.2\"" +
" ]," +
" \"instance-id\":\"juju-badd06-1\"," +
" \"machine-status\":{}," +
" \"modification-status\":{}," +
" \"series\":\"trusty\"," +
" \"network-interfaces\":{" +
" \"eth0\":{" +
" \"ip-addresses\":[" +
" \"10.0.0.2\"," +
" \"10.0.1.2\"" +
" ]," +
" \"mac-address\":\"aa:bb:cc:dd:ee:ff\"," +
" \"is-up\":true" +
" }" +
" }," +
" \"containers\":{" +
" \"1/lxd/0\":{" +
" \"juju-status\":{" +
" \"current\":\"pending\"" +
" }," +
" \"dns-name\":\"10.0.0.3\"," +
" \"ip-addresses\":[" +
" \"10.0.0.3\"," +
" \"10.0.1.3\"" +
" ]," +
" \"instance-id\":\"juju-badd06-1-lxd-0\"," +
" \"machine-status\":{}," +
" \"modification-status\":{}," +
" \"series\":\"trusty\"," +
" \"network-interfaces\":{" +
" \"eth0\":{" +
" \"ip-addresses\":[" +
" \"10.0.0.3\"," +
" \"10.0.1.3\"" +
" ]," +
" \"mac-address\":\"aa:bb:cc:dd:ee:ff\"," +
" \"is-up\":true" +
" }" +
" }" +
" }" +
" }," +
" \"lxd-profiles\":{" +
" \"lxd-profile-name\":{" +
" \"config\":{" +
" \"environment.http_proxy\":\"\"" +
" }," +
" \"description\":\"lxd-profile description\"," +
" \"devices\":{" +
" \"tun\":{" +
" \"path\":\"/dev/net/tun\"," +
" \"type\":\"unix-char\"" +
" }" +
" }" +
" }" +
" }" +
" }" +
" }" +
" }\n")
c.Assert(err, jc.ErrorIsNil)
actualJSON, err := unmarshalStringAsJSON(cmdtesting.Stdout(context))
c.Assert(err, jc.ErrorIsNil)
c.Assert(actualJSON, gc.DeepEquals, expectedJSON)
}
| agpl-3.0 |
codeforeurope/samenspel | lib/grab_name.rb | 167 | # -*- encoding : utf-8 -*-
module GrabName
protected
def self.grab_name(id)
e = self.find(id,:select => 'name')
e = e.nil? ? '' : e.name
end
end
| agpl-3.0 |
hyc/BerkeleyDB | test/xa/utilities/bdb_xa_util.h | 1624 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
*/
#include <pthread.h>
#include <db.h>
/* Maximum number of db handles that init/close_xa_server will handle. */
#define MAX_NUMDB 4
/* Names for the databases. */
static char *db_names[] = {"table1.db", "table2.db", "table3.db", "table4.db"};
/* Debugging output. */
#ifdef VERBOSE
static int verbose = 1;
#else
static int verbose = 0;
#endif
/* Table handles. */
DB *dbs[MAX_NUMDB];
/*
* This function syncs all threads threads by putting them to
* sleep until the last thread enters and sync function and
* forces the rest to wake up.
* counter - A counter starting at 0 shared by all threads
* num_threads - the number of threads being synced.
*/
int sync_thr(int *counter, int num_threads, pthread_cond_t *cond_var);
/*
* Print callback for __db_prdbt.
*/
int pr_callback(void *handle, const void *str_arg);
/*
* Initialize an XA server and allocates and opens database handles.
* The number of database handles it opens is the value of the argument
* num_db.
*/
int init_xa_server(int num_db, const char *progname, int use_mvcc);
/*
* Called when the servers are shutdown. This closes all open
* database handles. num_db is the number of open database handles.
*/
void close_xa_server(int num_db, const char *progname);
/*
* check_data --
* Compare data between two databases to ensure that they are identical.
*/
int check_data(DB_ENV *dbenv1, const char *name1, DB_ENV *dbenv2,
const char *name2, const char *progname);
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/forms/nokdetails/BaseAccessLogic.java | 4011 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.nokdetails;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
if(!form.getGlobalContext().Core.getParentFormModeIsNotNull())
return false;
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
}
}
}
| agpl-3.0 |
tallysmartins/noosfero | lib/noosfero/api/session.rb | 5667 | require "uri"
module Noosfero
module API
class Session < Grape::API
# Login to get token
#
# Parameters:
# login (*required) - user login or email
# password (required) - user password
#
# Example Request:
# POST http://localhost:3000/api/v1/login?login=adminuser&password=admin
post "/login" do
begin
user ||= User.authenticate(params[:login], params[:password], environment)
rescue NoosferoExceptions::UserNotActivated => e
render_api_error!(e.message, 401)
end
return unauthorized! unless user
@current_user = user
present user, :with => Entities::UserLogin, :current_person => current_person
end
post "/login_from_cookie" do
return unauthorized! if cookies[:auth_token].blank?
user = User.where(remember_token: cookies[:auth_token]).first
return unauthorized! unless user && user.activated?
@current_user = user
present user, :with => Entities::UserLogin, :current_person => current_person
end
# Create user.
#
# Parameters:
# email (required) - Email
# password (required) - Password
# login - login
# Example Request:
# POST /[email protected]&password=pas&password_confirmation=pas&login=some
params do
requires :email, type: String, desc: _("Email")
requires :login, type: String, desc: _("Login")
requires :password, type: String, desc: _("Password")
end
post "/register" do
attrs = attributes_for_keys [:email, :login, :password, :password_confirmation] + environment.signup_person_fields
name = params[:name].present? ? params[:name] : attrs[:email]
attrs[:password_confirmation] = attrs[:password] if !attrs.has_key?(:password_confirmation)
user = User.new(attrs.merge(:name => name))
begin
user.signup!
user.generate_private_token! if user.activated?
present user, :with => Entities::UserLogin, :current_person => user.person
rescue ActiveRecord::RecordInvalid
message = user.errors.as_json.merge((user.person.present? ? user.person.errors : {}).as_json).to_json
render_api_error!(message, 400)
end
end
params do
requires :activation_code, type: String, desc: _("Activation token")
end
# Activate a user.
#
# Parameter:
# activation_code (required) - Activation token
# Example Request:
# PATCH /activate?activation_code=28259abd12cc6a64ef9399cf3286cb998b96aeaf
patch "/activate" do
user = User.find_by activation_code: params[:activation_code]
if user
unless user.environment.enabled?('admin_must_approve_new_users')
if user.activate
user.generate_private_token!
present user, :with => Entities::UserLogin, :current_person => current_person
end
else
if user.create_moderate_task
user.activation_code = nil
user.save!
# Waiting for admin moderate user registration
status 202
body({
:message => 'Waiting for admin moderate user registration'
})
end
end
else
# Token not found in database
render_api_error!(_('Token is invalid'), 412)
end
end
# Request a new password.
#
# Parameters:
# value (required) - Email or login
# Example Request:
# POST /[email protected]
post "/forgot_password" do
requestors = fetch_requestors(params[:value])
not_found! if requestors.blank?
remote_ip = (request.respond_to?(:remote_ip) && request.remote_ip) || (env && env['REMOTE_ADDR'])
requestors.each do |requestor|
ChangePassword.create!(:requestor => requestor)
end
end
# Resend activation code.
#
# Parameters:
# value (required) - Email or login
# Example Request:
# POST /[email protected]
post "/resend_activation_code" do
requestors = fetch_requestors(params[:value])
not_found! if requestors.blank?
remote_ip = (request.respond_to?(:remote_ip) && request.remote_ip) || (env && env['REMOTE_ADDR'])
requestors.each do |requestor|
requestor.user.resend_activation_code
end
present requestors.map(&:user), :with => Entities::UserLogin
end
params do
requires :code, type: String, desc: _("Forgot password code")
end
# Change password
#
# Parameters:
# code (required) - Change password code
# password (required)
# password_confirmation (required)
# Example Request:
# PATCH /new_password?code=xxxx&password=secret&password_confirmation=secret
patch "/new_password" do
change_password = ChangePassword.find_by code: params[:code]
not_found! if change_password.nil?
if change_password.update_attributes(:password => params[:password], :password_confirmation => params[:password_confirmation])
change_password.finish
present change_password.requestor.user, :with => Entities::UserLogin, :current_person => current_person
else
something_wrong!
end
end
end
end
end
| agpl-3.0 |
hybrasyl/server | hybrasyl/Plugins/Message.cs | 697 | using System;
using System.Collections.Generic;
using System.Text;
namespace Hybrasyl.Plugins
{
// TODO: interface
public class Message
{
public string Sender = string.Empty;
public string Recipient = string.Empty;
public Xml.MessageType Type { get; set; }
public string Text = string.Empty;
public string Subject = string.Empty;
public Message(Xml.MessageType type, string sender, string recipient, string subject, string body)
{
Type = type;
Sender = sender;
Recipient = recipient;
Text = body;
Subject = subject;
}
public Message() { }
}
}
| agpl-3.0 |
eHealthAfrica/ureport | ureport/contacts/tests.py | 15406 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.utils import timezone
from mock import patch
import pytz
from ureport.contacts.models import ContactField, Contact, ReportersCounter
from ureport.contacts.tasks import fetch_contacts_task
from ureport.locations.models import Boundary
from ureport.tests import DashTest, TembaContactField, MockTembaClient, TembaContact
from temba_client.v1.types import Group as TembaGroup
from ureport.utils import json_date_to_datetime
class ContactFieldTest(DashTest):
def setUp(self):
super(ContactFieldTest, self).setUp()
self.nigeria = self.create_org('nigeria', self.admin)
def test_kwargs_from_temba(self):
temba_contact_field = TembaContactField.create(key='foo', label='Bar', value_type='T')
kwargs = ContactField.kwargs_from_temba(self.nigeria, temba_contact_field)
self.assertEqual(kwargs, dict(org=self.nigeria, key='foo', label='Bar', value_type='T'))
# try creating contact from them
ContactField.objects.create(**kwargs)
@patch('dash.orgs.models.TembaClient1', MockTembaClient)
def test_fetch_contact_fields(self):
ContactField.objects.create(org=self.nigeria, key='old', label='Old', value_type='T')
field_keys = ContactField.fetch_contact_fields(self.nigeria)
self.assertEqual(field_keys, ['occupation'])
self.assertIsNone(ContactField.objects.filter(key='old', org=self.nigeria).first())
contact_field = ContactField.objects.get()
self.assertEqual(contact_field.org, self.nigeria)
self.assertEqual(contact_field.key, 'occupation')
self.assertEqual(contact_field.label, 'Activité')
self.assertEqual(contact_field.value_type, 'T')
@patch('dash.orgs.models.TembaClient1', MockTembaClient)
def test_get_contact_fields(self):
field_keys = ContactField.get_contact_fields(self.nigeria)
self.assertEqual(field_keys, ['occupation'])
with patch('django.core.cache.cache.get') as cache_get_mock:
cache_get_mock.return_value = None
field_keys = ContactField.get_contact_fields(self.nigeria)
self.assertEqual(field_keys, ['occupation'])
cache_get_mock.return_value = ['occupation']
with patch('ureport.contacts.models.ContactField.fetch_contact_fields') as mock_fetch:
ContactField.get_contact_fields(self.nigeria)
self.assertFalse(mock_fetch.called)
class ContactTest(DashTest):
def setUp(self):
super(ContactTest, self).setUp()
self.nigeria = self.create_org('nigeria', self.admin)
self.nigeria.set_config('reporter_group', "Ureporters")
self.nigeria.set_config('registration_label', "Registration Date")
self.nigeria.set_config('state_label', "State")
self.nigeria.set_config('district_label', "LGA")
self.nigeria.set_config('occupation_label', "Activité")
self.nigeria.set_config('born_label', "Born")
self.nigeria.set_config('gender_label', 'Gender')
self.nigeria.set_config('female_label', "Female")
self.nigeria.set_config('male_label', 'Male')
# boundaries fetched
self.country = Boundary.objects.create(org=self.nigeria, osm_id="R-NIGERIA", name="Nigeria", level=0, parent=None,
geometry='{"foo":"bar-country"}')
self.state = Boundary.objects.create(org=self.nigeria, osm_id="R-LAGOS", name="Lagos", level=1,
parent=self.country, geometry='{"foo":"bar-state"}')
self.district = Boundary.objects.create(org=self.nigeria, osm_id="R-OYO", name="Oyo", level=2,
parent=self.state, geometry='{"foo":"bar-state"}')
self.registration_date = ContactField.objects.create(org=self.nigeria, key='registration_date',
label='Registration Date', value_type='T')
self.state_field = ContactField.objects.create(org=self.nigeria, key='state', label='State', value_type='S')
self.district_field = ContactField.objects.create(org=self.nigeria, key='lga', label='LGA', value_type='D')
self.occupation_field = ContactField.objects.create(org=self.nigeria, key='occupation', label='Activité',
value_type='T')
self.born_field = ContactField.objects.create(org=self.nigeria, key='born', label='Born', value_type='T')
self.gender_field = ContactField.objects.create(org=self.nigeria, key='gender', label='Gender', value_type='T')
def test_kwargs_from_temba(self):
temba_contact = TembaContact.create(uuid='C-006', name="Jan", urns=['tel:123'],
groups=['G-001', 'G-007'],
fields={'registration_date': None, 'state': None,
'lga': None, 'occupation': None, 'born': None,
'gender': None},
language='eng')
kwargs = Contact.kwargs_from_temba(self.nigeria, temba_contact)
self.assertEqual(kwargs, dict(uuid='C-006', org=self.nigeria, gender='', born=0, occupation='',
registered_on=None, state='', district=''))
# try creating contact from them
Contact.objects.create(**kwargs)
# Invalid boundaries become ''
temba_contact = TembaContact.create(uuid='C-007', name="Jan", urns=['tel:123'],
groups=['G-001', 'G-007'],
fields={'registration_date': '2014-01-02T03:04:05.000000Z',
'state': 'Kigali', 'lga': 'Oyo', 'occupation': 'Student',
'born': '1990', 'gender': 'Male'},
language='eng')
kwargs = Contact.kwargs_from_temba(self.nigeria, temba_contact)
self.assertEqual(kwargs, dict(uuid='C-007', org=self.nigeria, gender='M', born=1990, occupation='Student',
registered_on=json_date_to_datetime('2014-01-02T03:04:05.000'), state='',
district=''))
# try creating contact from them
Contact.objects.create(**kwargs)
temba_contact = TembaContact.create(uuid='C-008', name="Jan", urns=['tel:123'],
groups=['G-001', 'G-007'],
fields={'registration_date': '2014-01-02T03:04:05.000000Z', 'state':'Lagos',
'lga': 'Oyo', 'occupation': 'Student', 'born': '1990',
'gender': 'Male'},
language='eng')
kwargs = Contact.kwargs_from_temba(self.nigeria, temba_contact)
self.assertEqual(kwargs, dict(uuid='C-008', org=self.nigeria, gender='M', born=1990, occupation='Student',
registered_on=json_date_to_datetime('2014-01-02T03:04:05.000'), state='R-LAGOS',
district='R-OYO'))
# try creating contact from them
Contact.objects.create(**kwargs)
def test_fetch_contacts(self):
self.nigeria.set_config('reporter_group', 'Reporters')
tz = pytz.timezone('UTC')
with patch.object(timezone, 'now', return_value=tz.localize(datetime(2015, 9, 29, 10, 20, 30, 40))):
with patch('dash.orgs.models.TembaClient1.get_groups') as mock_groups:
group = TembaGroup.create(uuid="uuid-8", name='reporters', size=120)
mock_groups.return_value = [group]
with patch('dash.orgs.models.TembaClient1.get_contacts') as mock_contacts:
mock_contacts.return_value = [
TembaContact.create(uuid='000-001', name="Ann", urns=['tel:1234'], groups=['000-002'],
fields=dict(state="Lagos", lga="Oyo", gender='Female', born="1990"),
language='eng',
modified_on=datetime(2015, 9, 20, 10, 20, 30, 400000, pytz.utc))]
seen_uuids = Contact.fetch_contacts(self.nigeria)
self.assertEqual(seen_uuids, [])
group = TembaGroup.create(uuid="000-002", name='reporters', size=120)
mock_groups.return_value = [group]
with patch('dash.orgs.models.TembaClient1.get_contacts') as mock_contacts:
mock_contacts.return_value = [
TembaContact.create(uuid='000-001', name="Ann",urns=['tel:1234'], groups=['000-002'],
fields=dict(state="Lagos", lga="Oyo",gender='Female', born="1990"),
language='eng',
modified_on=datetime(2015, 9, 20, 10, 20, 30, 400000, pytz.utc))]
seen_uuids = Contact.fetch_contacts(self.nigeria)
self.assertTrue('000-001' in seen_uuids)
contact = Contact.objects.get()
self.assertEqual(contact.uuid, '000-001')
self.assertEqual(contact.org, self.nigeria)
self.assertEqual(contact.state, 'R-LAGOS')
self.assertEqual(contact.district, 'R-OYO')
self.assertEqual(contact.gender, 'F')
self.assertEqual(contact.born, 1990)
Contact.fetch_contacts(self.nigeria, after=datetime(2014, 12, 01, 22, 34, 36, 123000, pytz.utc))
self.assertTrue('000-001' in seen_uuids)
# delete the contacts
Contact.objects.all().delete()
group1 = TembaGroup.create(uuid="000-001", name='reporters too', size=10)
group2 = TembaGroup.create(uuid="000-002", name='reporters', size=120)
mock_groups.return_value = [group1, group2]
with patch('dash.orgs.models.TembaClient1.get_contacts') as mock_contacts:
mock_contacts.return_value = [
TembaContact.create(uuid='000-001', name="Ann",urns=['tel:1234'], groups=['000-002'],
fields=dict(state="Lagos", lga="Oyo",gender='Female', born="1990"),
language='eng',
modified_on=datetime(2015, 9, 20, 10, 20, 30, 400000, pytz.utc))]
seen_uuids = Contact.fetch_contacts(self.nigeria)
self.assertTrue('000-001' in seen_uuids)
contact = Contact.objects.get()
self.assertEqual(contact.uuid, '000-001')
self.assertEqual(contact.org, self.nigeria)
self.assertEqual(contact.state, 'R-LAGOS')
self.assertEqual(contact.district, 'R-OYO')
self.assertEqual(contact.gender, 'F')
self.assertEqual(contact.born, 1990)
Contact.fetch_contacts(self.nigeria, after=datetime(2014, 12, 01, 22, 34, 36, 123000, pytz.utc))
self.assertTrue('000-001' in seen_uuids)
def test_reporters_counter(self):
self.assertEqual(ReportersCounter.get_counts(self.nigeria), dict())
Contact.objects.create(uuid='C-007', org=self.nigeria, gender='M', born=1990, occupation='Student',
registered_on=json_date_to_datetime('2014-01-02T03:04:05.000'), state='R-LAGOS',
district='R-OYO')
expected = dict()
expected['total-reporters'] = 1
expected['gender:m'] = 1
expected['occupation:student'] = 1
expected['born:1990'] = 1
expected['registered_on:2014-01-02'] = 1
expected['state:R-LAGOS'] = 1
expected['district:R-OYO'] = 1
self.assertEqual(ReportersCounter.get_counts(self.nigeria), expected)
Contact.objects.create(uuid='C-008', org=self.nigeria, gender='M', born=1980, occupation='Teacher',
registered_on=json_date_to_datetime('2014-01-02T03:07:05.000'), state='R-LAGOS',
district='R-OYO')
expected = dict()
expected['total-reporters'] = 2
expected['gender:m'] = 2
expected['occupation:student'] = 1
expected['occupation:teacher'] = 1
expected['born:1990'] = 1
expected['born:1980'] = 1
expected['registered_on:2014-01-02'] = 2
expected['state:R-LAGOS'] = 2
expected['district:R-OYO'] = 2
self.assertEqual(ReportersCounter.get_counts(self.nigeria), expected)
@patch('dash.orgs.models.TembaClient1', MockTembaClient)
def test_tasks(self):
with self.settings(CACHES={'default': {'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '127.0.0.1:6379:1',
'OPTIONS': {'CLIENT_CLASS': 'redis_cache.client.DefaultClient'}
}}):
with patch('ureport.contacts.tasks.Contact.fetch_contacts') as mock_fetch_contacts:
with patch('ureport.contacts.tasks.Boundary.fetch_boundaries') as mock_fetch_boundaries:
with patch('ureport.contacts.tasks.ContactField.fetch_contact_fields') as mock_fetch_contact_fields:
mock_fetch_contacts.return_value = 'FETCHED'
mock_fetch_boundaries.return_value = 'FETCHED'
mock_fetch_contact_fields.return_value = 'FETCHED'
fetch_contacts_task(self.nigeria.pk, True)
mock_fetch_contacts.assert_called_once_with(self.nigeria, after=None)
mock_fetch_boundaries.assert_called_with(self.nigeria)
mock_fetch_contact_fields.assert_called_with(self.nigeria)
self.assertEqual(mock_fetch_boundaries.call_count, 2)
self.assertEqual(mock_fetch_contact_fields.call_count, 2)
mock_fetch_contacts.reset_mock()
mock_fetch_boundaries.reset_mock()
mock_fetch_contact_fields.reset_mock()
with patch('django.core.cache.cache.get') as cache_get_mock:
date_str = '2014-01-02T01:04:05.000Z'
d1 = json_date_to_datetime(date_str)
cache_get_mock.return_value = date_str
fetch_contacts_task(self.nigeria.pk)
mock_fetch_contacts.assert_called_once_with(self.nigeria, after=d1)
self.assertFalse(mock_fetch_boundaries.called)
self.assertFalse(mock_fetch_contact_fields.called)
| agpl-3.0 |
herbert-venancio/taskboard | sizing-importer/src/test/java/objective/taskboard/sizingImport/cost/CostValidatorTest.java | 16733 | package objective.taskboard.sizingImport.cost;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static objective.taskboard.sizingImport.SizingImportConfig.SHEET_COST;
import static objective.taskboard.sizingImport.SizingImportConfig.SHEET_SCOPE;
import static objective.taskboard.sizingImport.cost.CostColumnMappingDefinitionProvider.EFFORT;
import static objective.taskboard.sizingImport.cost.CostColumnMappingDefinitionProvider.INDIRECT_COSTS;
import static objective.taskboard.sizingImport.cost.CostColumnMappingDefinitionProvider.INDIRECT_COSTS_KEY;
import static objective.taskboard.sizingImport.cost.CostColumnMappingDefinitionProvider.TOTAL_INDIRECT_COSTS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import objective.taskboard.google.SpreadsheetsManager;
import objective.taskboard.sizingImport.JiraFacade;
import objective.taskboard.sizingImport.SheetColumnDefinition;
import objective.taskboard.sizingImport.SizingImportConfig;
import objective.taskboard.sizingImport.SizingImportConfig.IndirectCosts;
import objective.taskboard.sizingImport.SizingImportValidator.ValidationContext;
import objective.taskboard.sizingImport.SizingImportValidator.ValidationContextWithSpreadsheet;
import objective.taskboard.sizingImport.SizingImportValidator.ValidationResult;
public class CostValidatorTest {
private static final String SPREADSHEET_ID = "100";
private static final Long PARENT_TYPE_ID = 1L;
private final SizingImportConfig config = new SizingImportConfig();
private final JiraFacade jiraFacade = mock(JiraFacade.class);
private final SpreadsheetsManager spreadsheetsManager = mock(SpreadsheetsManager.class);
private final CostColumnMappingDefinitionProvider costColumnProvider = mock(CostColumnMappingDefinitionProvider.class);
private final CostSheetSkipper costSheetSkipper = mock(CostSheetSkipper.class);
private final ValidationContext context = new ValidationContext(SPREADSHEET_ID, spreadsheetsManager);
private List<List<Object>> sheetCostData;
private ValidationContextWithSpreadsheet contextWithSpreadsheet;
private final CostValidator subject = new CostValidator(config, jiraFacade, costColumnProvider, costSheetSkipper);
@Before
public void setup() {
IndirectCosts indirectCosts = new IndirectCosts();
indirectCosts.setParentTypeId(PARENT_TYPE_ID);
config.setIndirectCosts(indirectCosts);
sheetCostData = asList(
asList("Indirect Costs", "Key", "Role Level", "Role", "Hour($)", "Weekly Hours", "% of Project", "Project Days", "Effort"),
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"),
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"));
when(spreadsheetsManager.readRange(SPREADSHEET_ID, format("'%s'", SHEET_COST))).thenAnswer((i) -> sheetCostData);
contextWithSpreadsheet = new ValidationContextWithSpreadsheet(context, asList(SHEET_SCOPE, "Timeline", SHEET_COST));
when(costColumnProvider.getHeaderMappings()).thenReturn(asList(
new ColumnMappingDefinition(INDIRECT_COSTS, "A"),
new ColumnMappingDefinition(INDIRECT_COSTS_KEY, "B"),
new ColumnMappingDefinition(EFFORT, "I")));
when(costColumnProvider.getFooterMappings()).thenReturn(asList(
new ColumnMappingDefinition(TOTAL_INDIRECT_COSTS, "A")));
when(costSheetSkipper.shouldSkip(SPREADSHEET_ID)).thenReturn(false);
}
@Test
public void shouldReturnSuccessWhenEverythingIsCorrect() {
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.success);
}
@Test
public void shouldFailWhenSpreadsheetsHasNoSheetEntitledAsCost() {
contextWithSpreadsheet = new ValidationContextWithSpreadsheet(context, asList(SHEET_SCOPE, "Timeline"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Specified URL should contain a sheet with title “Cost”.", result.errorMessage);
assertEquals("Found sheets: Scope, Timeline.", result.errorDetail);
}
@Test
public void shouldFailWhenIndirectCostsHasEmptyHeader() {
sheetCostData = asList(
asList(),
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"),
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertInvalidSheetCostFormat(result);
}
@Test
public void shouldFailWhenIndirectCostsHasNoHeader() {
sheetCostData = asList(
null,
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"),
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertInvalidSheetCostFormat(result);
}
@Test
public void shouldFailWhenThereAreNoRowsInCostSheet() {
sheetCostData = emptyList();
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertInvalidSheetCostFormat(result);
}
private void assertInvalidSheetCostFormat(ValidationResult result) {
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Missing required header columns in “Cost“ sheet.", result.errorMessage);
assertEquals("“Indirect Costs” column should be placed at position “A”, “Key” column should be placed at position “B”, "
+ "“Effort” column should be placed at position “I”. And all the columns should be placed at the same row.", result.errorDetail);
}
@Test
public void shouldFailWhenIndirectCostsHeaderColumnIsOutOfBound() {
when(costColumnProvider.getHeaderMappings()).thenReturn(asList(
new ColumnMappingDefinition(INDIRECT_COSTS, "Z"),
new ColumnMappingDefinition(INDIRECT_COSTS_KEY, "B"),
new ColumnMappingDefinition(EFFORT, "I")));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Missing required header columns in “Cost“ sheet.", result.errorMessage);
assertEquals("“Indirect Costs” column should be placed at position “Z”. And all the columns should be placed at the same row.", result.errorDetail);
}
@Test
public void shouldFailWhenSomeIndirectCostsHeaderColumnsAreMissing() {
sheetCostData = asList(
asList("Indirect Costs", "", "Role Level", "Role", "Hour($)", "Weekly Hours", "% of Project", "Project Days", ""),
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"),
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Missing required header columns in “Cost“ sheet.", result.errorMessage);
assertEquals("“Key” column should be placed at position “B”, “Effort” column should be placed at position “I”. "
+ "And all the columns should be placed at the same row.", result.errorDetail);
}
@Test
public void shouldFailWhenSomeIndirectCostsHeaderColumnsAreInIncorrectRow() {
sheetCostData = asList(
asList("Progress", "Key", "Grand Total", "", "", "XS", "S", "", "Effort"),
asList("Indirect Costs", "", "Role Level", "Role", "Hour($)", "Weekly Hours", "% of Project", "Project Days", ""),
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"),
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Missing required columns in “Cost“ sheet (row 2).", result.errorMessage);
assertEquals("“Key” column should be placed at position “B”, “Effort” column should be placed at position “I”.", result.errorDetail);
}
@Test
public void shouldFailWhenSomeIndirectCostsHeaderColumnsAreInIncorrectColumn() {
sheetCostData = asList(
asList("Progress", "Key", "Grand Total", "", "", "XS", "S", "", "Effort"),
asList("Indirect Costs", "Role Level", "Key", "Role", "Hour($)", "Weekly Hours", "% of Project", "Effort", "Project Days"),
asList("Dev Support", "Tech Lead", "", "Tech lead", "$225", "5.0", "", "1,446", "46"),
asList("Coach", "Coach", "", "Coach", "$225", "", "25%", "723", "46"),
asList("Total Indirect Costs", "", "", "", "", "", "", "2,169", "46"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Incorrectly positioned columns in “Cost“ sheet (row 2).", result.errorMessage);
assertEquals("“Key” column should be moved to position “B”, “Effort” column should be moved to position “I”.", result.errorDetail);
}
@Test
public void shouldFailWhenIndirectCostsHasNoFooter() {
sheetCostData = asList(
asList("Indirect Costs", "Key", "Role Level", "Role", "Hour($)", "Weekly Hours", "% of Project", "Project Days", "Effort"),
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Missing required footer columns in “Cost“ sheet.", result.errorMessage);
assertEquals("“Total Indirect Costs” column should be placed at position “A”. "
+ "And all the columns should be placed at the same row after the header row 1.", result.errorDetail);
}
@Test
public void shouldFailWhenSomeIndirectCostsFooterColumnsAreIncorrectlyPositioned() {
when(costColumnProvider.getFooterMappings()).thenReturn(asList(
new ColumnMappingDefinition(TOTAL_INDIRECT_COSTS, "A"),
new ColumnMappingDefinition(new SheetColumnDefinition("Phase"), "C"),
new ColumnMappingDefinition(new SheetColumnDefinition("Demand"), "D")));
sheetCostData = asList(
asList("Progress", "87%", "Phase", "Demand", "", "XS", "S", "", ""),
asList("Indirect Costs", "Key", "Role Level", "Role", "Hour($)", "Weekly Hours", "% of Project", "Project Days", "Effort"),
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"),
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Missing required columns in “Cost“ sheet (row 5).", result.errorMessage);
assertEquals("“Phase” column should be placed at position “C”, “Demand” column should be placed at position “D”.", result.errorDetail);
}
@Test
public void shouldFailWhenIndirectCostsFooterIsBeforeHeader() {
sheetCostData = asList(
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"),
asList("Indirect Costs", "Key", "Role Level", "Role", "Hour($)", "Weekly Hours", "% of Project", "Project Days", "Effort"),
asList("Dev Support", "", "Tech Lead", "Tech lead", "$225", "5.0", "", "46", "1,446"),
asList("Coach", "", "Coach", "Coach", "$225", "", "25%", "46", "723"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Incorrect order for header and footer in “Cost“ sheet.", result.errorMessage);
assertEquals("Footer row 1 should be moved to after the header row 2.", result.errorDetail);
}
@Test
public void shouldFailWhenIndirectCostsHasNoData() {
sheetCostData = asList(
asList("Indirect Costs", "Key", "Role Level", "Role", "Hour($)", "Weekly Hours", "% of Project", "Project Days", "Effort"),
asList("Total Indirect Costs", "", "", "", "", "", "", "46", "2,169"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid spreadsheet format: Missing Indirect Costs in “Cost“ sheet.", result.errorMessage);
assertEquals("Indirect Costs to import should start after the header row 1 and should end before the footer row 2.", result.errorDetail);
}
@Test
public void shouldFailWhenIndirectCostsHasInvalidConfiguredIssueTypeId() {
when(jiraFacade.getIssueTypeById(PARENT_TYPE_ID)).thenThrow(new IllegalArgumentException("There's no Issue Type with given ID: 1"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.failed());
assertEquals("Invalid configured issue type ids for “Cost“ sheet.", result.errorMessage);
assertEquals("There's no Issue Type with given ID: 1", result.errorDetail);
}
@Test
public void shouldReturnSuccessWhenHasNoCostSheetButSkipCostSheetValidation() {
when(costSheetSkipper.shouldSkip(SPREADSHEET_ID)).thenReturn(true);
contextWithSpreadsheet = new ValidationContextWithSpreadsheet(context, asList(SHEET_SCOPE, "Timeline"));
ValidationResult result = subject.validate(contextWithSpreadsheet);
assertTrue(result.success);
}
}
| agpl-3.0 |
zheguang/voltdb | src/ee/expressions/parametervalueexpression.cpp | 2859 | /* This file is part of VoltDB.
* Copyright (C) 2008-2014 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "parametervalueexpression.h"
#include "common/debuglog.h"
#include "common/valuevector.h"
#include "common/executorcontext.hpp"
#include "execution/VoltDBEngine.h"
namespace voltdb {
ParameterValueExpression::ParameterValueExpression(int value_idx)
: AbstractExpression(EXPRESSION_TYPE_VALUE_PARAMETER),
m_valueIdx(value_idx), m_paramValue()
{
VOLT_TRACE("ParameterValueExpression %d", value_idx);
ExecutorContext* context = ExecutorContext::getExecutorContext();
VoltDBEngine* engine = context->getEngine();
assert(engine != NULL);
NValueArray& params = engine->getParameterContainer();
assert(value_idx < params.size());
m_paramValue = ¶ms[value_idx];
};
}
| agpl-3.0 |
openmeteo/enhydris | enhydris/templates/enhydris/station_list/main-default.html | 1029 | {% extends "enhydris/station_list/common.html" %}
{% load i18n %}
{% block body_classes %}
page page-map-full
{% endblock %}
{% block title %}
{% trans 'Stations' %} — {{ block.super }}
{% endblock %}
{% block content %}
{% include "enhydris/station_list/map.html" %}
<div class="page-main-content">
<div class="container search-content-wrapper">
{% if request.GET.q or request.GET.bbox %}
<article class="search-result">
{% include "enhydris/station_list/station_list.html" %}
</article>
{% endif %}
{% block search %}
{% include "enhydris/base/search.html" %}
{% include "enhydris/base/searchtips.html" %}
{% endblock %}
</div>
</div>
{% endblock %}
{% block map_js %}
{{ block.super }}
<script type="text/javascript">
enhydris.mapMode = 'many-stations';
if (document.querySelector(".search-result")) {
document.querySelector(".page-map-full").classList.add("page-search-result");
}
</script>
{% endblock %}
| agpl-3.0 |
ipit-international/learning-environment | owncloud/settings/l10n/ko.php | 7680 | <?php
$TRANSLATIONS = array(
"Unable to load list from App Store" => "앱 스토어에서 목록을 가져올 수 없습니다",
"Authentication error" => "인증 오류",
"Group already exists" => "그룹이 이미 존재함",
"Unable to add group" => "그룹을 추가할 수 없음",
"Email saved" => "이메일 저장됨",
"Invalid email" => "잘못된 이메일 주소",
"Unable to delete group" => "그룹을 삭제할 수 없음",
"Unable to delete user" => "사용자를 삭제할 수 없음.",
"Language changed" => "언어가 변경됨",
"Invalid request" => "잘못된 요청",
"Admins can't remove themself from the admin group" => "관리자 자신을 관리자 그룹에서 삭제할 수 없음",
"Unable to add user to group %s" => "그룹 %s에 사용자를 추가할 수 없음",
"Unable to remove user from group %s" => "그룹 %s에서 사용자를 삭제할 수 없음",
"Couldn't update app." => "앱을 업데이트할 수 없습니다.",
"Wrong password" => "잘못된 비밀번호",
"Unable to change password" => "비밀번호를 변경하실수 없습니다",
"Update to {appversion}" => "버전 {appversion}(으)로 업데이트",
"Disable" => "비활성화",
"Enable" => "사용함",
"Please wait...." => "기다려 주십시오....",
"Error while disabling app" => "앱을 사용중지하는 도중 에러발생",
"Error while enabling app" => "앱을 사용토록 하는 중에 에러발생",
"Updating...." => "업데이트 중....",
"Error while updating app" => "앱을 업데이트하는 중 오류 발생",
"Error" => "오류",
"Update" => "업데이트",
"Updated" => "업데이트됨",
"Select a profile picture" => "프로필 사진 선택",
"Decrypting files... Please wait, this can take some time." => "파일 해독중... 잠시만 기다려주세요, 시간이 걸릴수 있습니다.",
"Saving..." => "저장 중...",
"deleted" => "삭제됨",
"undo" => "실행 취소",
"Unable to remove user" => "사용자를 삭제할 수 없음",
"Groups" => "그룹",
"Group Admin" => "그룹 관리자",
"Delete" => "삭제",
"add group" => "그룹 추가",
"A valid username must be provided" => "올바른 사용자 이름을 입력해야 함",
"Error creating user" => "사용자 생성 오류",
"A valid password must be provided" => "올바른 암호를 입력해야 함",
"__language_name__" => "한국어",
"Security Warning" => "보안 경고",
"Setup Warning" => "설정 경고",
"Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken." => "WebDAV 인터페이스가 제대로 작동하지 않습니다. 웹 서버에서 파일 동기화를 사용할 수 있도록 설정이 제대로 되지 않은 것 같습니다.",
"Module 'fileinfo' missing" => "모듈 'fileinfo'가 없음",
"The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." => "PHP 모듈 'fileinfo'가 존재하지 않습니다. MIME 형식 감지 결과를 향상시키기 위하여 이 모듈을 활성화하는 것을 추천합니다.",
"Locale not working" => "로캘이 작동하지 않음",
"Internet connection not working" => "인터넷에 연결할 수 없음",
"Cron" => "크론",
"Execute one task with each page loaded" => "개별 페이지를 불러올 때마다 실행",
"Sharing" => "공유",
"Enable Share API" => "공유 API 사용하기",
"Allow apps to use the Share API" => "앱에서 공유 API를 사용할 수 있도록 허용",
"Allow links" => "링크 허용",
"Allow users to share items to the public with links" => "사용자가 개별 항목의 링크를 공유할 수 있도록 허용",
"Allow public uploads" => "퍼블릭 업로드 허용",
"Allow resharing" => "재공유 허용",
"Allow users to share items shared with them again" => "사용자에게 공유된 항목을 다시 공유할 수 있도록 허용",
"Allow users to share with anyone" => "누구나와 공유할 수 있도록 허용",
"Allow users to only share with users in their groups" => "사용자가 속해 있는 그룹의 사용자와만 공유할 수 있도록 허용",
"Allow mail notification" => "메일 알림을 허용",
"Allow user to send mail notification for shared files" => "사용자에게 공유 파일에 대한 메일 알림을 허용합니다",
"Security" => "보안",
"Enforce HTTPS" => "HTTPS 강제 사용",
"Log" => "로그",
"Log level" => "로그 단계",
"More" => "더 중요함",
"Less" => "덜 중요함",
"Version" => "버전",
"Developed by the <a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud community</a>, the <a href=\"https://github.com/owncloud\" target=\"_blank\">source code</a> is licensed under the <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>." => "<a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud 커뮤니티</a>에 의해서 개발되었습니다. <a href=\"https://github.com/owncloud\" target=\"_blank\">원본 코드</a>는 <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>에 따라 사용이 허가됩니다.",
"Add your App" => "내 앱 추가",
"More Apps" => "더 많은 앱",
"Select an App" => "앱 선택",
"See application page at apps.owncloud.com" => "apps.owncloud.com에 있는 앱 페이지를 참고하십시오",
"<span class=\"licence\"></span>-licensed by <span class=\"author\"></span>" => "<span class=\"licence\"></span>-라이선스됨: <span class=\"author\"></span>",
"User Documentation" => "사용자 문서",
"Administrator Documentation" => "관리자 문서",
"Online Documentation" => "온라인 문서",
"Forum" => "포럼",
"Bugtracker" => "버그 트래커",
"Commercial Support" => "상업용 지원",
"Get the apps to sync your files" => "파일 동기화 앱 가져오기",
"Show First Run Wizard again" => "첫 실행 마법사 다시 보이기",
"You have used <strong>%s</strong> of the available <strong>%s</strong>" => "현재 공간 중 <strong>%s</strong>/<strong>%s</strong>을(를) 사용 중입니다",
"Password" => "암호",
"Your password was changed" => "암호가 변경되었습니다",
"Unable to change your password" => "암호를 변경할 수 없음",
"Current password" => "현재 암호",
"New password" => "새 암호",
"Change password" => "암호 변경",
"Email" => "이메일",
"Your email address" => "이메일 주소",
"Fill in an email address to enable password recovery" => "암호 찾기 기능을 사용하려면 이메일 주소를 입력하십시오",
"Profile picture" => "프로필 사진",
"Upload new" => "새로이 업로드하기",
"Select new from Files" => "파일에서 선택",
"Remove image" => "그림 삭제",
"Abort" => "대하여",
"Choose as profile image" => "프로필 사진을 선택해주세요",
"Language" => "언어",
"Help translate" => "번역 돕기",
"WebDAV" => "WebDAV",
"Encryption" => "암호화",
"Log-in password" => "로그인 비밀번호",
"Decrypt all Files" => "모든 파일 해독",
"Login Name" => "로그인 이름",
"Create" => "만들기",
"Admin Recovery Password" => "관리자 복구 암호",
"Enter the recovery password in order to recover the users files during password change" => "암호 변경 시 변경된 사용자 파일을 복구하려면 복구 암호를 입력하십시오",
"Default Storage" => "기본 저장소",
"Unlimited" => "무제한",
"Other" => "기타",
"Username" => "사용자 이름",
"Storage" => "저장소",
"set new password" => "새 암호 설정",
"Default" => "기본값"
);
$PLURAL_FORMS = "nplurals=1; plural=0;";
| agpl-3.0 |
wesley1001/io.scrollback.neighborhoods | android/app/src/main/java/io/scrollback/neighborhoods/bundle/Checksum.java | 1065 | package io.scrollback.neighborhoods.bundle;
import android.support.annotation.NonNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Checksum {
public static String MD5(@NonNull InputStream stream) throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[8192];
int numOfBytesRead;
while ((numOfBytesRead = stream.read(buffer)) > 0) {
md.update(buffer, 0, numOfBytesRead);
}
byte[] hash = md.digest();
return String.format("%032x", new BigInteger(1, hash));
}
public static String MD5(@NonNull File file) throws IOException, NoSuchAlgorithmException {
InputStream stream = new FileInputStream(file);
try {
return MD5(stream);
} finally {
stream.close();
}
}
}
| agpl-3.0 |
et304383/passbolt_api | app/webroot/js/lib/can/dist/amd/can/hashchange.js | 719 | /*!
* CanJS - 2.2.9
* http://canjs.com/
* Copyright (c) 2015 Bitovi
* Fri, 11 Sep 2015 23:12:43 GMT
* Licensed MIT
*/
/*[email protected]#util/hashchange*/
define(['can/util/can'], function (can) {
(function () {
var addEvent = function (el, ev, fn) {
if (el.addEventListener) {
el.addEventListener(ev, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + ev, fn);
} else {
el['on' + ev] = fn;
}
}, onHashchange = function () {
can.trigger(window, 'hashchange');
};
addEvent(window, 'hashchange', onHashchange);
}());
});
| agpl-3.0 |
shahrooz33ce/sugarcrm | include/database/MssqlManager.php | 51509 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: This file handles the Data base functionality for the application.
* It acts as the DB abstraction layer for the application. It depends on helper classes
* which generate the necessary SQL. This sql is then passed to PEAR DB classes.
* The helper class is chosen in DBManagerFactory, which is driven by 'db_type' in 'dbconfig' under config.php.
*
* All the functions in this class will work with any bean which implements the meta interface.
* The passed bean is passed to helper class which uses these functions to generate correct sql.
*
* The meta interface has the following functions:
* getTableName() Returns table name of the object.
* getFieldDefinitions() Returns a collection of field definitions in order.
* getFieldDefintion(name) Return field definition for the field.
* getFieldValue(name) Returns the value of the field identified by name.
* If the field is not set, the function will return boolean FALSE.
* getPrimaryFieldDefinition() Returns the field definition for primary key
*
* The field definition is an array with the following keys:
*
* name This represents name of the field. This is a required field.
* type This represents type of the field. This is a required field and valid values are:
* int
* long
* varchar
* text
* date
* datetime
* double
* float
* uint
* ulong
* time
* short
* enum
* length This is used only when the type is varchar and denotes the length of the string.
* The max value is 255.
* enumvals This is a list of valid values for an enum separated by "|".
* It is used only if the type is ?enum?;
* required This field dictates whether it is a required value.
* The default value is ?FALSE?.
* isPrimary This field identifies the primary key of the table.
* If none of the fields have this flag set to ?TRUE?,
* the first field definition is assume to be the primary key.
* Default value for this field is ?FALSE?.
* default This field sets the default value for the field definition.
*
*
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
class MssqlManager extends DBManager
{
/**
* @see DBManager::$dbType
*/
public $dbType = 'mssql';
/**
* @see DBManager::$backendFunctions
*/
protected $backendFunctions = array(
'free_result' => 'mssql_free_result',
'close' => 'mssql_close',
'row_count' => 'mssql_num_rows'
);
/**
* @see DBManager::connect()
*/
public function connect(
array $configOptions = null,
$dieOnError = false
)
{
global $sugar_config;
if (is_null($configOptions))
$configOptions = $sugar_config['dbconfig'];
//SET DATEFORMAT to 'YYYY-MM-DD''
ini_set('mssql.datetimeconvert', '0');
//set the text size and textlimit to max number so that blob columns are not truncated
ini_set('mssql.textlimit','2147483647');
ini_set('mssql.textsize','2147483647');
//set the connections parameters
$connect_param = '';
$configOptions['db_host_instance'] = trim($configOptions['db_host_instance']);
if (empty($configOptions['db_host_instance']))
$connect_param = $configOptions['db_host_name'];
else
$connect_param = $configOptions['db_host_name']."\\".$configOptions['db_host_instance'];
//create persistent connection
if ($sugar_config['dbconfigoption']['persistent'] == true) {
$this->database =@mssql_pconnect(
$connect_param ,
$configOptions['db_user_name'],
$configOptions['db_password']
);
}
//if no persistent connection created, then create regular connection
if(!$this->database){
$this->database = mssql_connect(
$connect_param ,
$configOptions['db_user_name'],
$configOptions['db_password']
);
if(!$this->database){
$GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name'].
" as ".$configOptions['db_user_name'].".");
sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
}
if($this->database && $sugar_config['dbconfigoption']['persistent'] == true){
$_SESSION['administrator_error'] = "<B>Severe Performance Degradation: Persistent Database Connections "
. "not working. Please set \$sugar_config['dbconfigoption']['persistent'] to false in your "
. "config.php file</B>";
}
}
//make sure connection exists
if(!$this->database){
sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
}
//select database
//Adding sleep and retry for mssql connection. We have come across scenarios when
//an error is thrown.' Unable to select database'. Following will try to connect to
//mssql db maximum number of 5 times at the interval of .2 second. If can not connect
//it will throw an Unable to select database message.
if(!@mssql_select_db($configOptions['db_name'], $this->database)){
$connected = false;
for($i=0;$i<5;$i++){
usleep(200000);
if(@mssql_select_db($configOptions['db_name'], $this->database)){
$connected = true;
break;
}
}
if(!$connected){
$GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}");
sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
}
}
if($this->checkError('Could Not Connect', $dieOnError))
$GLOBALS['log']->info("connected to db");
$GLOBALS['log']->info("Connect:".$this->database);
}
/**
* @see DBManager::version()
*/
public function version()
{
return $this->getOne("SELECT @@VERSION as version");
}
/**
* @see DBManager::checkError()
*/
public function checkError(
$msg = '',
$dieOnError = false
)
{
if (parent::checkError($msg, $dieOnError))
return true;
$sqlmsg = mssql_get_last_message();
$sqlpos = strpos($sqlmsg, 'Changed database context to');
$sqlpos2 = strpos($sqlmsg, 'Warning:');
$sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false )
$sqlmsg = ''; // empty out sqlmsg if its either of the two error messages described above
else {
global $app_strings;
//ERR_MSSQL_DB_CONTEXT: localized version of 'Changed database context to' message
if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
//ignore the message from sql-server if $app_strings array is empty. This will happen
//only if connection if made before languge is set.
$GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
$sqlmsg = '';
}
else {
$sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
if ( $sqlpos !== false )
$sqlmsg = '';
}
}
if ( strlen($sqlmsg) > 2 ) {
$GLOBALS['log']->fatal("$msg: SQL Server error: " . $sqlmsg);
return true;
}
return false;
}
/**
* @see DBManager::query()
*/
public function query(
$sql,
$dieOnError = false,
$msg = '',
$suppress = false
)
{
// Flag if there are odd number of single quotes
if ((substr_count($sql, "'") & 1))
$GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
$this->countQuery($sql);
$GLOBALS['log']->info('Query:' . $sql);
$this->checkConnection();
$this->query_time = microtime(true);
// Bug 34892 - Clear out previous error message by checking the @@ERROR global variable
$errorNumberHandle = mssql_query("SELECT @@ERROR",$this->database);
$errorNumber = array_shift(mssql_fetch_row($errorNumberHandle));
if ($suppress) {
}
else {
$result = @mssql_query($sql, $this->database);
}
if (!$result) {
// awu Bug 10657: ignoring mssql error message 'Changed database context to' - an intermittent
// and difficult to reproduce error. The message is only a warning, and does
// not affect the functionality of the query
$sqlmsg = mssql_get_last_message();
$sqlpos = strpos($sqlmsg, 'Changed database context to');
$sqlpos2 = strpos($sqlmsg, 'Warning:');
$sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false) // if sqlmsg has 'Changed database context to', just log it
$GLOBALS['log']->debug($sqlmsg . ": " . $sql );
else {
$GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
if($dieOnError)
sugar_die('SQL Error : ' . $sqlmsg);
else
echo 'SQL Error : ' . $sqlmsg;
}
}
$this->lastmysqlrow = -1;
$this->query_time = microtime(true) - $this->query_time;
$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
$this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
return $result;
}
/**
* This function take in the sql for a union query, the start and offset,
* and wraps it around an "mssql friendly" limit query
*
* @param string $sql
* @param int $start record to start at
* @param int $count number of records to retrieve
* @return string SQL statement
*/
private function handleUnionLimitQuery(
$sql,
$start,
$count
)
{
//set the start to 0, no negs
if ($start < 0)
$start=0;
$GLOBALS['log']->debug(print_r(func_get_args(),true));
$this->lastsql = $sql;
//change the casing to lower for easier string comparison, and trim whitespaces
$sql = strtolower(trim($sql)) ;
//set default sql
$limitUnionSQL = $sql;
$order_by_str = 'order by';
//make array of order by's. substring approach was proving too inconsistent
$orderByArray = explode($order_by_str, $sql);
$unionOrderBy = '';
$rowNumOrderBy = '';
//count the number of array elements
$unionOrderByCount = count($orderByArray);
$arr_count = 0;
//process if there are elements
if ($unionOrderByCount){
//we really want the last ordery by, so reconstruct string
//adding a 1 to count, as we dont wish to process the last element
$unionsql = '';
while ($unionOrderByCount>$arr_count+1) {
$unionsql .= $orderByArray[$arr_count];
$arr_count = $arr_count+1;
//add an "order by" string back if we are coming into loop again
//remember they were taken out when array was created
if ($unionOrderByCount>$arr_count+1) {
$unionsql .= "order by";
}
}
//grab the last order by element, set both order by's'
$unionOrderBy = $orderByArray[$arr_count];
$rowNumOrderBy = $unionOrderBy;
//if last element contains a "select", then this is part of the union query,
//and there is no order by to use
if (strpos($unionOrderBy, "select")) {
$unionsql = $sql;
//with no guidance on what to use for required order by in rownumber function,
//resort to using name column.
$rowNumOrderBy = 'id';
$unionOrderBy = "";
}
}
else {
//there are no order by elements, so just pass back string
$unionsql = $sql;
//with no guidance on what to use for required order by in rownumber function,
//resort to using name column.
$rowNumOrderBy = 'id';
$unionOrderBy = '';
}
//Unions need the column name being sorted on to match acroos all queries in Union statement
//so we do not want to strip the alias like in other queries. Just add the "order by" string and
//pass column name as is
if ($unionOrderBy != '') {
$unionOrderBy = ' order by ' . $unionOrderBy;
}
//if start is 0, then just use a top query
if($start == 0) {
$limitUnionSQL = "select top $count * from (" .$unionsql .") as top_count ".$unionOrderBy;
}
else {
//if start is more than 0, then use top query in conjunction
//with rownumber() function to create limit query.
$limitUnionSQL = "select top $count * from( select ROW_NUMBER() OVER ( order by "
.$rowNumOrderBy.") AS row_number, * from ("
.$unionsql .") As numbered) "
. "As top_count_limit WHERE row_number > $start "
.$unionOrderBy;
}
return $limitUnionSQL;
}
/**
* @see DBManager::limitQuery()
*/
public function limitQuery(
$sql,
$start,
$count,
$dieOnError = false,
$msg = '')
{
$newSQL = $sql;
$distinctSQLARRAY = array();
if (strpos($sql, "UNION") && !preg_match("/(\')(UNION).?(\')/i", $sql))
$newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
else {
if ($start < 0)
$start = 0;
$GLOBALS['log']->debug(print_r(func_get_args(),true));
$this->lastsql = $sql;
$matches = array();
preg_match('/^(.*SELECT )(.*?FROM.*WHERE)(.*)$/isxU',$sql, $matches);
if (!empty($matches[3])) {
if ($start == 0) {
$match_two = strtolower($matches[2]);
if (!strpos($match_two, "distinct")> 0 && strpos($match_two, "distinct") !==0) {
//proceed as normal
$newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
}
else {
$distinct_o = strpos($match_two, "distinct");
$up_to_distinct_str = substr($match_two, 0, $distinct_o);
//check to see if the distinct is within a function, if so, then proceed as normal
if (strpos($up_to_distinct_str,"(")) {
//proceed as normal
$newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
}
else {
//if distinct is not within a function, then parse
//string contains distinct clause, "TOP needs to come after Distinct"
//get position of distinct
$match_zero = strtolower($matches[0]);
$distinct_pos = strpos($match_zero , "distinct");
//get position of where
$where_pos = strpos($match_zero, "where");
//parse through string
$beg = substr($matches[0], 0, $distinct_pos+9 );
$mid = substr($matches[0], strlen($beg), ($where_pos+5) - (strlen($beg)));
$end = substr($matches[0], strlen($beg) + strlen($mid) );
//repopulate matches array
$matches[1] = $beg; $matches[2] = $mid; $matches[3] = $end;
$newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
}
}
}
else {
$orderByMatch = array();
preg_match('/^(.*)(ORDER BY)(.*)$/is',$matches[3], $orderByMatch);
//if there is a distinct clause, parse sql string as we will have to insert the rownumber
//for paging, AFTER the distinct clause
$hasDistinct = strpos(strtolower($matches[0]), "distinct");
if ($hasDistinct) {
$matches_sql = strtolower($matches[0]);
//remove reference to distinct and select keywords, as we will use a group by instead
//we need to use group by because we are introducing rownumber column which would make every row unique
//take out the select and distinct from string so we can reuse in group by
$dist_str = ' distinct ';
$distinct_pos = strpos($matches_sql, $dist_str);
$matches_sql = substr($matches_sql,$distinct_pos+ strlen($dist_str));
//get the position of where and from for further processing
$from_pos = strpos($matches_sql , " from ");
$where_pos = strpos($matches_sql, "where");
//split the sql into a string before and after the from clause
//we will use the columns being selected to construct the group by clause
if ($from_pos>0 ) {
$distinctSQLARRAY[0] = substr($matches_sql,0, $from_pos+1);
$distinctSQLARRAY[1] = substr($matches_sql,$from_pos+1);
//get position of order by (if it exists) so we can strip it from the string
$ob_pos = strpos($distinctSQLARRAY[1], "order by");
if ($ob_pos) {
$distinctSQLARRAY[1] = substr($distinctSQLARRAY[1],0,$ob_pos);
}
// strip off last closing parathese from the where clause
$distinctSQLARRAY[1] = preg_replace("/\)\s$/"," ",$distinctSQLARRAY[1]);
}
//place group by string into array
$grpByArr = explode(',', $distinctSQLARRAY[0]);
$grpByStr = '';
$first = true;
//remove the aliases for each group by element, sql server doesnt like these in group by.
foreach ($grpByArr as $gb) {
$gb = trim($gb);
//clean out the extra stuff added if we are concating first_name and last_name together
//this way both fields are added in correctly to the group by
$gb = str_replace("isnull(","",$gb);
$gb = str_replace("'') + ' ' + ","",$gb);
//remove outer reference if they exist
if (strpos($gb,"'")!==false){
continue;
}
//if there is a space, then an alias exists, remove alias
if (strpos($gb,' ')){
$gb = substr( $gb, 0,strpos($gb,' '));
}
//if resulting string is not empty then add to new group by string
if (!empty($gb)) {
if ($first) {
$grpByStr .= " $gb";
$first = false;
}
else {
$grpByStr .= ", $gb";
}
}
}
}
if (!empty($orderByMatch[3])) {
//if there is a distinct clause, form query with rownumber after distinct
if ($hasDistinct) {
$newSQL = "SELECT TOP $count * FROM
(
SELECT ROW_NUMBER()
OVER (ORDER BY ".$this->returnOrderBy($sql, $orderByMatch[3]).") AS row_number,
count(*) counter, " . $distinctSQLARRAY[0] . "
" . $distinctSQLARRAY[1] . "
group by " . $grpByStr . "
) AS a
WHERE row_number > $start";
}
else {
$newSQL = "SELECT TOP $count * FROM
(
" . $matches[1] . " ROW_NUMBER()
OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number,
" . $matches[2] . $orderByMatch[1]. "
) AS a
WHERE row_number > $start";
}
}else{
//bug: 22231 Records in campaigns' subpanel may not come from
//table of $_REQUEST['module']. Get it directly from query
$upperQuery = strtoupper($matches[2]);
if (!strpos($upperQuery,"JOIN")){
$from_pos = strpos($upperQuery , "FROM") + 4;
$where_pos = strpos($upperQuery, "WHERE");
$tablename = trim(substr($upperQuery,$from_pos, $where_pos - $from_pos));
}else{
$tablename = $this->getTableNameFromModuleName($_REQUEST['module'],$sql);
}
//if there is a distinct clause, form query with rownumber after distinct
if ($hasDistinct) {
$newSQL = "SELECT TOP $count * FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
" . $distinctSQLARRAY[1] . "
group by " . $grpByStr . "
)
AS a
WHERE row_number > $start";
}
else {
$newSQL = "SELECT TOP $count * FROM
(
" . $matches[1] . " ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, " . $matches[2] . $matches[3]. "
)
AS a
WHERE row_number > $start";
}
}
}
}
}
$GLOBALS['log']->debug('Limit Query: ' . $newSQL);
$result = $this->query($newSQL, $dieOnError, $msg);
$this->dump_slow_queries($newSQL);
return $result;
}
/**
* Searches for begginning and ending characters. It places contents into
* an array and replaces contents in original string. This is used to account for use of
* nested functions while aliasing column names
*
* @param string $p_sql SQL statement
* @param string $strip_beg Beginning character
* @param string $strip_end Ending character
* @param string $patt Optional, pattern to
*/
private function removePatternFromSQL(
$p_sql,
$strip_beg,
$strip_end,
$patt = 'patt')
{
//strip all single quotes out
$beg_sin = 0;
$sec_sin = 0;
$count = substr_count ( $p_sql, $strip_beg);
$increment = 1;
if ($strip_beg != $strip_end)
$increment = 2;
$i=0;
$offset = 0;
$strip_array = array();
while ($i<$count && $offset<strlen($p_sql)) {
if ($offset > strlen($p_sql))
{
break;
}
$beg_sin = strpos($p_sql, $strip_beg, $offset);
if (!$beg_sin)
{
break;
}
$sec_sin = strpos($p_sql, $strip_end, $beg_sin+1);
$strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin +1);
if ($increment > 1) {
//we are in here because beginning and end patterns are not identical, so search for nesting
$exists = strpos($strip_array[$patt.$i], $strip_beg );
if ($exists>=0) {
$nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg ));
$strip_array[$patt.$i] = substr($p_sql,$nested_pos+$beg_sin,$sec_sin - ($nested_pos+$beg_sin)+1);
$p_sql = substr($p_sql, 0, $nested_pos+$beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
$i = $i + 1;
$beg_sin = $nested_pos;
continue;
}
}
$p_sql = substr($p_sql, 0, $beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
//move the marker up
$offset = $sec_sin+1;
$i = $i + 1;
}
$strip_array['sql_string'] = $p_sql;
return $strip_array;
}
/**
* adds a pattern
*
* @param string $token
* @param array $pattern_array
* @return string
*/
private function addPatternToSQL(
$token,
array $pattern_array
)
{
//strip all single quotes out
$pattern_array = array_reverse($pattern_array);
foreach ($pattern_array as $key => $replace) {
$token = str_replace( "##".$key."##", $replace,$token);
}
return $token;
}
/**
* gets an alias from the sql statement
*
* @param string $sql
* @param string $alias
* @return string
*/
private function getAliasFromSQL(
$sql,
$alias
)
{
$matches = array();
preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
//parse all single and double quotes out of array
$sin_array = $this->removePatternFromSQL($matches[2], "'", "'","sin_");
$new_sql = array_pop($sin_array);
$dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"","dub_");
$new_sql = array_pop($dub_array);
//search for parenthesis
$paren_array = $this->removePatternFromSQL($new_sql, "(", ")", "par_");
$new_sql = array_pop($paren_array);
//all functions should be removed now, so split the array on comma's
$mstr_sql_array = explode(",", $new_sql);
foreach($mstr_sql_array as $token ) {
if (strpos($token, $alias)) {
//found token, add back comments
$token = $this->addPatternToSQL($token, $paren_array);
$token = $this->addPatternToSQL($token, $dub_array);
$token = $this->addPatternToSQL($token, $sin_array);
//log and break out of this function
return $token;
}
}
return null;
}
/**
* Finds the alias of the order by column, and then return the preceding column name
*
* @param string $sql
* @param string $orderMatch
* @return string
*/
private function findColumnByAlias(
$sql,
$orderMatch
)
{
//change case to lowercase
$sql = strtolower($sql);
$patt = '/\s+'.trim($orderMatch).'\s*,/';
//check for the alias, it should contain comma, may contain space, \n, or \t
$matches = array();
preg_match($patt, $sql, $matches, PREG_OFFSET_CAPTURE);
$found_in_sql = isset($matches[0][1]) ? $matches[0][1] : false;
//set default for found variable
$found = $found_in_sql;
//if still no match found, then we need to parse through the string
if (!$found_in_sql){
//get count of how many times the match exists in string
$found_count = substr_count($sql, $orderMatch);
$i = 0;
$first_ = 0;
$len = strlen($orderMatch);
//loop through string as many times as there is a match
while ($found_count > $i) {
//get the first match
$found_in_sql = strpos($sql, $orderMatch,$first_);
//make sure there was a match
if($found_in_sql){
//grab the next 2 individual characters
$str_plusone = substr($sql,$found_in_sql + $len,1);
$str_plustwo = substr($sql,$found_in_sql + $len+1,1);
//if one of those characters is a comma, then we have our alias
if ($str_plusone === "," || $str_plustwo === ","){
//keep track of this position
$found = $found_in_sql;
}
}
//set the offset and increase the iteration counter
$first_ = $found_in_sql+$len;
$i = $i+1;
}
}
//return $found, defaults have been set, so if no match was found it will be a negative number
return $found;
}
/**
* Return the order by string to use in case the column has been aliased
*
* @param string $sql
* @param string $orig_order_match
* @return string
*/
private function returnOrderBy(
$sql,
$orig_order_match
)
{
$sql = strtolower($sql);
$orig_order_match = trim($orig_order_match);
if (strpos($orig_order_match, ".") != 0)
//this has a tablename defined, pass in the order match
return $orig_order_match;
//grab first space in order by
$firstSpace = strpos($orig_order_match, " ");
//split order by into column name and ascending/descending
$orderMatch = " " . strtolower(substr($orig_order_match, 0, $firstSpace));
$asc_desc = substr($orig_order_match,$firstSpace);
//look for column name as an alias in sql string
$found_in_sql = $this->findColumnByAlias($sql, $orderMatch);
if (!$found_in_sql) {
//check if this column needs the tablename prefixed to it
$orderMatch = ".".trim($orderMatch);
$colMatchPos = strpos($sql, $orderMatch);
if ($colMatchPos !== false) {
//grab sub string up to column name
$containsColStr = substr($sql,0, $colMatchPos);
//get position of first space, so we can grab table name
$lastSpacePos = strrpos($containsColStr, " ");
//use positions of column name, space before name, and length of column to find the correct column name
$col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
//bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
$containsCommaPos = strpos($col_name, ",");
if($containsCommaPos !== false) {
$col_name = substr($col_name, $containsCommaPos+1);
}
//return column name
return $col_name;
}
//break out of here, log this
$GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
return $orig_order_match;
}
else {
//if found, then parse and return
//grab string up to the aliased column
$GLOBALS['log']->debug("order by found, process sql string");
$psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
if (empty($psql))
$psql = trim(substr($sql, 0, $found_in_sql));
//grab the last comma before the alias
$comma_pos = strrpos($psql, " ");
//substring between the comma and the alias to find the joined_table alias and column name
$col_name = substr($psql,0, $comma_pos);
//make sure the string does not have an end parenthesis
//and is not part of a function (i.e. "ISNULL(leads.last_name,'') as name" )
//this is especially true for unified search from home screen
$alias_beg_pos = 0;
if(strpos($psql, " as "))
$alias_beg_pos = strpos($psql, " as ");
// Bug # 44923 - This breaks the query and does not properly filter isnull
// as there are other functions such as ltrim and rtrim.
/* else if (strncasecmp($psql, 'isnull', 6) != 0)
$alias_beg_pos = strpos($psql, " "); */
if ($alias_beg_pos > 0) {
$col_name = substr($psql,0, $alias_beg_pos );
}
//add the "asc/desc" order back
$col_name = $col_name. " ". $asc_desc;
//pass in new order by
$GLOBALS['log']->debug("order by being returned is " . $col_name);
return $col_name;
}
}
/**
* Take in a string of the module and retrieve the correspondent table name
*
* @param string $module_str module name
* @param string $sql SQL statement
* @return string table name
*/
private function getTableNameFromModuleName(
$module_str,
$sql
)
{
global $beanList, $beanFiles;
$GLOBALS['log']->debug("Module being processed is " . $module_str);
//get the right module files
//the module string exists in bean list, then process bean for correct table name
//note that we exempt the reports module from this, as queries from reporting module should be parsed for
//correct table name.
if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str]) && isset($beanFiles[$beanList[$module_str]])){
//if the class is not already loaded, then load files
if (!class_exists($beanList[$module_str]))
require_once($beanFiles[$beanList[$module_str]]);
//instantiate new bean
$module_bean = new $beanList[$module_str]();
//get table name from bean
$tbl_name = $module_bean->table_name;
//make sure table name is not just a blank space, or empty
$tbl_name = trim($tbl_name);
if(empty($tbl_name)){
$GLOBALS['log']->debug("Could not find table name for module $module_str. ");
$tbl_name = $module_str;
}
}
else {
//since the module does NOT exist in beanlist, then we have to parse the string
//and grab the table name from the passed in sql
$GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
$tbl_name = $module_str;
$sql = strtolower($sql);
//look for the location of the "from" in sql string
$fromLoc = strpos($sql," from " );
if ($fromLoc>0){
//found from, substring from the " FROM " string in sql to end
$tableEnd = substr($sql, $fromLoc+6);
//We know that tablename will be next parameter after from, so
//grab the next space after table name.
// MFH BUG #14009: Also check to see if there are any carriage returns before the next space so that we don't grab any arbitrary joins or other tables.
$carriage_ret = strpos($tableEnd,"\n");
$next_space = strpos($tableEnd," " );
if ($carriage_ret < $next_space)
$next_space = $carriage_ret;
if ($next_space > 0) {
$tbl_name= substr($tableEnd,0, $next_space);
if(empty($tbl_name)){
$GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
$tbl_name = $module_str;
}
}
//grab the table, to see if it is aliased
$aliasTableEnd = trim(substr($tableEnd, $next_space));
$alias_space = strpos ($aliasTableEnd, " " );
if ($alias_space > 0){
$alias_tbl_name= substr($aliasTableEnd,0, $alias_space);
strtolower($alias_tbl_name);
if(empty($alias_tbl_name)
|| $alias_tbl_name == "where"
|| $alias_tbl_name == "inner"
|| $alias_tbl_name == "left"
|| $alias_tbl_name == "join"
|| $alias_tbl_name == "outer"
|| $alias_tbl_name == "right") {
//not aliased, do nothing
}
elseif ($alias_tbl_name == "as") {
//the next word is the table name
$aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
$alias_space = strpos ($aliasTableEnd, " " );
if ($alias_space > 0) {
$alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
if (!empty($alias_tbl_name))
$tbl_name = $alias_tbl_name;
}
}
else {
//this is table alias
$tbl_name = $alias_tbl_name;
}
}
}
}
//return table name
$GLOBALS['log']->debug("Table name for module $module_str is: ".$tbl_name);
return $tbl_name;
}
/**
* @see DBManager::getFieldsArray()
*/
public function getFieldsArray(
&$result,
$make_lower_case = false
)
{
$field_array = array();
if(! isset($result) || empty($result))
return 0;
$i = 0;
while ($i < mssql_num_fields($result)) {
$meta = mssql_fetch_field($result, $i);
if (!$meta)
return 0;
if($make_lower_case==true)
$meta->name = strtolower($meta->name);
$field_array[] = $meta->name;
$i++;
}
return $field_array;
}
/**
* @see DBManager::getAffectedRowCount()
*/
public function getAffectedRowCount()
{
return $this->getOne("SELECT @@ROWCOUNT");
}
/**
* @see DBManager::describeField()
*/
protected function describeField(
$name,
$tablename
)
{
global $table_descriptions;
if(isset($table_descriptions[$tablename]) && isset($table_descriptions[$tablename][$name])){
return $table_descriptions[$tablename][$name];
}
$table_descriptions[$tablename] = array();
$sql = sprintf( "SELECT COLUMN_NAME AS Field
, DATA_TYPE + CASE WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL
THEN '(' + RTRIM(CAST(CHARACTER_MAXIMUM_LENGTH AS CHAR)) + ')'
ELSE '' END as 'Type'
, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE AS 'Null'
, CASE WHEN COLUMN_DEFAULT LIKE '((0))' THEN '(''0'')' ELSE COLUMN_DEFAULT END as 'Default'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '%s'",
$tablename
);
$result = $this->query($sql);
while ($row = $this->fetchByAssoc($result) )
$table_descriptions[$tablename][$row['Field']] = $row;
if (isset($table_descriptions[$tablename][$name]))
return $table_descriptions[$tablename][$name];
return array();
}
/**
* @see DBManager::fetchByAssoc()
*/
public function fetchByAssoc(
&$result,
$rowNum = -1,
$encode = true
)
{
if (!$result)
return false;
if ($result && $rowNum < 0) {
$row = mssql_fetch_assoc($result);
//MSSQL returns a space " " when a varchar column is empty ("") and not null.
//We need to iterate through the returned row array and strip empty spaces
if(!empty($row)){
foreach($row as $key => $column) {
//notice we only strip if one space is returned. we do not want to strip
//strings with intentional spaces (" foo ")
if (!empty($column) && $column ==" ") {
$row[$key] = '';
}
}
}
if($encode && $this->encode&& is_array($row))
return array_map('to_html', $row);
return $row;
}
if ($this->getRowCount($result) > $rowNum) {
if ( $rowNum == -1 )
$rowNum = 0;
@mssql_data_seek($result, $rowNum);
}
$this->lastmysqlrow = $rowNum;
$row = @mssql_fetch_assoc($result);
if($encode && $this->encode && is_array($row))
return array_map('to_html', $row);
return $row;
}
/**
* @see DBManager::quote()
*/
public function quote(
$string,
$isLike = true
)
{
return $string = str_replace("'","''", parent::quote($string));
}
/**
* @see DBManager::quoteForEmail()
*/
public function quoteForEmail(
$string,
$isLike = true
)
{
return str_replace("'","''", $string);
}
/**
* @see DBManager::tableExists()
*/
public function tableExists(
$tableName
)
{
$GLOBALS['log']->info("tableExists: $tableName");
$this->checkConnection();
$result = $this->query(
"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='".$tableName."'");
$rowCount = $this->getRowCount($result);
$this->freeResult($result);
return ($rowCount == 0) ? false : true;
}
/**
* @see DBManager::addIndexes()
*/
public function addIndexes(
$tablename,
$indexes,
$execute = true
)
{
$alters = $this->helper->indexSQL($tablename,array(),$indexes);
if ($execute)
$this->query($alters);
return $alters;
}
/**
* @see DBManager::dropIndexes()
*/
public function dropIndexes(
$tablename,
$indexes,
$execute = true
)
{
$sql = '';
foreach ($indexes as $index) {
if ( !empty($sql) ) $sql .= ";";
$name = $index['name'];
if($execute)
unset($GLOBALS['table_descriptions'][$tablename]['indexes'][$name]);
if ($index['type'] == 'primary')
$sql .= "ALTER TABLE $tablename DROP CONSTRAINT $name";
else
$sql .= "DROP INDEX $name on $tablename";
}
if (!empty($sql))
if($execute)
$this->query($sql);
return $sql;
}
/**
* @see DBManager::checkQuery()
*/
protected function checkQuery(
$sql
)
{
return true;
}
/**
* @see DBManager::getTablesArray()
*/
public function getTablesArray()
{
$GLOBALS['log']->debug('MSSQL fetching table list');
if($this->getDatabase()) {
$tables = array();
$r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
if (is_resource($r)) {
while ($a = $this->fetchByAssoc($r))
$tables[] = $a['TABLE_NAME'];
return $tables;
}
}
return false; // no database available
}
/**
* This call is meant to be used during install, when Full Text Search is enabled
* Indexing would always occur after a fresh sql server install, so this code creates
* a catalog and table with full text index.
*/
public function wakeupFTS()
{
$GLOBALS['log']->debug('MSSQL about to wakeup FTS');
if($this->getDatabase()) {
//create wakup catalog
$FTSqry[] = "if not exists( select * from sys.fulltext_catalogs where name ='wakeup_catalog' )
CREATE FULLTEXT CATALOG wakeup_catalog
";
//drop wakeup table if it exists
$FTSqry[] = "IF EXISTS(SELECT 'fts_wakeup' FROM sysobjects WHERE name = 'fts_wakeup' AND xtype='U')
DROP TABLE fts_wakeup
";
//create wakeup table
$FTSqry[] = "CREATE TABLE fts_wakeup(
id varchar(36) NOT NULL CONSTRAINT pk_fts_wakeup_id PRIMARY KEY CLUSTERED (id ASC ),
body text NULL,
kb_index int IDENTITY(1,1) NOT NULL CONSTRAINT wakeup_fts_unique_idx UNIQUE NONCLUSTERED
)
";
//create full text index
$FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
(
body
Language 0X0
)
KEY INDEX wakeup_fts_unique_idx ON wakeup_catalog
WITH CHANGE_TRACKING AUTO
";
//insert dummy data
$FTSqry[] = "INSERT INTO fts_wakeup (id ,body)
VALUES ('".create_guid()."', 'SugarCRM Rocks' )";
//create queries to stop and restart indexing
$FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup STOP POPULATION';
$FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup DISABLE';
$FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup ENABLE';
$FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING MANUAL';
$FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup START FULL POPULATION';
$FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING AUTO';
foreach($FTSqry as $q){
sleep(3);
$this->query($q);
}
}
return false; // no database available
}
/**
* @see DBManager::convert()
*/
public function convert(
$string,
$type,
array $additional_parameters = array(),
array $additional_parameters_oracle_only = array()
)
{
// convert the parameters array into a comma delimited string
$additional_parameters_string = '';
if (!empty($additional_parameters))
$additional_parameters_string = ','.implode(',',$additional_parameters);
switch ($type) {
case 'today': return "GETDATE()";
case 'left': return "LEFT($string".$additional_parameters_string.")";
case 'date_format':
if(!empty($additional_parameters) && in_array("'%Y-%m'", $additional_parameters))
return "CONVERT(varchar(7),". $string . ",120)";
else
return "CONVERT(varchar(10),". $string . ",120)";
case 'IFNULL': return "ISNULL($string".$additional_parameters_string.")";
case 'CONCAT': return "$string+".implode("+",$additional_parameters);
case 'text2char': return "CAST($string AS varchar(8000))";
}
return "$string";
}
/**
* @see DBManager::concat()
*/
public function concat(
$table,
array $fields
)
{
$ret = '';
foreach ( $fields as $index => $field )
if (empty($ret))
$ret = db_convert($table.".".$field,'IFNULL', array("''"));
else
$ret .= " + ' ' + ".db_convert($table.".".$field,'IFNULL', array("''"));
return empty($ret)?$ret:"LTRIM(RTRIM($ret))";
}
/**
* @see DBManager::fromConvert()
*/
public function fromConvert(
$string,
$type)
{
switch($type) {
case 'datetime': return substr($string, 0,19);
case 'date': return substr($string, 0,11);
case 'time': return substr($string, 11);
}
return $string;
}
}
| agpl-3.0 |
sivakuna-aap/superdesk | server/apps/archive/archive_test.py | 14852 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from bson import ObjectId
from superdesk import get_resource_service
from test_factory import SuperdeskTestCase
from eve.utils import date_to_str
from superdesk.utc import get_expiry_date, utcnow
from apps.archive.commands import get_overdue_scheduled_items
from apps.archive.archive import SOURCE as ARCHIVE
from superdesk.errors import SuperdeskApiError
from datetime import timedelta, datetime
from pytz import timezone
from apps.archive.common import validate_schedule, remove_media_files, \
format_dateline_to_locmmmddsrc, convert_task_attributes_to_objectId, \
is_genre, BROADCAST_GENRE
from settings import ORGANIZATION_NAME_ABBREVIATION
class RemoveSpikedContentTestCase(SuperdeskTestCase):
articles = [{'guid': 'tag:localhost:2015:69b961ab-2816-4b8a-a584-a7b402fed4f9',
'_id': '1',
'type': 'text',
'last_version': 3,
'_current_version': 4,
'body_html': 'Test body',
'urgency': 4,
'headline': 'Two students missing',
'pubstatus': 'usable',
'firstcreated': utcnow(),
'byline': 'By Alan Karben',
'ednote': 'Andrew Marwood contributed to this article',
'keywords': ['Student', 'Crime', 'Police', 'Missing'],
'subject':[{'qcode': '17004000', 'name': 'Statistics'},
{'qcode': '04001002', 'name': 'Weather'}],
'state': 'draft',
'expiry': utcnow() + timedelta(minutes=20),
'unique_name': '#1'},
{'guid': 'tag:localhost:2015:69b961ab-2816-4b8a-a974-xy4532fe33f9',
'_id': '2',
'last_version': 3,
'_current_version': 4,
'body_html': 'Test body of the second article',
'urgency': 4,
'headline': 'Another two students missing',
'pubstatus': 'usable',
'firstcreated': utcnow(),
'byline': 'By Alan Karben',
'ednote': 'Andrew Marwood contributed to this article',
'keywords': ['Student', 'Crime', 'Police', 'Missing'],
'subject':[{'qcode': '17004000', 'name': 'Statistics'},
{'qcode': '04001002', 'name': 'Weather'}],
'expiry': utcnow() + timedelta(minutes=20),
'state': 'draft',
'type': 'text',
'unique_name': '#2'},
{'guid': 'tag:localhost:2015:69b961ab-2816-4b8a-a584-a7b402fed4fa',
'_id': '3',
'_current_version': 4,
'body_html': 'Test body',
'urgency': 4,
'headline': 'Two students missing killed',
'pubstatus': 'usable',
'firstcreated': utcnow(),
'byline': 'By Alan Karben',
'ednote': 'Andrew Marwood contributed to this article killed',
'keywords': ['Student', 'Crime', 'Police', 'Missing'],
'subject':[{'qcode': '17004000', 'name': 'Statistics'},
{'qcode': '04001002', 'name': 'Weather'}],
'state': 'draft',
'expiry': utcnow() + timedelta(minutes=20),
'type': 'text',
'unique_name': '#3'},
{'guid': 'tag:localhost:2015:69b961ab-2816-4b8a-a584-a7b402fed4fc',
'_id': '4',
'_current_version': 3,
'state': 'draft',
'type': 'composite',
'groups': [{'id': 'root', 'refs': [{'idRef': 'main'}], 'role': 'grpRole:NEP'},
{
'id': 'main',
'refs': [
{
'location': 'archive',
'guid': '1',
'residRef': '1',
'type': 'text'
},
{
'location': 'archive',
'residRef': '2',
'guid': '2',
'type': 'text'
}
],
'role': 'grpRole:main'}],
'firstcreated': utcnow(),
'expiry': utcnow() + timedelta(minutes=20),
'unique_name': '#4'},
{'guid': 'tag:localhost:2015:69b961ab-4b8a-a584-2816-a7b402fed4fc',
'_id': '5',
'_current_version': 3,
'state': 'draft',
'type': 'composite',
'groups': [{'id': 'root', 'refs': [{'idRef': 'main'}, {'idRef': 'story'}], 'role': 'grpRole:NEP'},
{
'id': 'main',
'refs': [
{
'location': 'archive',
'guid': '1',
'residRef': '1',
'type': 'text'
}
],
'role': 'grpRole:main'},
{
'id': 'story',
'refs': [
{
'location': 'archive',
'guid': '4',
'residRef': '4',
'type': 'composite'
}
],
'role': 'grpRole:story'}],
'firstcreated': utcnow(),
'expiry': utcnow() + timedelta(minutes=20),
'unique_name': '#5'}]
media = {
'viewImage': {
'media': '1592730d582080f4e9fcc2fcf43aa357bda0ed19ffe314ee3248624cd4d4bc54',
'mimetype': 'image/jpeg',
'href': 'http://192.168.220.209/api/upload/abc/raw?_schema=http',
'height': 452,
'width': 640
},
'thumbnail': {
'media': '52250b4f37da50ee663fdbff057a5f064479f8a8bbd24fb8fdc06135d3f807bb',
'mimetype': 'image/jpeg',
'href': 'http://192.168.220.209/api/upload/abc/raw?_schema=http',
'height': 120,
'width': 169
},
'baseImage': {
'media': '7a608aa8f51432483918027dd06d0ef385b90702bfeba84ac4aec38ed1660b18',
'mimetype': 'image/jpeg',
'href': 'http://192.168.220.209/api/upload/abc/raw?_schema=http',
'height': 990,
'width': 1400
},
'original': {
'media': 'stub.jpeg',
'mimetype': 'image/jpeg',
'href': 'http://192.168.220.209/api/upload/stub.jpeg/raw?_schema=http',
'height': 2475,
'width': 3500
}
}
def setUp(self):
super().setUp()
def test_query_getting_expired_content(self):
self.app.data.insert(ARCHIVE, [{'expiry': get_expiry_date(-10), 'state': 'spiked'}])
self.app.data.insert(ARCHIVE, [{'expiry': get_expiry_date(0), 'state': 'spiked'}])
self.app.data.insert(ARCHIVE, [{'expiry': get_expiry_date(10), 'state': 'spiked'}])
self.app.data.insert(ARCHIVE, [{'expiry': get_expiry_date(20), 'state': 'spiked'}])
self.app.data.insert(ARCHIVE, [{'expiry': get_expiry_date(30), 'state': 'spiked'}])
self.app.data.insert(ARCHIVE, [{'expiry': None, 'state': 'spiked'}])
self.app.data.insert(ARCHIVE, [{'unique_id': 97, 'state': 'spiked'}])
now = utcnow()
expired_items = get_resource_service(ARCHIVE).get_expired_items(now)
self.assertEquals(2, expired_items.count())
def test_query_removing_media_files_keeps(self):
self.app.data.insert(ARCHIVE, [{'state': 'spiked',
'expiry': get_expiry_date(-10),
'type': 'picture',
'renditions': self.media}])
self.app.data.insert('ingest', [{'type': 'picture', 'renditions': self.media}])
self.app.data.insert('archive_versions', [{'type': 'picture', 'renditions': self.media}])
self.app.data.insert('legal_archive', [{'_id': 1, 'type': 'picture', 'renditions': self.media}])
self.app.data.insert('legal_archive_versions', [{'_id': 1, 'type': 'picture', 'renditions': self.media}])
archive_items = self.app.data.find_all('archive', None)
self.assertEqual(archive_items.count(), 1)
deleted = remove_media_files(archive_items[0])
self.assertFalse(deleted)
def test_query_getting_overdue_scheduled_content(self):
self.app.data.insert(ARCHIVE, [{'publish_schedule': get_expiry_date(-10), 'state': 'published'}])
self.app.data.insert(ARCHIVE, [{'publish_schedule': get_expiry_date(-10), 'state': 'scheduled'}])
self.app.data.insert(ARCHIVE, [{'publish_schedule': get_expiry_date(0), 'state': 'spiked'}])
self.app.data.insert(ARCHIVE, [{'publish_schedule': get_expiry_date(10), 'state': 'scheduled'}])
self.app.data.insert(ARCHIVE, [{'unique_id': 97, 'state': 'spiked'}])
now = date_to_str(utcnow())
overdueItems = get_overdue_scheduled_items(now, 'archive')
self.assertEquals(1, overdueItems.count())
class ArchiveTestCase(SuperdeskTestCase):
def setUp(self):
super().setUp()
def test_validate_schedule(self):
validate_schedule(utcnow() + timedelta(hours=2))
def test_validate_schedule_date_with_datetime_as_string_raises_superdeskApiError(self):
self.assertRaises(SuperdeskApiError, validate_schedule, "2015-04-27T10:53:48+00:00")
def test_validate_schedule_date_with_datetime_in_past_raises_superdeskApiError(self):
self.assertRaises(SuperdeskApiError, validate_schedule, utcnow() + timedelta(hours=-2))
def _get_located_and_current_utc_ts(self):
current_ts = utcnow()
located = {"dateline": "city", "city_code": "Sydney", "state": "NSW", "city": "Sydney", "state_code": "NSW",
"country_code": "AU", "tz": "Australia/Sydney", "country": "Australia"}
current_timestamp = datetime.fromtimestamp(current_ts.timestamp(), tz=timezone(located['tz']))
if current_timestamp.month == 9:
formatted_date = 'Sept {}'.format(current_timestamp.strftime('%d'))
elif 3 <= current_timestamp.month <= 7:
formatted_date = current_timestamp.strftime('%B %d')
else:
formatted_date = current_timestamp.strftime('%b %d')
return located, formatted_date, current_ts
def test_format_dateline_to_format_when_only_city_is_present(self):
located, formatted_date, current_ts = self._get_located_and_current_utc_ts()
formatted_dateline = format_dateline_to_locmmmddsrc(located, current_ts)
self.assertEqual(formatted_dateline, 'SYDNEY %s %s -' % (formatted_date, ORGANIZATION_NAME_ABBREVIATION))
def test_format_dateline_to_format_when_only_city_and_state_are_present(self):
located, formatted_date, current_ts = self._get_located_and_current_utc_ts()
located['dateline'] = "city,state"
formatted_dateline = format_dateline_to_locmmmddsrc(located, current_ts)
self.assertEqual(formatted_dateline, 'SYDNEY, NSW %s %s -' % (formatted_date, ORGANIZATION_NAME_ABBREVIATION))
def test_format_dateline_to_format_when_only_city_and_country_are_present(self):
located, formatted_date, current_ts = self._get_located_and_current_utc_ts()
located['dateline'] = "city,country"
formatted_dateline = format_dateline_to_locmmmddsrc(located, current_ts)
self.assertEqual(formatted_dateline, 'SYDNEY, AU %s %s -' % (formatted_date, ORGANIZATION_NAME_ABBREVIATION))
def test_format_dateline_to_format_when_city_state_and_country_are_present(self):
located, formatted_date, current_ts = self._get_located_and_current_utc_ts()
located['dateline'] = "city,state,country"
formatted_dateline = format_dateline_to_locmmmddsrc(located, current_ts)
self.assertEqual(formatted_dateline, 'SYDNEY, NSW, AU %s %s -' % (formatted_date,
ORGANIZATION_NAME_ABBREVIATION))
def test_if_task_attributes_converted_to_objectid(self):
doc = {
'task': {
'user': '562435231d41c835d7b5fb55',
'desk': ObjectId("562435241d41c835d7b5fb5d"),
'stage': 'test',
'last_authoring_desk': 3245,
'last_production_desk': None
}
}
convert_task_attributes_to_objectId(doc)
self.assertIsInstance(doc['task']['user'], ObjectId)
self.assertEqual(doc['task']['desk'], ObjectId("562435241d41c835d7b5fb5d"))
self.assertEqual(doc['task']['stage'], 'test')
self.assertEqual(doc['task']['last_authoring_desk'], 3245)
self.assertIsNone(doc['task']['last_production_desk'])
class ArchiveCommonTestCase(SuperdeskTestCase):
def setUp(self):
super().setUp()
def test_broadcast_content(self):
content = {
'genre': [{'name': 'Broadcast Script', 'value': 'Broadcast Script'}]
}
self.assertTrue(is_genre(content, BROADCAST_GENRE))
def test_broadcast_content_if_genre_is_none(self):
content = {
'genre': None
}
self.assertFalse(is_genre(content, BROADCAST_GENRE))
def test_broadcast_content_if_genre_is_empty_list(self):
content = {
'genre': []
}
self.assertFalse(is_genre(content, BROADCAST_GENRE))
def test_broadcast_content_if_genre_is_other_than_broadcast(self):
content = {
'genre': [{'name': 'Article', 'value': 'Article'}]
}
self.assertFalse(is_genre(content, BROADCAST_GENRE))
self.assertTrue(is_genre(content, 'Article'))
| agpl-3.0 |
arrivu/hoodemo | vendor/plugins/qti_exporter/spec_canvas/lib/qti/qti_1_2_zip_spec.rb | 8059 | require File.expand_path(File.dirname(__FILE__) + '/../../qti_helper')
if Qti.migration_executable
describe "QTI 1.2 zip with id prepender value" do
before(:all) do
@archive_file_path = File.join(BASE_FIXTURE_DIR, 'qti', 'plain_qti.zip')
unzipped_file_path = File.join(File.dirname(@archive_file_path), "qti_#{File.basename(@archive_file_path, '.zip')}", 'oi')
@dir = File.join(File.dirname(@archive_file_path), "qti_plain_qti")
@course = Course.create!(:name => 'tester')
@migration = ContentMigration.create(:context => @course)
@converter = Qti::Converter.new(:export_archive_path=>@archive_file_path, :base_download_dir=>unzipped_file_path, :id_prepender=>'prepend_test', :content_migration => @migration)
@converter.export
@course_data = @converter.course.with_indifferent_access
@course_data['all_files_export'] ||= {}
@course_data['all_files_export']['file_path'] = @course_data['all_files_zip']
@migration.migration_settings[:migration_ids_to_import] = {:copy=>{}}
@migration.migration_settings[:files_import_root_path] = @course_data[:files_import_root_path]
@course.import_from_migration(@course_data, nil, @migration)
end
after(:all) do
truncate_all_tables
@converter.delete_unzipped_archive
if File.exists?(@dir)
FileUtils::rm_rf(@dir)
end
end
it "should convert the assessments" do
@converter.course[:assessments].should == QTI_EXPORT_ASSESSMENT
@course.quizzes.count.should == 1
quiz = @course.quizzes.first
quiz.title.should == 'Quiz'
quiz.quiz_questions.count.should == 10
end
it "should convert the questions" do
@course_data[:assessment_questions][:assessment_questions].length.should == 10
@course.assessment_questions.count.should == 10
end
it "should create an assessment question bank for the quiz" do
@course.assessment_question_banks.count.should == 1
bank = @course.assessment_question_banks.first
bank.title.should == 'Quiz'
bank.assessment_questions.count.should == 10
end
it "should have file paths" do
@course_data[:overview_file_path].index("oi/overview.json").should_not be_nil
@course_data[:export_folder_path].index('spec_canvas/fixtures/qti/qti_plain_qti/oi').should_not be_nil
@course_data[:full_export_file_path].index('spec_canvas/fixtures/qti/qti_plain_qti/oi/course_export.json').should_not be_nil
end
it "should import the included files" do
@course.attachments.count.should == 4
dir = Canvas::Migration::MigratorHelper::QUIZ_FILE_DIRECTORY
@course.attachments.find_by_migration_id("prepend_test_f3e5ead7f6e1b25a46a4145100566821").full_path.should == "course files/#{dir}/#{@migration.id}/exam1/my_files/org1/images/image.png"
@course.attachments.find_by_migration_id("prepend_test_c16566de1661613ef9e5517ec69c25a1").full_path.should == "course files/#{dir}/#{@migration.id}/contact info.png"
@course.attachments.find_by_migration_id("prepend_test_4d348a246af616c7d9a7d403367c1a30").full_path.should == "course files/#{dir}/#{@migration.id}/exam1/my_files/org0/images/image.png"
@course.attachments.find_by_migration_id("prepend_test_d2b5ca33bd970f64a6301fa75ae2eb22").full_path.should == "course files/#{dir}/#{@migration.id}/image.png"
end
it "should use expected file links in questions" do
aq = @course.assessment_questions.find_by_migration_id("prepend_test_QUE_1003")
c_att = @course.attachments.find_by_migration_id("prepend_test_4d348a246af616c7d9a7d403367c1a30")
att = aq.attachments.find_by_migration_id(CC::CCHelper.create_key(c_att))
aq.question_data["question_text"].should =~ %r{files/#{att.id}/download}
aq = @course.assessment_questions.find_by_migration_id("prepend_test_QUE_1007")
c_att = @course.attachments.find_by_migration_id("prepend_test_f3e5ead7f6e1b25a46a4145100566821")
att = aq.attachments.find_by_migration_id(CC::CCHelper.create_key(c_att))
aq.question_data["question_text"].should =~ %r{files/#{att.id}/download}
aq = @course.assessment_questions.find_by_migration_id("prepend_test_QUE_1014")
c_att = @course.attachments.find_by_migration_id("prepend_test_d2b5ca33bd970f64a6301fa75ae2eb22")
att = aq.attachments.find_by_migration_id(CC::CCHelper.create_key(c_att))
aq.question_data["question_text"].should =~ %r{files/#{att.id}/download}
aq = @course.assessment_questions.find_by_migration_id("prepend_test_QUE_1053")
c_att = @course.attachments.find_by_migration_id("prepend_test_c16566de1661613ef9e5517ec69c25a1")
att = aq.attachments.find_by_migration_id(CC::CCHelper.create_key(c_att))
aq.question_data["question_text"].should =~ %r{files/#{att.id}/download}
end
it "should hide the quiz directory" do
folder = @course.folders.find_by_name(Canvas::Migration::MigratorHelper::QUIZ_FILE_DIRECTORY)
folder.hidden?.should be_true
end
it "should use new attachments for imports with same file names" do
# run a second migration and check that there are different attachments on the questions
migration = ContentMigration.create(:context => @course)
converter = Qti::Converter.new(:export_archive_path=>@archive_file_path, :id_prepender=>'test2', :content_migration => migration)
converter.export
course_data = converter.course.with_indifferent_access
course_data['all_files_export'] ||= {}
course_data['all_files_export']['file_path'] = course_data['all_files_zip']
migration.migration_settings[:migration_ids_to_import] = {:copy=>{}}
migration.migration_settings[:files_import_root_path] = course_data[:files_import_root_path]
@course.import_from_migration(course_data, nil, migration)
# Check the first import
aq = @course.assessment_questions.find_by_migration_id("prepend_test_QUE_1003")
c_att = @course.attachments.find_by_migration_id("prepend_test_4d348a246af616c7d9a7d403367c1a30")
att = aq.attachments.find_by_migration_id(CC::CCHelper.create_key(c_att))
aq.question_data["question_text"].should =~ %r{files/#{att.id}/download}
# check the second import
aq = @course.assessment_questions.find_by_migration_id("test2_QUE_1003")
c_att = @course.attachments.find_by_migration_id("test2_4d348a246af616c7d9a7d403367c1a30")
att = aq.attachments.find_by_migration_id(CC::CCHelper.create_key(c_att))
aq.question_data["question_text"].should =~ %r{files/#{att.id}/download}
end
end
QTI_EXPORT_ASSESSMENT = {
:assessments=>
[{:migration_id=>"prepend_test_A1001",
:questions=>
[{:migration_id=>"prepend_test_QUE_1003", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1007", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1014", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1018", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1022", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1031", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1037", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1043", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1049", :question_type=>"question_reference"},
{:migration_id=>"prepend_test_QUE_1053", :question_type=>"question_reference"}],
:question_count=>10,
:quiz_type=>nil,
:quiz_name=>"Quiz",
:title=>"Quiz"}]}
end
| agpl-3.0 |
jondo/paperpile | plack/perl5/win32/lib/CPANPLUS/Internals/Source.pm | 42163 | package CPANPLUS::Internals::Source;
use strict;
use CPANPLUS::Error;
use CPANPLUS::Module;
use CPANPLUS::Module::Fake;
use CPANPLUS::Module::Author;
use CPANPLUS::Internals::Constants;
use File::Fetch;
use Archive::Extract;
use IPC::Cmd qw[can_run];
use File::Temp qw[tempdir];
use File::Basename qw[dirname];
use Params::Check qw[check];
use Module::Load::Conditional qw[can_load];
use Locale::Maketext::Simple Class => 'CPANPLUS', Style => 'gettext';
$Params::Check::VERBOSE = 1;
### list of methods the parent class must implement
{ for my $sub ( qw[_init_trees _finalize_trees
_standard_trees_completed _custom_trees_completed
_add_module_object _add_author_object _save_state
]
) {
no strict 'refs';
*$sub = sub {
my $self = shift;
my $class = ref $self || $self;
require Carp;
Carp::croak( loc( "Class %1 must implement method '%2'",
$class, $sub ) );
}
}
}
{
my $recurse; # flag to prevent recursive calls to *_tree functions
### lazy loading of module tree
sub _module_tree {
my $self = $_[0];
unless ($self->_mtree or $recurse++ > 0) {
my $uptodate = $self->_check_trees( @_[1..$#_] );
$self->_build_trees(uptodate => $uptodate);
}
$recurse--;
return $self->_mtree;
}
### lazy loading of author tree
sub _author_tree {
my $self = $_[0];
unless ($self->_atree or $recurse++ > 0) {
my $uptodate = $self->_check_trees( @_[1..$#_] );
$self->_build_trees(uptodate => $uptodate);
}
$recurse--;
return $self->_atree;
}
}
=pod
=head1 NAME
CPANPLUS::Internals::Source
=head1 SYNOPSIS
### lazy load author/module trees ###
$cb->_author_tree;
$cb->_module_tree;
=head1 DESCRIPTION
CPANPLUS::Internals::Source controls the updating of source files and
the parsing of them into usable module/author trees to be used by
C<CPANPLUS>.
Functions exist to check if source files are still C<good to use> as
well as update them, and then parse them.
The flow looks like this:
$cb->_author_tree || $cb->_module_tree
$cb->_check_trees
$cb->__check_uptodate
$cb->_update_source
$cb->__update_custom_module_sources
$cb->__update_custom_module_source
$cb->_build_trees
### engine methods
{ $cb->_init_trees;
$cb->_standard_trees_completed
$cb->_custom_trees_completed
}
$cb->__create_author_tree
### engine methods
{ $cb->_add_author_object }
$cb->__create_module_tree
$cb->__create_dslip_tree
### engine methods
{ $cb->_add_module_object }
$cb->__create_custom_module_entries
$cb->_dslip_defs
=head1 METHODS
=cut
=pod
=head2 $cb->_build_trees( uptodate => BOOL, [use_stored => BOOL, path => $path, verbose => BOOL] )
This method rebuilds the author- and module-trees from source.
It takes the following arguments:
=over 4
=item uptodate
Indicates whether any on disk caches are still ok to use.
=item path
The absolute path to the directory holding the source files.
=item verbose
A boolean flag indicating whether or not to be verbose.
=item use_stored
A boolean flag indicating whether or not it is ok to use previously
stored trees. Defaults to true.
=back
Returns a boolean indicating success.
=cut
### (re)build the trees ###
sub _build_trees {
my ($self, %hash) = @_;
my $conf = $self->configure_object;
my($path,$uptodate,$use_stored,$verbose);
my $tmpl = {
path => { default => $conf->get_conf('base'), store => \$path },
verbose => { default => $conf->get_conf('verbose'), store => \$verbose },
uptodate => { required => 1, store => \$uptodate },
use_stored => { default => 1, store => \$use_stored },
};
my $args = check( $tmpl, \%hash ) or return;
$self->_init_trees(
path => $path,
uptodate => $uptodate,
verbose => $verbose,
use_stored => $use_stored,
) or do {
error( loc("Could not initialize trees" ) );
return;
};
### return if we weren't able to build the trees ###
return unless $self->_mtree && $self->_atree;
### did we get everything from a stored state? if not,
### process them now.
if( not $self->_standard_trees_completed ) {
### first, prep the author tree
$self->__create_author_tree(
uptodate => $uptodate,
path => $path,
verbose => $verbose,
) or return;
### and now the module tree
$self->_create_mod_tree(
uptodate => $uptodate,
path => $path,
verbose => $verbose,
) or return;
}
### XXX unpleasant hack. since custom sources uses ->parse_module, we
### already have a special module object with extra meta data. that
### doesn't gelwell with the sqlite storage engine. So, we check 'normal'
### trees from seperate trees, so the engine can treat them differently.
### Effectively this means that with the SQLite engine, for now, custom
### sources are continuously reparsed =/ -kane
if( not $self->_custom_trees_completed ) {
### update them if the other sources are also deemed out of date
if( $conf->get_conf('enable_custom_sources') ) {
$self->__update_custom_module_sources( verbose => $verbose )
or error(loc("Could not update custom module sources"));
}
### add custom sources here if enabled
if( $conf->get_conf('enable_custom_sources') ) {
$self->__create_custom_module_entries( verbose => $verbose )
or error(loc("Could not create custom module entries"));
}
}
### give the source engine a chance to wrap up creation
$self->_finalize_trees(
path => $path,
uptodate => $uptodate,
verbose => $verbose,
use_stored => $use_stored,
) or do {
error(loc( "Could not finalize trees" ));
return;
};
### still necessary? can only run one instance now ###
### will probably stay that way --kane
# my $id = $self->_store_id( $self );
#
# unless ( $id == $self->_id ) {
# error( loc("IDs do not match: %1 != %2. Storage failed!", $id, $self->_id) );
# }
return 1;
}
=pod
=head2 $cb->_check_trees( [update_source => BOOL, path => PATH, verbose => BOOL] )
Retrieve source files and return a boolean indicating whether or not
the source files are up to date.
Takes several arguments:
=over 4
=item update_source
A flag to force re-fetching of the source files, even
if they are still up to date.
=item path
The absolute path to the directory holding the source files.
=item verbose
A boolean flag indicating whether or not to be verbose.
=back
Will get information from the config file by default.
=cut
### retrieve source files, and returns a boolean indicating if it's up to date
sub _check_trees {
my ($self, %hash) = @_;
my $conf = $self->configure_object;
my $update_source;
my $verbose;
my $path;
my $tmpl = {
path => { default => $conf->get_conf('base'),
store => \$path
},
verbose => { default => $conf->get_conf('verbose'),
store => \$verbose
},
update_source => { default => 0, store => \$update_source },
};
my $args = check( $tmpl, \%hash ) or return;
### if the user never wants to update their source without explicitly
### telling us, shortcircuit here
return 1 if $conf->get_conf('no_update') && !$update_source;
### a check to see if our source files are still up to date ###
msg( loc("Checking if source files are up to date"), $verbose );
my $uptodate = 1; # default return value
for my $name (qw[auth dslip mod]) {
for my $file ( $conf->_get_source( $name ) ) {
$self->__check_uptodate(
file => File::Spec->catfile( $path, $file ),
name => $name,
update_source => $update_source,
verbose => $verbose,
) or $uptodate = 0;
}
}
### if we're explicitly asked to update the sources, or if the
### standard source files are out of date, update the custom sources
### as well
### RT #47820: Don't try to update custom sources if they are disabled
### in the configuration.
$self->__update_custom_module_sources( verbose => $verbose )
if $conf->get_conf('enable_custom_sources') and ( $update_source or !$uptodate );
return $uptodate;
}
=pod
=head2 $cb->__check_uptodate( file => $file, name => $name, [update_source => BOOL, verbose => BOOL] )
C<__check_uptodate> checks if a given source file is still up-to-date
and if not, or when C<update_source> is true, will re-fetch the source
file.
Takes the following arguments:
=over 4
=item file
The source file to check.
=item name
The internal shortcut name for the source file (used for config
lookups).
=item update_source
Flag to force updating of sourcefiles regardless.
=item verbose
Boolean to indicate whether to be verbose or not.
=back
Returns a boolean value indicating whether the current files are up
to date or not.
=cut
### this method checks whether or not the source files we are using are still up to date
sub __check_uptodate {
my $self = shift;
my %hash = @_;
my $conf = $self->configure_object;
my $tmpl = {
file => { required => 1 },
name => { required => 1 },
update_source => { default => 0 },
verbose => { default => $conf->get_conf('verbose') },
};
my $args = check( $tmpl, \%hash ) or return;
my $flag;
unless ( -e $args->{'file'} && (
( stat $args->{'file'} )[9]
+ $conf->_get_source('update') )
> time ) {
$flag = 1;
}
if ( $flag or $args->{'update_source'} ) {
if ( $self->_update_source( name => $args->{'name'} ) ) {
return 0; # return 0 so 'uptodate' will be set to 0, meaning no
# use of previously stored hashrefs!
} else {
msg( loc("Unable to update source, attempting to get away with using old source file!"), $args->{verbose} );
return 1;
}
} else {
return 1;
}
}
=pod
=head2 $cb->_update_source( name => $name, [path => $path, verbose => BOOL] )
This method does the actual fetching of source files.
It takes the following arguments:
=over 4
=item name
The internal shortcut name for the source file (used for config
lookups).
=item path
The full path where to write the files.
=item verbose
Boolean to indicate whether to be verbose or not.
=back
Returns a boolean to indicate success.
=cut
### this sub fetches new source files ###
sub _update_source {
my $self = shift;
my %hash = @_;
my $conf = $self->configure_object;
my $verbose;
my $tmpl = {
name => { required => 1 },
path => { default => $conf->get_conf('base') },
verbose => { default => $conf->get_conf('verbose'), store => \$verbose },
};
my $args = check( $tmpl, \%hash ) or return;
my $path = $args->{path};
{ ### this could use a clean up - Kane
### no worries about the / -> we get it from the _ftp configuration, so
### it's not platform dependant. -kane
my ($dir, $file) = $conf->_get_mirror( $args->{'name'} ) =~ m|(.+/)(.+)$|sg;
msg( loc("Updating source file '%1'", $file), $verbose );
my $fake = CPANPLUS::Module::Fake->new(
module => $args->{'name'},
path => $dir,
package => $file,
_id => $self->_id,
);
### can't use $fake->fetch here, since ->parent won't work --
### the sources haven't been saved yet
my $rv = $self->_fetch(
module => $fake,
fetchdir => $path,
force => 1,
);
unless ($rv) {
error( loc("Couldn't fetch '%1'", $file) );
return;
}
$self->_update_timestamp( file => File::Spec->catfile($path, $file) );
}
return 1;
}
=pod
=head2 $cb->__create_author_tree([path => $path, uptodate => BOOL, verbose => BOOL])
This method opens a source files and parses its contents into a
searchable author-tree or restores a file-cached version of a
previous parse, if the sources are uptodate and the file-cache exists.
It takes the following arguments:
=over 4
=item uptodate
A flag indicating whether the file-cache is uptodate or not.
=item path
The absolute path to the directory holding the source files.
=item verbose
A boolean flag indicating whether or not to be verbose.
=back
Will get information from the config file by default.
Returns a tree on success, false on failure.
=cut
sub __create_author_tree {
my $self = shift;
my %hash = @_;
my $conf = $self->configure_object;
my $tmpl = {
path => { default => $conf->get_conf('base') },
verbose => { default => $conf->get_conf('verbose') },
uptodate => { default => 0 },
};
my $args = check( $tmpl, \%hash ) or return;
my $file = File::Spec->catfile(
$args->{path},
$conf->_get_source('auth')
);
msg(loc("Rebuilding author tree, this might take a while"),
$args->{verbose});
### extract the file ###
my $ae = Archive::Extract->new( archive => $file ) or return;
my $out = STRIP_GZ_SUFFIX->($file);
### make sure to set the PREFER_BIN flag if desired ###
{ local $Archive::Extract::PREFER_BIN = $conf->get_conf('prefer_bin');
$ae->extract( to => $out ) or return;
}
my $cont = $self->_get_file_contents( file => $out ) or return;
### don't need it anymore ###
unlink $out;
for ( split /\n/, $cont ) {
my($id, $name, $email) = m/^alias \s+
(\S+) \s+
"\s* ([^\"\<]+?) \s* <(.+)> \s*"
/x;
$self->_add_author_object(
author => $name, #authors name
email => $email, #authors email address
cpanid => $id, #authors CPAN ID
) or error( loc("Could not add author '%1'", $name ) );
}
return $self->_atree;
} #__create_author_tree
=pod
=head2 $cb->_create_mod_tree([path => $path, uptodate => BOOL, verbose => BOOL])
This method opens a source files and parses its contents into a
searchable module-tree or restores a file-cached version of a
previous parse, if the sources are uptodate and the file-cache exists.
It takes the following arguments:
=over 4
=item uptodate
A flag indicating whether the file-cache is up-to-date or not.
=item path
The absolute path to the directory holding the source files.
=item verbose
A boolean flag indicating whether or not to be verbose.
=back
Will get information from the config file by default.
Returns a tree on success, false on failure.
=cut
### this builds a hash reference with the structure of the cpan module tree ###
sub _create_mod_tree {
my $self = shift;
my %hash = @_;
my $conf = $self->configure_object;
my $tmpl = {
path => { default => $conf->get_conf('base') },
verbose => { default => $conf->get_conf('verbose') },
uptodate => { default => 0 },
};
my $args = check( $tmpl, \%hash ) or return undef;
my $file = File::Spec->catfile($args->{path}, $conf->_get_source('mod'));
msg(loc("Rebuilding module tree, this might take a while"),
$args->{verbose});
my $dslip_tree = $self->__create_dslip_tree( %$args );
### extract the file ###
my $ae = Archive::Extract->new( archive => $file ) or return;
my $out = STRIP_GZ_SUFFIX->($file);
### make sure to set the PREFER_BIN flag if desired ###
{ local $Archive::Extract::PREFER_BIN = $conf->get_conf('prefer_bin');
$ae->extract( to => $out ) or return;
}
my $content = $self->_get_file_contents( file => $out ) or return;
my $lines = $content =~ tr/\n/\n/;
### don't need it anymore ###
unlink $out;
my($past_header, $count);
for ( split /\n/, $content ) {
### quick hack to read past the header of the file ###
### this is still rather evil... fix some time - Kane
if( m|^\s*$| ) {
unless( $count ) {
error(loc("Could not determine line count from %1", $file));
return;
}
$past_header = 1;
}
### we're still in the header -- find the amount of lines we expect
unless( $past_header ) {
### if the line count doesn't match what we expect, bail out
### this should address: #45644: detect broken index
$count = $1 if /^Line-Count:\s+(\d+)/;
if( $count ) {
if( $lines < $count ) {
error(loc("Expected to read at least %1 lines, but %2 ".
"contains only %3 lines!",
$count, $file, $lines ));
return;
}
}
### still in the header, keep moving
next;
}
### skip empty lines ###
next unless /\S/;
chomp;
my @data = split /\s+/;
### filter out the author and filename as well ###
### authors can apparently have digits in their names,
### and dirs can have dots... blah!
my ($author, $package) = $data[2] =~
m| (?:[A-Z\d-]/)?
(?:[A-Z\d-]{2}/)?
([A-Z\d-]+) (?:/[\S]+)?/
([^/]+)$
|xsg;
### remove file name from the path
$data[2] =~ s|/[^/]+$||;
my $aobj = $self->author_tree($author);
unless( $aobj ) {
error( loc( "No such author '%1' -- can't make module object " .
"'%2' that is supposed to belong to this author",
$author, $data[0] ) );
next;
}
### adding the dslip info
### probably can use some optimization
my $dslip;
for my $item ( qw[ statd stats statl stati statp ] ) {
### checking if there's an entry in the dslip info before
### catting it on. appeasing warnings this way
$dslip .= $dslip_tree->{ $data[0] }->{$item}
? $dslip_tree->{ $data[0] }->{$item}
: ' ';
}
### XXX this could be sped up if we used author names, not author
### objects in creation, and then look them up in the author tree
### when needed. This will need a fix to all the places that create
### fake author/module objects as well.
### callback to store the individual object
$self->_add_module_object(
module => $data[0], # full module name
version => ($data[1] eq 'undef' # version number
? '0.0'
: $data[1]),
path => File::Spec::Unix->catfile(
$conf->_get_mirror('base'),
$data[2],
), # extended path on the cpan mirror,
# like /A/AB/ABIGAIL
comment => $data[3], # comment on the module
author => $aobj,
package => $package, # package name, like
# 'foo-bar-baz-1.03.tar.gz'
description => $dslip_tree->{ $data[0] }->{'description'},
dslip => $dslip,
mtime => '',
) or error( loc( "Could not add module '%1'", $data[0] ) );
} #for
return $self->_mtree;
} #_create_mod_tree
=pod
=head2 $cb->__create_dslip_tree([path => $path, uptodate => BOOL, verbose => BOOL])
This method opens a source files and parses its contents into a
searchable dslip-tree or restores a file-cached version of a
previous parse, if the sources are uptodate and the file-cache exists.
It takes the following arguments:
=over 4
=item uptodate
A flag indicating whether the file-cache is uptodate or not.
=item path
The absolute path to the directory holding the source files.
=item verbose
A boolean flag indicating whether or not to be verbose.
=back
Will get information from the config file by default.
Returns a tree on success, false on failure.
=cut
sub __create_dslip_tree {
my $self = shift;
my %hash = @_;
my $conf = $self->configure_object;
my $tmpl = {
path => { default => $conf->get_conf('base') },
verbose => { default => $conf->get_conf('verbose') },
uptodate => { default => 0 },
};
my $args = check( $tmpl, \%hash ) or return;
### get the file name of the source ###
my $file = File::Spec->catfile($args->{path}, $conf->_get_source('dslip'));
### extract the file ###
my $ae = Archive::Extract->new( archive => $file ) or return;
my $out = STRIP_GZ_SUFFIX->($file);
### make sure to set the PREFER_BIN flag if desired ###
{ local $Archive::Extract::PREFER_BIN = $conf->get_conf('prefer_bin');
$ae->extract( to => $out ) or return;
}
my $in = $self->_get_file_contents( file => $out ) or return;
### don't need it anymore ###
unlink $out;
### get rid of the comments and the code ###
### need a smarter parser, some people have this in their dslip info:
# [
# 'Statistics::LTU',
# 'R',
# 'd',
# 'p',
# 'O',
# '?',
# 'Implements Linear Threshold Units',
# ...skipping...
# "\x{c4}dd \x{fc}ml\x{e4}\x{fc}ts t\x{f6} \x{eb}v\x{eb}r\x{ff}th\x{ef}ng!",
# 'BENNIE',
# '11'
# ],
### also, older versions say:
### $cols = [....]
### and newer versions say:
### $CPANPLUS::Modulelist::cols = [...]
### split '$cols' and '$data' into 2 variables ###
### use this regex to make sure dslips with ';' in them don't cause
### parser errors
my ($ds_one, $ds_two) = ($in =~ m|.+}\s+
(\$(?:CPAN::Modulelist::)?cols.*?)
(\$(?:CPAN::Modulelist::)?data.*)
|sx);
### eval them into existence ###
### still not too fond of this solution - kane ###
my ($cols, $data);
{ #local $@; can't use this, it's buggy -kane
$cols = eval $ds_one;
error( loc("Error in eval of dslip source files: %1", $@) ) if $@;
$data = eval $ds_two;
error( loc("Error in eval of dslip source files: %1", $@) ) if $@;
}
my $tree = {};
my $primary = "modid";
### this comes from CPAN::Modulelist
### which is in 03modlist.data.gz
for (@$data){
my %hash;
@hash{@$cols} = @$_;
$tree->{$hash{$primary}} = \%hash;
}
return $tree;
} #__create_dslip_tree
=pod
=head2 $cb->_dslip_defs ()
This function returns the definition structure (ARRAYREF) of the
dslip tree.
=cut
### these are the definitions used for dslip info
### they shouldn't change over time.. so hardcoding them doesn't appear to
### be a problem. if it is, we need to parse 03modlist.data better to filter
### all this out.
### right now, this is just used to look up dslip info from a module
sub _dslip_defs {
my $self = shift;
my $aref = [
# D
[ q|Development Stage|, {
i => loc('Idea, listed to gain consensus or as a placeholder'),
c => loc('under construction but pre-alpha (not yet released)'),
a => loc('Alpha testing'),
b => loc('Beta testing'),
R => loc('Released'),
M => loc('Mature (no rigorous definition)'),
S => loc('Standard, supplied with Perl 5'),
}],
# S
[ q|Support Level|, {
m => loc('Mailing-list'),
d => loc('Developer'),
u => loc('Usenet newsgroup comp.lang.perl.modules'),
n => loc('None known, try comp.lang.perl.modules'),
a => loc('Abandoned; volunteers welcome to take over maintainance'),
}],
# L
[ q|Language Used|, {
p => loc('Perl-only, no compiler needed, should be platform independent'),
c => loc('C and perl, a C compiler will be needed'),
h => loc('Hybrid, written in perl with optional C code, no compiler needed'),
'+' => loc('C++ and perl, a C++ compiler will be needed'),
o => loc('perl and another language other than C or C++'),
}],
# I
[ q|Interface Style|, {
f => loc('plain Functions, no references used'),
h => loc('hybrid, object and function interfaces available'),
n => loc('no interface at all (huh?)'),
r => loc('some use of unblessed References or ties'),
O => loc('Object oriented using blessed references and/or inheritance'),
}],
# P
[ q|Public License|, {
p => loc('Standard-Perl: user may choose between GPL and Artistic'),
g => loc('GPL: GNU General Public License'),
l => loc('LGPL: "GNU Lesser General Public License" (previously known as "GNU Library General Public License")'),
b => loc('BSD: The BSD License'),
a => loc('Artistic license alone'),
o => loc('other (but distribution allowed without restrictions)'),
}],
];
return $aref;
}
=head2 $file = $cb->_add_custom_module_source( uri => URI, [verbose => BOOL] );
Adds a custom source index and updates it based on the provided URI.
Returns the full path to the index file on success or false on failure.
=cut
sub _add_custom_module_source {
my $self = shift;
my $conf = $self->configure_object;
my %hash = @_;
my($verbose,$uri);
my $tmpl = {
verbose => { default => $conf->get_conf('verbose'),
store => \$verbose },
uri => { required => 1, store => \$uri }
};
check( $tmpl, \%hash ) or return;
### what index file should we use on disk?
my $index = $self->__custom_module_source_index_file( uri => $uri );
### already have it.
if( IS_FILE->( $index ) ) {
msg(loc("Source '%1' already added", $uri));
return 1;
}
### do we need to create the targe dir?
{ my $dir = dirname( $index );
unless( IS_DIR->( $dir ) ) {
$self->_mkdir( dir => $dir ) or return
}
}
### write the file
my $fh = OPEN_FILE->( $index => '>' ) or do {
error(loc("Could not open index file for '%1'", $uri));
return;
};
### basically we 'touched' it. Check the return value, may be
### important on win32 and similar OS, where there's file length
### limits
close $fh or do {
error(loc("Could not write index file to disk for '%1'", $uri));
return;
};
$self->__update_custom_module_source(
remote => $uri,
local => $index,
verbose => $verbose,
) or do {
### we faild to update it, we probably have an empty
### possibly silly filename on disk now -- remove it
1 while unlink $index;
return;
};
return $index;
}
=head2 $index = $cb->__custom_module_source_index_file( uri => $uri );
Returns the full path to the encoded index file for C<$uri>, as used by
all C<custom module source> routines.
=cut
sub __custom_module_source_index_file {
my $self = shift;
my $conf = $self->configure_object;
my %hash = @_;
my($verbose,$uri);
my $tmpl = {
uri => { required => 1, store => \$uri }
};
check( $tmpl, \%hash ) or return;
my $index = File::Spec->catfile(
$conf->get_conf('base'),
$conf->_get_build('custom_sources'),
$self->_uri_encode( uri => $uri ),
);
return $index;
}
=head2 $file = $cb->_remove_custom_module_source( uri => URI, [verbose => BOOL] );
Removes a custom index file based on the URI provided.
Returns the full path to the index file on success or false on failure.
=cut
sub _remove_custom_module_source {
my $self = shift;
my $conf = $self->configure_object;
my %hash = @_;
my($verbose,$uri);
my $tmpl = {
verbose => { default => $conf->get_conf('verbose'),
store => \$verbose },
uri => { required => 1, store => \$uri }
};
check( $tmpl, \%hash ) or return;
### use uri => local, instead of the other way around
my %files = reverse $self->__list_custom_module_sources;
### On VMS the case of key to %files can be either exact or lower case
### XXX abstract this lookup out? --kane
my $file = $files{ $uri };
$file = $files{ lc $uri } if !defined($file) && ON_VMS;
unless (defined $file) {
error(loc("No such custom source '%1'", $uri));
return;
};
1 while unlink $file;
if( IS_FILE->( $file ) ) {
error(loc("Could not remove index file '%1' for custom source '%2'",
$file, $uri));
return;
}
msg(loc("Successfully removed index file for '%1'", $uri), $verbose);
return $file;
}
=head2 %files = $cb->__list_custom_module_sources
This method scans the 'custom-sources' directory in your base directory
for additional sources to include in your module tree.
Returns a list of key value pairs as follows:
/full/path/to/source/file%3Fencoded => http://decoded/mirror/path
=cut
sub __list_custom_module_sources {
my $self = shift;
my $conf = $self->configure_object;
my($verbose);
my $tmpl = {
verbose => { default => $conf->get_conf('verbose'),
store => \$verbose },
};
my $dir = File::Spec->catdir(
$conf->get_conf('base'),
$conf->_get_build('custom_sources'),
);
unless( IS_DIR->( $dir ) ) {
msg(loc("No '%1' dir, skipping custom sources", $dir), $verbose);
return;
}
### unencode the files
### skip ones starting with # though
my %files = map {
my $org = $_;
my $dec = $self->_uri_decode( uri => $_ );
File::Spec->catfile( $dir, $org ) => $dec
} grep { $_ !~ /^#/ } READ_DIR->( $dir );
return %files;
}
=head2 $bool = $cb->__update_custom_module_sources( [verbose => BOOL] );
Attempts to update all the index files to your custom module sources.
If the index is missing, and it's a C<file://> uri, it will generate
a new local index for you.
Return true on success, false on failure.
=cut
sub __update_custom_module_sources {
my $self = shift;
my $conf = $self->configure_object;
my %hash = @_;
my $verbose;
my $tmpl = {
verbose => { default => $conf->get_conf('verbose'),
store => \$verbose }
};
check( $tmpl, \%hash ) or return;
my %files = $self->__list_custom_module_sources;
### uptodate check has been done a few levels up.
my $fail;
while( my($local,$remote) = each %files ) {
$self->__update_custom_module_source(
remote => $remote,
local => $local,
verbose => $verbose,
) or ( $fail++, next );
}
error(loc("Failed updating one or more remote sources files")) if $fail;
return if $fail;
return 1;
}
=head2 $ok = $cb->__update_custom_module_source
Attempts to update all the index files to your custom module sources.
If the index is missing, and it's a C<file://> uri, it will generate
a new local index for you.
Return true on success, false on failure.
=cut
sub __update_custom_module_source {
my $self = shift;
my $conf = $self->configure_object;
my %hash = @_;
my($verbose,$local,$remote);
my $tmpl = {
verbose => { default => $conf->get_conf('verbose'),
store => \$verbose },
local => { store => \$local, allow => FILE_EXISTS },
remote => { required => 1, store => \$remote },
};
check( $tmpl, \%hash ) or return;
msg( loc("Updating sources from '%1'", $remote), $verbose);
### if you didn't provide a local file, we'll look in your custom
### dir to find the local encoded version for you
$local ||= do {
### find all files we know of
my %files = reverse $self->__list_custom_module_sources or do {
error(loc("No custom modules sources defined -- need '%1' argument",
'local'));
return;
};
### On VMS the case of key to %files can be either exact or lower case
### XXX abstract this lookup out? --kane
my $file = $files{ $remote };
$file = $files{ lc $remote } if !defined ($file) && ON_VMS;
### return the local file we're supposed to use
$file or do {
error(loc("Remote source '%1' unknown -- needs '%2' argument",
$remote, 'local'));
return;
};
};
my $uri = join '/', $remote, $conf->_get_source('custom_index');
my $ff = File::Fetch->new( uri => $uri );
### tempdir doesn't clean up by default, as opposed to tempfile()
### so add it explicitly.
my $dir = tempdir( CLEANUP => 1 );
my $res = do { local $File::Fetch::WARN = 0;
local $File::Fetch::WARN = 0;
$ff->fetch( to => $dir );
};
### couldn't get the file
unless( $res ) {
### it's not a local scheme, so can't auto index
unless( $ff->scheme eq 'file' ) {
error(loc("Could not update sources from '%1': %2",
$remote, $ff->error ));
return;
### it's a local uri, we can index it ourselves
} else {
msg(loc("No index file found at '%1', generating one",
$ff->uri), $verbose );
### ON VMS, if you are working with a UNIX file specification,
### you need currently use the UNIX variants of the File::Spec.
my $ff_path = do {
my $file_class = 'File::Spec';
$file_class .= '::Unix' if ON_VMS;
$file_class->catdir( File::Spec::Unix->splitdir( $ff->path ) );
};
$self->__write_custom_module_index(
path => $ff_path,
to => $local,
verbose => $verbose,
) or return;
### XXX don't write that here, __write_custom_module_index
### already prints this out
#msg(loc("Index file written to '%1'", $to), $verbose);
}
### copy it to the real spot and update its timestamp
} else {
$self->_move( file => $res, to => $local ) or return;
$self->_update_timestamp( file => $local );
msg(loc("Index file saved to '%1'", $local), $verbose);
}
return $local;
}
=head2 $bool = $cb->__write_custom_module_index( path => /path/to/packages, [to => /path/to/index/file, verbose => BOOL] )
Scans the C<path> you provided for packages and writes an index with all
the available packages to C<$path/packages.txt>. If you'd like the index
to be written to a different file, provide the C<to> argument.
Returns true on success and false on failure.
=cut
sub __write_custom_module_index {
my $self = shift;
my $conf = $self->configure_object;
my %hash = @_;
my ($verbose, $path, $to);
my $tmpl = {
verbose => { default => $conf->get_conf('verbose'),
store => \$verbose },
path => { required => 1, allow => DIR_EXISTS, store => \$path },
to => { store => \$to },
};
check( $tmpl, \%hash ) or return;
### no explicit to? then we'll use our default
$to ||= File::Spec->catfile( $path, $conf->_get_source('custom_index') );
my @files;
require File::Find;
File::Find::find( sub {
### let's see if A::E can even parse it
my $ae = do {
local $Archive::Extract::WARN = 0;
local $Archive::Extract::WARN = 0;
Archive::Extract->new( archive => $File::Find::name )
} or return;
### it's a type A::E recognize, so we can add it
$ae->type or return;
### neither $_ nor $File::Find::name have the chunk of the path in
### it starting $path -- it's either only the filename, or the full
### path, so we have to strip it ourselves
### make sure to remove the leading slash as well.
my $copy = $File::Find::name;
my $re = quotemeta($path);
$copy =~ s|^$re[\\/]?||i;
push @files, $copy;
}, $path );
### does the dir exist? if not, create it.
{ my $dir = dirname( $to );
unless( IS_DIR->( $dir ) ) {
$self->_mkdir( dir => $dir ) or return
}
}
### create the index file
my $fh = OPEN_FILE->( $to => '>' ) or return;
print $fh "$_\n" for @files;
close $fh;
msg(loc("Successfully written index file to '%1'", $to), $verbose);
return $to;
}
=head2 $bool = $cb->__create_custom_module_entries( [verbose => BOOL] )
Creates entries in the module tree based upon the files as returned
by C<__list_custom_module_sources>.
Returns true on success, false on failure.
=cut
### use $auth_obj as a persistant version, so we don't have to recreate
### modules all the time
{ my $auth_obj;
sub __create_custom_module_entries {
my $self = shift;
my $conf = $self->configure_object;
my %hash = @_;
my $verbose;
my $tmpl = {
verbose => { default => $conf->get_conf('verbose'), store => \$verbose },
};
check( $tmpl, \%hash ) or return undef;
my %files = $self->__list_custom_module_sources;
while( my($file,$name) = each %files ) {
msg(loc("Adding packages from custom source '%1'", $name), $verbose);
my $fh = OPEN_FILE->( $file ) or next;
while( local $_ = <$fh> ) {
chomp;
next if /^#/;
next unless /\S+/;
### join on / -- it's a URI after all!
my $parse = join '/', $name, $_;
### try to make a module object out of it
my $mod = $self->parse_module( module => $parse ) or (
error(loc("Could not parse '%1'", $_)),
next
);
### mark this object with a custom author
$auth_obj ||= do {
my $id = CUSTOM_AUTHOR_ID;
### if the object is being created for the first time,
### make sure there's an entry in the author tree as
### well, so we can search on the CPAN ID
$self->author_tree->{ $id } =
CPANPLUS::Module::Author::Fake->new( cpanid => $id );
};
$mod->author( $auth_obj );
### and now add it to the modlue tree -- this MAY
### override things of course
if( my $old_mod = $self->module_tree( $mod->module ) ) {
### On VMS use the old module name to get the real case
$mod->module( $old_mod->module ) if ON_VMS;
msg(loc("About to overwrite module tree entry for '%1' with '%2'",
$mod->module, $mod->package), $verbose);
}
### mark where it came from
$mod->description( loc("Custom source from '%1'",$name) );
### store it in the module tree
$self->module_tree->{ $mod->module } = $mod;
}
}
return 1;
}
}
1;
| agpl-3.0 |
Andr3iC/courtlistener | cl/visualizations/templates/visualization_embedded.html | 1485 | {% extends "visualization.html" %}
{% load markdown_deux_tags %}
{% load text_filters %}
{% load humanize %}
{% block title %}Embedded Network Graph of {{ viz.title }} –
CourtListener.com{% endblock %}
{# Disable a number of blocks #}
{% block description %}{% endblock %}
{% block meta %}{% endblock %}
{% block icons %}{% endblock %}
{% block header %}{% endblock %}
{% block footer %}{% endblock %}
{% block social %}{% endblock %}
{% block viz-id %}{% endblock %}
{% block vis-subtitles %}{% endblock %}
{% block vis-lower-content %}{% endblock %}
{% block vis-forms %}{% endblock %}
{# Add en embed class to the body so that it gets minimized. #}
{% block body-classes %}embed{% endblock %}
{# This value corresponds closely with the iframe height for the embed page #}
{% block height %}400{% endblock %}
{% block vis-title %}
<h3 id="title"
class="text-center">{{ viz.title|v_wrapper }}</h3>
{% endblock %}
{% block vis-caption %}
<div class="row">
<div class="col-xs-6">
<p>Created by {{ viz.user }} at <a
href="https://www.courtlistener.com/"
target="_blank">CourtListener.com</a>.
</p>
</div>
<div class="col-xs-6 text-right">
<p>
<a href="{{ viz.get_absolute_url }}?{{ request.GET.urlencode }}" class="btn btn-primary"
target="_blank">View Original</a>
</p>
</div>
</div>
{% endblock %}
| agpl-3.0 |
annando/friendica | src/Module/Magic.php | 4902 | <?php
/**
* @copyright Copyright (C) 2010-2022, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module;
use Friendica\App;
use Friendica\BaseModule;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\Database;
use Friendica\Model\Contact;
use Friendica\Model\User;
use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Util\HTTPSignature;
use Friendica\Util\Profiler;
use Friendica\Util\Strings;
use Psr\Log\LoggerInterface;
/**
* Magic Auth (remote authentication) module.
*
* Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
*/
class Magic extends BaseModule
{
/** @var App */
protected $app;
/** @var Database */
protected $dba;
/** @var ICanSendHttpRequests */
protected $httpClient;
public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, Database $dba, ICanSendHttpRequests $httpClient, array $server, array $parameters = [])
{
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->app = $app;
$this->dba = $dba;
$this->httpClient = $httpClient;
}
protected function rawContent(array $request = [])
{
$this->logger->info('magic module: invoked');
$this->logger->debug('args', ['request' => $_REQUEST]);
$addr = $_REQUEST['addr'] ?? '';
$dest = $_REQUEST['dest'] ?? '';
$owa = (!empty($_REQUEST['owa']) ? intval($_REQUEST['owa']) : 0);
$cid = 0;
if (!empty($addr)) {
$cid = Contact::getIdForURL($addr);
} elseif (!empty($dest)) {
$cid = Contact::getIdForURL($dest);
}
if (!$cid) {
$this->logger->info('No contact record found', $_REQUEST);
// @TODO Finding a more elegant possibility to redirect to either internal or external URL
$this->app->redirect($dest);
}
$contact = $this->dba->selectFirst('contact', ['id', 'nurl', 'url'], ['id' => $cid]);
// Redirect if the contact is already authenticated on this site.
if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl->get())) !== false) {
$this->logger->info('Contact is already authenticated');
System::externalRedirect($dest);
}
// OpenWebAuth
if (local_user() && $owa) {
$user = User::getById(local_user());
// Extract the basepath
// NOTE: we need another solution because this does only work
// for friendica contacts :-/ . We should have the basepath
// of a contact also in the contact table.
$exp = explode('/profile/', $contact['url']);
$basepath = $exp[0];
$header = [
'Accept' => ['application/x-dfrn+json', 'application/x-zot+json'],
'X-Open-Web-Auth' => [Strings::getRandomHex()],
];
// Create a header that is signed with the local users private key.
$header = HTTPSignature::createSig(
$header,
$user['prvkey'],
'acct:' . $user['nickname'] . '@' . $this->baseUrl->getHostname() . ($this->baseUrl->getUrlPath() ? '/' . $this->baseUrl->getUrlPath() : '')
);
// Try to get an authentication token from the other instance.
$curlResult = $this->httpClient->get($basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
if ($curlResult->isSuccess()) {
$j = json_decode($curlResult->getBody(), true);
if ($j['success']) {
$token = '';
if ($j['encrypted_token']) {
// The token is encrypted. If the local user is really the one the other instance
// thinks he/she is, the token can be decrypted with the local users public key.
openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $user['prvkey']);
} else {
$token = $j['token'];
}
$args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
$this->logger->info('Redirecting', ['path' => $dest . $args]);
System::externalRedirect($dest . $args);
}
}
System::externalRedirect($dest);
}
// @TODO Finding a more elegant possibility to redirect to either internal or external URL
$this->app->redirect($dest);
}
}
| agpl-3.0 |
ralphkretzschmar/zurmohuf | app/protected/modules/accounts/tests/unit/walkthrough/AccountsDesignerSuperUserWalkthroughTest.php | 94738 | <?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2015 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address [email protected].
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2015. All rights reserved".
********************************************************************************/
/**
* Designer Module Walkthrough of accounts.
* Walkthrough for the super user of all possible controller actions.
* Since this is a super user, he should have access to all controller actions
* without any exceptions being thrown.
* This also test the creation of the customfileds, addition of custom fields to all the layouts including the search
* views.
* This also test creation, search, edit and delete of the account based on the custom fields.
*/
class AccountsDesignerSuperUserWalkthroughTest extends ZurmoWalkthroughBaseTest
{
public static $activateDefaultLanguages = true;
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
SecurityTestHelper::createSuperAdmin();
$super = User::getByUsername('super');
Yii::app()->user->userModel = $super;
Currency::makeBaseCurrency();
//Create a account for testing
$account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
}
public function testSuperUserAccountDefaultControllerActions()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Default Controller actions requiring some sort of parameter via POST or GET
//Load Account Modules Menu.
$this->resetPostArray();
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/modulesMenu');
//Load AttributesList for Account module.
$this->resetPostArray();
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/attributesList');
//Load ModuleLayoutsList for Account module.
$this->resetPostArray();
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/moduleLayoutsList');
//Load ModuleEdit view for each applicable module.
$this->resetPostArray();
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/moduleEdit');
//Now validate save with failed validation.
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
$this->setPostArray(array('ajax' => 'edit-form',
'AccountsModuleForm' => $this->createModuleEditBadValidationPostData()));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/moduleEdit');
//Now validate save with successful validation.
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
$this->setPostArray(array('ajax' => 'edit-form',
'AccountsModuleForm' => $this->createModuleEditGoodValidationPostData('acc new name')));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/moduleEdit');
$this->assertEquals('[]', $content);
//Now save successfully.
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenATaskIsCompleted();
$this->assertTrue($value);
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenANoteIsCreated();
$this->assertTrue($value);
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenAnEmailIsSentOrArchived();
$this->assertTrue($value);
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenAMeetingIsInThePast();
$this->assertTrue($value);
$postDataForForm = $this->createModuleEditGoodValidationPostData('acc new name');
$postDataForForm['updateLatestActivityDateTimeWhenATaskIsCompleted'] = '';
$postDataForForm['updateLatestActivityDateTimeWhenANoteIsCreated'] = '';
$postDataForForm['updateLatestActivityDateTimeWhenAnEmailIsSentOrArchived'] = '';
$postDataForForm['updateLatestActivityDateTimeWhenAMeetingIsInThePast'] = '';
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
$this->setPostArray(array('save' => 'Save', 'AccountsModuleForm' => $postDataForForm));
$this->runControllerWithRedirectExceptionAndGetContent('designer/default/moduleEdit');
//Now confirm everything did in fact save correctly.
$this->assertEquals('Acc New Name', AccountsModule::getModuleLabelByTypeAndLanguage('Singular'));
$this->assertEquals('Acc New Names', AccountsModule::getModuleLabelByTypeAndLanguage('Plural'));
$this->assertEquals('acc new name', AccountsModule::getModuleLabelByTypeAndLanguage('SingularLowerCase'));
$this->assertEquals('acc new names', AccountsModule::getModuleLabelByTypeAndLanguage('PluralLowerCase'));
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenATaskIsCompleted();
$this->assertFalse($value);
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenANoteIsCreated();
$this->assertFalse($value);
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenAnEmailIsSentOrArchived();
$this->assertFalse($value);
$value = AccountsModule::shouldUpdateLatestActivityDateTimeWhenAMeetingIsInThePast();
$this->assertFalse($value);
//Load LayoutEdit for each applicable module and applicable layout
$this->resetPostArray();
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountEditAndDetailsView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsListView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsMassEditView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsModalListView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsModalSearchView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsRelatedListView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsSearchView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountConvertToView'));
$this->runControllerWithNoExceptionsAndGetContent('designer/default/LayoutEdit');
}
/**
* @depends testSuperUserAccountDefaultControllerActions
*/
public function testSuperUserCustomFieldsWalkthroughForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Test create field list.
$this->resetPostArray();
$this->setGetArray(array('moduleClassName' => 'AccountsModule'));
//View creation screen, then create custom field for each custom field type.
$this->createCheckBoxCustomFieldByModule ('AccountsModule', 'checkbox');
$this->createCurrencyValueCustomFieldByModule ('AccountsModule', 'currency');
$this->createDateCustomFieldByModule ('AccountsModule', 'date');
$this->createDateTimeCustomFieldByModule ('AccountsModule', 'datetime');
$this->createDecimalCustomFieldByModule ('AccountsModule', 'decimal');
$this->createDropDownCustomFieldByModule ('AccountsModule', 'picklist');
$this->createDependentDropDownCustomFieldByModule ('AccountsModule', 'countrylist');
$this->createDependentDropDownCustomFieldByModule ('AccountsModule', 'statelist');
$this->createDependentDropDownCustomFieldByModule ('AccountsModule', 'citylist');
$this->createMultiSelectDropDownCustomFieldByModule ('AccountsModule', 'multiselect');
$this->createTagCloudCustomFieldByModule ('AccountsModule', 'tagcloud');
$this->createCalculatedNumberCustomFieldByModule ('AccountsModule', 'calcnumber');
$this->createDropDownDependencyCustomFieldByModule ('AccountsModule', 'dropdowndep');
$this->createDropDownDependencyCustomFieldByModule ('AccountsModule', 'dropdowndep2');
$this->createIntegerCustomFieldByModule ('AccountsModule', 'integer');
$this->createPhoneCustomFieldByModule ('AccountsModule', 'phone');
$this->createRadioDropDownCustomFieldByModule ('AccountsModule', 'radio');
$this->createTextCustomFieldByModule ('AccountsModule', 'text');
$this->createTextAreaCustomFieldByModule ('AccountsModule', 'textarea');
$this->createUrlCustomFieldByModule ('AccountsModule', 'url');
}
/**
* @depends testSuperUserCustomFieldsWalkthroughForAccountsModule
*/
public function testSuperUserAddCustomFieldsToLayoutsForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Add custom fields to AccountEditAndDetailsView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountEditAndDetailsView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountEditAndDetailsViewLayoutWithAllCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout,
'LayoutPanelsTypeForm' => array('type' => FormLayout::PANELS_DISPLAY_TYPE_ALL)));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertContains('Layout saved successfully', $content);
//Add all fields to AccountsSearchView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsSearchView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountsSearchViewLayoutWithAllCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertContains('Layout saved successfully', $content);
//Add all fields to AccountsModalSearchView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsModalSearchView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountsSearchViewLayoutWithAllCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertContains('Layout saved successfully', $content);
//Add all fields to AccountsListView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsListView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountsListViewLayoutWithAllStandardAndCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertContains('Layout saved successfully', $content);
//Add all fields to AccountsRelatedListView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsRelatedListView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountsListViewLayoutWithAllStandardAndCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertContains('Layout saved successfully', $content);
//Add all fields to AccountsModalListView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsModalListView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountsListViewLayoutWithAllStandardAndCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertContains('Layout saved successfully', $content);
//Add all fields to AccountsMassEditView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountsMassEditView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountsMassEditViewLayoutWithAllStandardAndCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertContains('Layout saved successfully', $content);
//Add all fields to AccountConvertToView.
$this->setGetArray(array('moduleClassName' => 'AccountsModule',
'viewClassName' => 'AccountConvertToView'));
$layout = AccountsDesignerWalkthroughHelperUtil::getAccountEditAndDetailsViewLayoutWithAllCustomFieldsPlaced();
$this->setPostArray(array('save' => 'Save', 'layout' => $layout));
$content = $this->runControllerWithExitExceptionAndGetContent('designer/default/LayoutEdit');
$this->assertFalse(strpos($content, 'Layout saved successfully') === false);
}
/**
* @depends testSuperUserAddCustomFieldsToLayoutsForAccountsModule
*/
public function testLayoutsLoadOkAfterCustomFieldsPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
$superAccountId = self::getModelIdByModelNameAndName ('Account', 'superAccount');
//Load create, edit, and details views.
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/create');
$this->setGetArray(array('id' => $superAccountId));
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/edit');
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/details');
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/list');
$this->setGetArray(array(
'modalTransferInformation' => array('sourceIdFieldId' => 'x', 'sourceNameFieldId' => 'y', 'modalId' => 'z')
));
$this->resetPostArray();
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/modalList');
$this->setGetArray(array('selectAll' => '1'));
$this->resetPostArray();
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/massEdit');
//todo: test related list once the related list is available in a sub view.
}
/**
* @depends testLayoutsLoadOkAfterCustomFieldsPlacedForAccountsModule
*/
public function testCreateAnAccountUserAfterTheCustomFieldsArePlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Set the date and datetime variable values here
$date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time());
$dateAssert = date('Y-m-d');
$datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time());
$datetimeAssert = date('Y-m-d H:i:')."00";
$baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
//Create a new account based on the custom fields.
$this->resetGetArray();
$this->setPostArray(array('Account' => array(
'name' => 'myNewAccount',
'officePhone' => '259-784-2169',
'industry' => array('value' => 'Automotive'),
'officeFax' => '299-845-7863',
'employees' => '930',
'annualRevenue' => '474000000',
'type' => array('value' => 'Prospect'),
'website' => 'http://www.Unnamed.com',
'primaryEmail' => array('emailAddress' => '[email protected]',
'optOut' => '1',
'isInvalid' => '0'),
'secondaryEmail' => array('emailAddress' => '',
'optOut' => '0',
'isInvalid' => '0'),
'billingAddress' => array('street1' => '6466 South Madison Creek',
'street2' => '',
'city' => 'Chicago',
'state' => 'IL',
'postalCode' => '60652',
'country' => 'USA'),
'shippingAddress' => array('street1' => '27054 West Michigan Lane',
'street2' => '',
'city' => 'Austin',
'state' => 'TX',
'postalCode' => '78759',
'country' => 'USA'),
'description' => 'This is a Description',
'explicitReadWriteModelPermissions' => array('type' => null),
'checkboxCstm' => '1',
'currencyCstm' => array('value' => 45,
'currency' => array('id' =>
$baseCurrency->id)),
'dateCstm' => $date,
'datetimeCstm' => $datetime,
'decimalCstm' => '123',
'picklistCstm' => array('value' => 'a'),
'multiselectCstm' => array('values' => array('ff', 'rr')),
'tagcloudCstm' => array('values' => array('writing', 'gardening')),
'countrylistCstm' => array('value' => 'bbbb'),
'statelistCstm' => array('value' => 'bbb1'),
'citylistCstm' => array('value' => 'bb1'),
'integerCstm' => '12',
'phoneCstm' => '259-784-2169',
'radioCstm' => array('value' => 'd'),
'textCstm' => 'This is a test Text',
'textareaCstm' => 'This is a test TextArea',
'urlCstm' => 'http://wwww.abc.com')));
$this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/create');
//Check the details if they are saved properly for the custom fields.
$account = Account::getByName('myNewAccount');
//Retrieve the permission for the account.
$explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::
makeBySecurableItem(Account::getById($account[0]->id));
$readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
$readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name , 'myNewAccount');
$this->assertEquals($account[0]->officePhone , '259-784-2169');
$this->assertEquals($account[0]->industry->value , 'Automotive');
$this->assertEquals($account[0]->officeFax , '299-845-7863');
$this->assertEquals($account[0]->employees , '930');
$this->assertEquals($account[0]->annualRevenue , '474000000');
$this->assertEquals($account[0]->type->value , 'Prospect');
$this->assertEquals($account[0]->website , 'http://www.Unnamed.com');
$this->assertEquals($account[0]->primaryEmail->emailAddress , '[email protected]');
$this->assertEquals($account[0]->primaryEmail->optOut , '1');
$this->assertEquals($account[0]->primaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->secondaryEmail->emailAddress , '');
$this->assertEquals($account[0]->secondaryEmail->optOut , '0');
$this->assertEquals($account[0]->secondaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->billingAddress->street1 , '6466 South Madison Creek');
$this->assertEquals($account[0]->billingAddress->street2 , '');
$this->assertEquals($account[0]->billingAddress->city , 'Chicago');
$this->assertEquals($account[0]->billingAddress->state , 'IL');
$this->assertEquals($account[0]->billingAddress->postalCode , '60652');
$this->assertEquals($account[0]->billingAddress->country , 'USA');
$this->assertEquals($account[0]->shippingAddress->street1 , '27054 West Michigan Lane');
$this->assertEquals($account[0]->shippingAddress->street2 , '');
$this->assertEquals($account[0]->shippingAddress->city , 'Austin');
$this->assertEquals($account[0]->shippingAddress->state , 'TX');
$this->assertEquals($account[0]->shippingAddress->postalCode , '78759');
$this->assertEquals($account[0]->shippingAddress->country , 'USA');
$this->assertEquals($account[0]->description , 'This is a Description');
$this->assertEquals(0 , count($readWritePermitables));
$this->assertEquals(0 , count($readOnlyPermitables));
$this->assertEquals($account[0]->checkboxCstm , '1');
$this->assertEquals($account[0]->currencyCstm->value , 45);
$this->assertEquals($account[0]->currencyCstm->currency->id , $baseCurrency->id);
$this->assertEquals($account[0]->dateCstm , $dateAssert);
$this->assertEquals($account[0]->datetimeCstm , $datetimeAssert);
$this->assertEquals($account[0]->decimalCstm , '123');
$this->assertEquals($account[0]->picklistCstm->value , 'a');
$this->assertEquals($account[0]->integerCstm , 12);
$this->assertEquals($account[0]->phoneCstm , '259-784-2169');
$this->assertEquals($account[0]->radioCstm->value , 'd');
$this->assertEquals($account[0]->textCstm , 'This is a test Text');
$this->assertEquals($account[0]->textareaCstm , 'This is a test TextArea');
$this->assertEquals($account[0]->urlCstm , 'http://wwww.abc.com');
$this->assertEquals($account[0]->countrylistCstm->value , 'bbbb');
$this->assertEquals($account[0]->statelistCstm->value , 'bbb1');
$this->assertEquals($account[0]->citylistCstm->value , 'bb1');
$this->assertContains('ff' , $account[0]->multiselectCstm->values);
$this->assertContains('rr' , $account[0]->multiselectCstm->values);
$this->assertContains('writing' , $account[0]->tagcloudCstm->values);
$this->assertContains('gardening' , $account[0]->tagcloudCstm->values);
$metadata = CalculatedDerivedAttributeMetadata::
getByNameAndModelClassName('calcnumber', 'Account');
$formatType = CalculatedNumberUtil::FORMAT_TYPE_INTEGER;
$currencyCode = null;
$testCalculatedValue = CalculatedNumberUtil::calculateByFormulaAndModelAndResolveFormat($metadata->getFormula(), $account[0]);
$this->assertEquals('474,000,930' , $testCalculatedValue); // Not Coding Standard
}
/**
* @depends testCreateAnAccountUserAfterTheCustomFieldsArePlacedForAccountsModule
*/
public function testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleAfterCreatingTheAccountUser()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Search a created account using the customfields.
$this->resetPostArray();
$this->setGetArray(array('AccountsSearchForm' => array(
'name' => 'myNewAccount',
'officePhone' => '259-784-2169',
'type' => array('value' => 'Prospect'),
'officeFax' => '299-845-7863',
'employees' => '930',
'website' => 'http://www.Unnamed.com',
'annualRevenue' => '474000000',
'anyCity' => 'Austin',
'anyState' => 'TX',
'anyStreet' => '27054 West Michigan Lane',
'anyPostalCode' => '78759',
'anyCountry' => 'USA',
'anyEmail' => '[email protected]',
'anyOptOutEmail' => array('value' => '1'),
'anyInvalidEmail' => array('value' => ''),
'ownedItemsOnly' => '1',
'industry' => array('value' => 'Automotive'),
'decimalCstm' => '123',
'integerCstm' => '12',
'phoneCstm' => '259-784-2169',
'textCstm' => 'This is a test Text',
'textareaCstm' => 'This is a test TextArea',
'urlCstm' => 'http://wwww.abc.com',
'checkboxCstm' => array('value' => '1'),
'currencyCstm' => array('value' => 45),
'picklistCstm' => array('value' => 'a'),
'multiselectCstm' => array('values' => array('ff', 'rr')),
'tagcloudCstm' => array('values' => array('writing', 'gardening')),
'countrylistCstm' => array('value' => 'bbbb'),
'statelistCstm' => array('value' => 'bbb1'),
'citylistCstm' => array('value' => 'bb1'),
'radioCstm' => array('value' => 'd'),
'dateCstm__Date' => array('type' => 'Today'),
'datetimeCstm__DateTime' => array('type' => 'Today')),
'ajax' => 'list-view'));
$content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default');
//Check if the account name exists after the search is performed on the basis of the
//custom fields added to the accounts module.
//$this->assertContains("Displaying 1-1 of 1 result(s).", $content); //removed until we show the count again in the listview.
$this->assertContains("myNewAccount", $content);
}
/**
* @depends testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleAfterCreatingTheAccountUser
*/
public function testEditOfTheAccountUserForTheTagCloudFieldAfterLeavingOnlyOneTagPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Set the date and datetime variable values here.
$date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time());
$dateAssert = date('Y-m-d');
$datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time());
$datetimeAssert = date('Y-m-d H:i:')."00";
$baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
$explicitReadWriteModelPermission = ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP;
//Get the account id from the recently created account.
$account = Account::getByName('myNewAccount');
$accountId = $account[0]->id;
$this->assertEquals(2, $account[0]->tagcloudCstm->values->count());
//Edit and save the account.
$this->setGetArray(array('id' => $accountId));
$this->setPostArray(array('Account' => array(
'name' => 'myEditAccount',
'officePhone' => '259-734-2169',
'industry' => array('value' => 'Energy'),
'officeFax' => '299-825-7863',
'employees' => '630',
'annualRevenue' => '472000000',
'type' => array('value' => 'Customer'),
'website' => 'http://www.UnnamedEdit.com',
'primaryEmail' => array('emailAddress' => '[email protected]',
'optOut' => '0',
'isInvalid' => '0'),
'secondaryEmail' => array('emailAddress' => '',
'optOut' => '0',
'isInvalid' => '0'),
'billingAddress' => array('street1' => '26378 South Arlington Ave',
'street2' => '',
'city' => 'San Jose',
'state' => 'CA',
'postalCode' => '95131',
'country' => 'USA'),
'shippingAddress' => array('street1' => '8519 East Franklin Center',
'street2' => '',
'city' => 'Chicago',
'state' => 'IL',
'postalCode' => '60652',
'country' => 'USA'),
'description' => 'This is a Edit Description',
'explicitReadWriteModelPermissions' => array('type' => $explicitReadWriteModelPermission),
'dateCstm' => $date,
'datetimeCstm' => $datetime,
'checkboxCstm' => '0',
'currencyCstm' => array('value' => 40,
'currency' => array(
'id' => $baseCurrency->id)),
'decimalCstm' => '12',
'picklistCstm' => array('value' => 'b'),
'multiselectCstm' => array('values' => array('gg', 'hh')),
'tagcloudCstm' => array('values' => array('writing')),
'countrylistCstm' => array('value' => 'aaaa'),
'statelistCstm' => array('value' => 'aaa1'),
'citylistCstm' => array('value' => 'ab1'),
'integerCstm' => '11',
'phoneCstm' => '259-784-2069',
'radioCstm' => array('value' => 'e'),
'textCstm' => 'This is a test Edit Text',
'textareaCstm' => 'This is a test Edit TextArea',
'urlCstm' => 'http://wwww.abc-edit.com'),
'save' => 'Save'));
$this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/edit');
//Check the details if they are saved properly for the custom fields after the edit.
$account = Account::getByName('myEditAccount');
//Retrieve the permission of the account
$explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::
makeBySecurableItem(Account::getById($account[0]->id));
$readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
$readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name , 'myEditAccount');
$this->assertEquals($account[0]->officePhone , '259-734-2169');
$this->assertEquals($account[0]->industry->value , 'Energy');
$this->assertEquals($account[0]->officeFax , '299-825-7863');
$this->assertEquals($account[0]->employees , '630');
$this->assertEquals($account[0]->annualRevenue , '472000000');
$this->assertEquals($account[0]->type->value , 'Customer');
$this->assertEquals($account[0]->website , 'http://www.UnnamedEdit.com');
$this->assertEquals($account[0]->primaryEmail->emailAddress , '[email protected]');
$this->assertEquals($account[0]->primaryEmail->optOut , '0');
$this->assertEquals($account[0]->primaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->secondaryEmail->emailAddress , '');
$this->assertEquals($account[0]->secondaryEmail->optOut , '0');
$this->assertEquals($account[0]->secondaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->billingAddress->street1 , '26378 South Arlington Ave');
$this->assertEquals($account[0]->billingAddress->street2 , '');
$this->assertEquals($account[0]->billingAddress->city , 'San Jose');
$this->assertEquals($account[0]->billingAddress->state , 'CA');
$this->assertEquals($account[0]->billingAddress->postalCode , '95131');
$this->assertEquals($account[0]->billingAddress->country , 'USA');
$this->assertEquals($account[0]->shippingAddress->street1 , '8519 East Franklin Center');
$this->assertEquals($account[0]->shippingAddress->street2 , '');
$this->assertEquals($account[0]->shippingAddress->city , 'Chicago');
$this->assertEquals($account[0]->shippingAddress->state , 'IL');
$this->assertEquals($account[0]->shippingAddress->postalCode , '60652');
$this->assertEquals($account[0]->shippingAddress->country , 'USA');
$this->assertEquals($account[0]->description , 'This is a Edit Description');
$this->assertEquals(1 , count($readWritePermitables));
$this->assertEquals(0 , count($readOnlyPermitables));
$this->assertEquals($account[0]->checkboxCstm , '0');
$this->assertEquals($account[0]->currencyCstm->value , 40);
$this->assertEquals($account[0]->currencyCstm->currency->id , $baseCurrency->id);
$this->assertEquals($account[0]->dateCstm , $dateAssert);
$this->assertEquals($account[0]->datetimeCstm , $datetimeAssert);
$this->assertEquals($account[0]->decimalCstm , '12');
$this->assertEquals($account[0]->picklistCstm->value , 'b');
$this->assertEquals($account[0]->integerCstm , 11);
$this->assertEquals($account[0]->phoneCstm , '259-784-2069');
$this->assertEquals($account[0]->radioCstm->value , 'e');
$this->assertEquals($account[0]->textCstm , 'This is a test Edit Text');
$this->assertEquals($account[0]->textareaCstm , 'This is a test Edit TextArea');
$this->assertEquals($account[0]->urlCstm , 'http://wwww.abc-edit.com');
$this->assertEquals($account[0]->countrylistCstm->value , 'aaaa');
$this->assertEquals($account[0]->statelistCstm->value , 'aaa1');
$this->assertEquals($account[0]->citylistCstm->value , 'ab1');
$this->assertContains('gg' , $account[0]->multiselectCstm->values);
$this->assertContains('hh' , $account[0]->multiselectCstm->values);
$this->assertEquals(1 , $account[0]->tagcloudCstm->values->count());
$metadata = CalculatedDerivedAttributeMetadata::
getByNameAndModelClassName('calcnumber', 'Account');
$formatType = CalculatedNumberUtil::FORMAT_TYPE_INTEGER;
$currencyCode = null;
$testCalculatedValue = CalculatedNumberUtil::calculateByFormulaAndModelAndResolveFormat($metadata->getFormula(), $account[0]);
$this->assertEquals('472,000,630' , $testCalculatedValue); // Not Coding Standard
}
/**
* @depends testEditOfTheAccountUserForTheTagCloudFieldAfterLeavingOnlyOneTagPlacedForAccountsModule
*/
public function testEditOfTheAccountUserForTheTagCloudFieldAfterRemovingAllTagsPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Set the date and datetime variable values here.
$date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time());
$datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time());
$baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
$explicitReadWriteModelPermission = ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP;
$account = Account::getByName('myEditAccount');
$accountId = $account[0]->id;
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name, 'myEditAccount');
$this->assertEquals(1, $account[0]->tagcloudCstm->values->count());
//Edit and save the account.
$this->setGetArray(array('id' => $accountId));
$this->setPostArray(array('Account' => array(
'name' => '',
'officePhone' => '259-734-2169',
'industry' => array('value' => 'Energy'),
'officeFax' => '299-825-7863',
'employees' => '630',
'annualRevenue' => '472000000',
'type' => array('value' => 'Customer'),
'website' => 'http://www.UnnamedEdit.com',
'primaryEmail' => array('emailAddress' => '[email protected]',
'optOut' => '0',
'isInvalid' => '0'),
'secondaryEmail' => array('emailAddress' => '',
'optOut' => '0',
'isInvalid' => '0'),
'billingAddress' => array('street1' => '26378 South Arlington Ave',
'street2' => '',
'city' => 'San Jose',
'state' => 'CA',
'postalCode' => '95131',
'country' => 'USA'),
'shippingAddress' => array('street1' => '8519 East Franklin Center',
'street2' => '',
'city' => 'Chicago',
'state' => 'IL',
'postalCode' => '60652',
'country' => 'USA'),
'description' => 'This is a Edit Description',
'explicitReadWriteModelPermissions' => array('type' => $explicitReadWriteModelPermission),
'dateCstm' => $date,
'datetimeCstm' => $datetime,
'checkboxCstm' => '0',
'currencyCstm' => array('value' => 40,
'currency' => array(
'id' => $baseCurrency->id)),
'decimalCstm' => '12',
'picklistCstm' => array('value' => 'b'),
'multiselectCstm' => array('values' => array('gg', 'hh')),
'tagcloudCstm' => array('values' => array()),
'countrylistCstm' => array('value' => 'aaaa'),
'statelistCstm' => array('value' => 'aaa1'),
'citylistCstm' => array('value' => 'ab1'),
'integerCstm' => '11',
'phoneCstm' => '259-784-2069',
'radioCstm' => array('value' => 'e'),
'textCstm' => 'This is a test Edit Text',
'textareaCstm' => 'This is a test Edit TextArea',
'urlCstm' => 'http://wwww.abc-edit.com'),
'save' => 'Save'));
$content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default/edit');
$this->assertContains("tagcloud en cannot be blank.", $content);
}
/**
* @depends testEditOfTheAccountUserForTheTagCloudFieldAfterRemovingAllTagsPlacedForAccountsModule
*/
public function testEditOfTheAccountUserForTheCustomFieldsPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Set the date and datetime variable values here.
$date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time());
$dateAssert = date('Y-m-d');
$datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time());
$datetimeAssert = date('Y-m-d H:i:')."00";
$baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
$explicitReadWriteModelPermission = ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP;
//Get the account id from the recently created account.
$account = Account::getByName('myEditAccount');
$accountId = $account[0]->id;
//Edit and save the account.
$this->setGetArray(array('id' => $accountId));
$this->setPostArray(array('Account' => array(
'name' => 'myEditAccount',
'officePhone' => '259-734-2169',
'industry' => array('value' => 'Energy'),
'officeFax' => '299-825-7863',
'employees' => '630',
'annualRevenue' => '472000000',
'type' => array('value' => 'Customer'),
'website' => 'http://www.UnnamedEdit.com',
'primaryEmail' => array('emailAddress' => '[email protected]',
'optOut' => '0',
'isInvalid' => '0'),
'secondaryEmail' => array('emailAddress' => '',
'optOut' => '0',
'isInvalid' => '0'),
'billingAddress' => array('street1' => '26378 South Arlington Ave',
'street2' => '',
'city' => 'San Jose',
'state' => 'CA',
'postalCode' => '95131',
'country' => 'USA'),
'shippingAddress' => array('street1' => '8519 East Franklin Center',
'street2' => '',
'city' => 'Chicago',
'state' => 'IL',
'postalCode' => '60652',
'country' => 'USA'),
'description' => 'This is a Edit Description',
'explicitReadWriteModelPermissions' => array('type' => $explicitReadWriteModelPermission),
'dateCstm' => $date,
'datetimeCstm' => $datetime,
'checkboxCstm' => '0',
'currencyCstm' => array('value' => 40,
'currency' => array(
'id' => $baseCurrency->id)),
'decimalCstm' => '12',
'picklistCstm' => array('value' => 'b'),
'multiselectCstm' => array('values' => array('gg', 'hh')),
'tagcloudCstm' => array('values' => array('reading', 'surfing')),
'countrylistCstm' => array('value' => 'aaaa'),
'statelistCstm' => array('value' => 'aaa1'),
'citylistCstm' => array('value' => 'ab1'),
'integerCstm' => '11',
'phoneCstm' => '259-784-2069',
'radioCstm' => array('value' => 'e'),
'textCstm' => 'This is a test Edit Text',
'textareaCstm' => 'This is a test Edit TextArea',
'urlCstm' => 'http://wwww.abc-edit.com'),
'save' => 'Save'));
$this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/edit');
//Check the details if they are saved properly for the custom fields after the edit.
$account = Account::getByName('myEditAccount');
//Retrieve the permission of the account
$explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::
makeBySecurableItem(Account::getById($account[0]->id));
$readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
$readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name , 'myEditAccount');
$this->assertEquals($account[0]->officePhone , '259-734-2169');
$this->assertEquals($account[0]->industry->value , 'Energy');
$this->assertEquals($account[0]->officeFax , '299-825-7863');
$this->assertEquals($account[0]->employees , '630');
$this->assertEquals($account[0]->annualRevenue , '472000000');
$this->assertEquals($account[0]->type->value , 'Customer');
$this->assertEquals($account[0]->website , 'http://www.UnnamedEdit.com');
$this->assertEquals($account[0]->primaryEmail->emailAddress , '[email protected]');
$this->assertEquals($account[0]->primaryEmail->optOut , '0');
$this->assertEquals($account[0]->primaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->secondaryEmail->emailAddress , '');
$this->assertEquals($account[0]->secondaryEmail->optOut , '0');
$this->assertEquals($account[0]->secondaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->billingAddress->street1 , '26378 South Arlington Ave');
$this->assertEquals($account[0]->billingAddress->street2 , '');
$this->assertEquals($account[0]->billingAddress->city , 'San Jose');
$this->assertEquals($account[0]->billingAddress->state , 'CA');
$this->assertEquals($account[0]->billingAddress->postalCode , '95131');
$this->assertEquals($account[0]->billingAddress->country , 'USA');
$this->assertEquals($account[0]->shippingAddress->street1 , '8519 East Franklin Center');
$this->assertEquals($account[0]->shippingAddress->street2 , '');
$this->assertEquals($account[0]->shippingAddress->city , 'Chicago');
$this->assertEquals($account[0]->shippingAddress->state , 'IL');
$this->assertEquals($account[0]->shippingAddress->postalCode , '60652');
$this->assertEquals($account[0]->shippingAddress->country , 'USA');
$this->assertEquals($account[0]->description , 'This is a Edit Description');
$this->assertEquals(1 , count($readWritePermitables));
$this->assertEquals(0 , count($readOnlyPermitables));
$this->assertEquals($account[0]->checkboxCstm , '0');
$this->assertEquals($account[0]->currencyCstm->value , 40);
$this->assertEquals($account[0]->currencyCstm->currency->id , $baseCurrency->id);
$this->assertEquals($account[0]->dateCstm , $dateAssert);
$this->assertEquals($account[0]->datetimeCstm , $datetimeAssert);
$this->assertEquals($account[0]->decimalCstm , '12');
$this->assertEquals($account[0]->picklistCstm->value , 'b');
$this->assertEquals($account[0]->integerCstm , 11);
$this->assertEquals($account[0]->phoneCstm , '259-784-2069');
$this->assertEquals($account[0]->radioCstm->value , 'e');
$this->assertEquals($account[0]->textCstm , 'This is a test Edit Text');
$this->assertEquals($account[0]->textareaCstm , 'This is a test Edit TextArea');
$this->assertEquals($account[0]->urlCstm , 'http://wwww.abc-edit.com');
$this->assertEquals($account[0]->countrylistCstm->value , 'aaaa');
$this->assertEquals($account[0]->statelistCstm->value , 'aaa1');
$this->assertEquals($account[0]->citylistCstm->value , 'ab1');
$this->assertContains('gg' , $account[0]->multiselectCstm->values);
$this->assertContains('hh' , $account[0]->multiselectCstm->values);
$this->assertContains('reading' , $account[0]->tagcloudCstm->values);
$this->assertContains('surfing' , $account[0]->tagcloudCstm->values);
$metadata = CalculatedDerivedAttributeMetadata::
getByNameAndModelClassName('calcnumber', 'Account');
$testCalculatedValue = CalculatedNumberUtil::calculateByFormulaAndModelAndResolveFormat($metadata->getFormula(), $account[0]);
$this->assertEquals('472,000,630' , $testCalculatedValue); // Not Coding Standard
}
/**
* @depends testEditOfTheAccountUserForTheCustomFieldsPlacedForAccountsModule
*/
public function testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleAfterEditingTheAccountUser()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Search a created account using the customfield.
$this->resetPostArray();
$this->setGetArray(array(
'AccountsSearchForm' => AccountsDesignerWalkthroughHelperUtil::fetchAccountsSearchFormGetData(),
'ajax' => 'list-view')
);
$content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default');
//Assert that the edit account exits after the edit and is diaplayed on the search page.
//$this->assertContains("Displaying 1-1 of 1 result(s).", $content); //removed until we show the count again in the listview.
$this->assertContains("myEditAccount", $content);
}
/**
* @depends testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleAfterEditingTheAccountUser
*/
public function testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleWithMultiSelectValueSetToNull()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Search a created account using the customfield.
$this->resetPostArray();
$this->setGetArray(array(
'AccountsSearchForm' => AccountsDesignerWalkthroughHelperUtil::fetchAccountsSearchFormGetDataWithMultiSelectValueSetToNull(),
'ajax' => 'list-view')
);
$content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default');
//Assert that the edit account exits after the edit and is diaplayed on the search page.
//$this->assertContains("Displaying 1-1 of 1 result(s).", $content); //removed until we show the count again in the listview.
$this->assertContains("myEditAccount", $content);
}
/**
* @depends testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleWithMultiSelectValueSetToNull
*/
public function testCreateSecondAccountForUserAfterTheCustomFieldsArePlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Set the date and datetime variable values here
$date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time());
$dateAssert = date('Y-m-d');
$datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time());
$datetimeAssert = date('Y-m-d H:i:')."00";
$baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
//Create a new account based on the custom fields.
$this->resetGetArray();
$this->setPostArray(array('Account' => array(
'name' => 'mySecondAccount',
'officePhone' => '259-784-2169',
'industry' => array('value' => 'Automotive'),
'officeFax' => '299-845-7863',
'employees' => '930',
'annualRevenue' => '474000000',
'type' => array('value' => 'Prospect'),
'website' => 'http://www.Unnamed.com',
'primaryEmail' => array('emailAddress' => '[email protected]',
'optOut' => '1',
'isInvalid' => '0'),
'secondaryEmail' => array('emailAddress' => '',
'optOut' => '0',
'isInvalid' => '0'),
'billingAddress' => array('street1' => '6466 South Madison Creek',
'street2' => '',
'city' => 'Chicago',
'state' => 'IL',
'postalCode' => '60652',
'country' => 'USA'),
'shippingAddress' => array('street1' => '27054 West Michigan Lane',
'street2' => '',
'city' => 'Austin',
'state' => 'TX',
'postalCode' => '78759',
'country' => 'USA'),
'description' => 'This is a Description',
'explicitReadWriteModelPermissions' => array('type' => null),
'checkboxCstm' => '1',
'currencyCstm' => array('value' => 45,
'currency' => array('id' =>
$baseCurrency->id)),
'dateCstm' => $date,
'datetimeCstm' => $datetime,
'decimalCstm' => '123',
'picklistCstm' => array('value' => 'a'),
'multiselectCstm' => array('values' => array('gg', 'ff')),
'tagcloudCstm' => array('values' => array('reading', 'writing')),
'countrylistCstm' => array('value' => 'bbbb'),
'statelistCstm' => array('value' => 'bbb1'),
'citylistCstm' => array('value' => 'bb1'),
'integerCstm' => '12',
'phoneCstm' => '259-784-2169',
'radioCstm' => array('value' => 'd'),
'textCstm' => 'This is a test Text',
'textareaCstm' => 'This is a test TextArea',
'urlCstm' => 'http://wwww.abc.com')));
$this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/create');
//Check the details if they are saved properly for the custom fields.
$account = Account::getByName('mySecondAccount');
//Retrieve the permission for the account.
$explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::
makeBySecurableItem(Account::getById($account[0]->id));
$readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
$readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name , 'mySecondAccount');
$this->assertEquals($account[0]->officePhone , '259-784-2169');
$this->assertEquals($account[0]->industry->value , 'Automotive');
$this->assertEquals($account[0]->officeFax , '299-845-7863');
$this->assertEquals($account[0]->employees , '930');
$this->assertEquals($account[0]->annualRevenue , '474000000');
$this->assertEquals($account[0]->type->value , 'Prospect');
$this->assertEquals($account[0]->website , 'http://www.Unnamed.com');
$this->assertEquals($account[0]->primaryEmail->emailAddress , '[email protected]');
$this->assertEquals($account[0]->primaryEmail->optOut , '1');
$this->assertEquals($account[0]->primaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->secondaryEmail->emailAddress , '');
$this->assertEquals($account[0]->secondaryEmail->optOut , '0');
$this->assertEquals($account[0]->secondaryEmail->isInvalid , '0');
$this->assertEquals($account[0]->billingAddress->street1 , '6466 South Madison Creek');
$this->assertEquals($account[0]->billingAddress->street2 , '');
$this->assertEquals($account[0]->billingAddress->city , 'Chicago');
$this->assertEquals($account[0]->billingAddress->state , 'IL');
$this->assertEquals($account[0]->billingAddress->postalCode , '60652');
$this->assertEquals($account[0]->billingAddress->country , 'USA');
$this->assertEquals($account[0]->shippingAddress->street1 , '27054 West Michigan Lane');
$this->assertEquals($account[0]->shippingAddress->street2 , '');
$this->assertEquals($account[0]->shippingAddress->city , 'Austin');
$this->assertEquals($account[0]->shippingAddress->state , 'TX');
$this->assertEquals($account[0]->shippingAddress->postalCode , '78759');
$this->assertEquals($account[0]->shippingAddress->country , 'USA');
$this->assertEquals($account[0]->description , 'This is a Description');
$this->assertEquals(0 , count($readWritePermitables));
$this->assertEquals(0 , count($readOnlyPermitables));
$this->assertEquals($account[0]->checkboxCstm , '1');
$this->assertEquals($account[0]->currencyCstm->value , 45);
$this->assertEquals($account[0]->currencyCstm->currency->id , $baseCurrency->id);
$this->assertEquals($account[0]->dateCstm , $dateAssert);
$this->assertEquals($account[0]->datetimeCstm , $datetimeAssert);
$this->assertEquals($account[0]->decimalCstm , '123');
$this->assertEquals($account[0]->picklistCstm->value , 'a');
$this->assertEquals($account[0]->integerCstm , 12);
$this->assertEquals($account[0]->phoneCstm , '259-784-2169');
$this->assertEquals($account[0]->radioCstm->value , 'd');
$this->assertEquals($account[0]->textCstm , 'This is a test Text');
$this->assertEquals($account[0]->textareaCstm , 'This is a test TextArea');
$this->assertEquals($account[0]->urlCstm , 'http://wwww.abc.com');
$this->assertEquals($account[0]->countrylistCstm->value , 'bbbb');
$this->assertEquals($account[0]->statelistCstm->value , 'bbb1');
$this->assertEquals($account[0]->citylistCstm->value , 'bb1');
$this->assertContains('gg' , $account[0]->multiselectCstm->values);
$this->assertContains('ff' , $account[0]->multiselectCstm->values);
$this->assertContains('reading' , $account[0]->tagcloudCstm->values);
$this->assertContains('writing' , $account[0]->tagcloudCstm->values);
}
/**
* @depends testCreateSecondAccountForUserAfterTheCustomFieldsArePlacedForAccountsModule
*/
public function testMultiValueCustomFieldContentAfterCreateAndEditPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Set the date and datetime variable values here
$date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time());
$dateAssert = date('Y-m-d');
$datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time());
$datetimeAssert = date('Y-m-d H:i:')."00";
$baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
//Create a new account based on the custom fields.
$this->resetGetArray();
$this->setPostArray(array('Account' => array(
'name' => 'myThirdAccount',
'officePhone' => '259-784-2169',
'industry' => array('value' => 'Automotive'),
'officeFax' => '299-845-7863',
'employees' => '930',
'annualRevenue' => '474000000',
'type' => array('value' => 'Prospect'),
'website' => 'http://www.Unnamed.com',
'primaryEmail' => array('emailAddress' => '[email protected]',
'optOut' => '1',
'isInvalid' => '0'),
'secondaryEmail' => array('emailAddress' => '',
'optOut' => '0',
'isInvalid' => '0'),
'billingAddress' => array('street1' => '6466 South Madison Creek',
'street2' => '',
'city' => 'Chicago',
'state' => 'IL',
'postalCode' => '60652',
'country' => 'USA'),
'shippingAddress' => array('street1' => '27054 West Michigan Lane',
'street2' => '',
'city' => 'Austin',
'state' => 'TX',
'postalCode' => '78759',
'country' => 'USA'),
'description' => 'This is a Description',
'explicitReadWriteModelPermissions' => array('type' => null),
'checkboxCstm' => '1',
'currencyCstm' => array('value' => 45,
'currency' => array('id' =>
$baseCurrency->id)),
'dateCstm' => $date,
'datetimeCstm' => $datetime,
'decimalCstm' => '123',
'picklistCstm' => array('value' => 'a'),
'multiselectCstm' => array('values' => array('gg', 'ff')),
'tagcloudCstm' => array('values' => array('reading', 'writing')),
'countrylistCstm' => array('value' => 'bbbb'),
'statelistCstm' => array('value' => 'bbb1'),
'citylistCstm' => array('value' => 'bb1'),
'integerCstm' => '12',
'phoneCstm' => '259-784-2169',
'radioCstm' => array('value' => 'd'),
'textCstm' => 'This is a test Text',
'textareaCstm' => 'This is a test TextArea',
'urlCstm' => 'http://wwww.abc.com')));
$this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/create');
//Check the details if they are saved properly for the custom fields.
$account = Account::getByName('myThirdAccount');
//Retrieve the permission for the account.
$explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::
makeBySecurableItem(Account::getById($account[0]->id));
$readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
$readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name , 'myThirdAccount');
$this->assertEquals(2 , $account[0]->multiselectCstm->values->count());
$this->assertEquals(2 , $account[0]->tagcloudCstm->values->count());
$this->assertContains('gg' , $account[0]->multiselectCstm->values);
$this->assertContains('ff' , $account[0]->multiselectCstm->values);
$this->assertContains('reading' , $account[0]->tagcloudCstm->values);
$this->assertContains('writing' , $account[0]->tagcloudCstm->values);
unset($account);
$account = Account::getByName('myThirdAccount');
$accountId = $account[0]->id;
//Edit and save the account.
$this->setGetArray(array('id' => $accountId));
$this->setPostArray(array('Account' => array(
'name' => 'myThirdAccount',
'multiselectCstm' => array('values' => array('ff')),
'tagcloudCstm' => array('values' => array('writing')),
),
'save' => 'Save'));
$this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/edit');
//Check the details if they are saved properly for the custom fields.
$account = Account::getByName('myThirdAccount');
//Retrieve the permission for the account.
$explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::
makeBySecurableItem(Account::getById($account[0]->id));
$readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
$readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
$this->assertEquals(1, count($account));
$this->assertEquals(1 , $account[0]->multiselectCstm->values->count());
$this->assertContains('ff' , $account[0]->multiselectCstm->values);
$this->assertNotContains('gg' , $account[0]->multiselectCstm->values);
$this->assertNotContains('hh' , $account[0]->multiselectCstm->values);
$this->assertNotContains('rr' , $account[0]->multiselectCstm->values);
$this->assertEquals(1 , $account[0]->tagcloudCstm->values->count());
$this->assertContains('writing' , $account[0]->tagcloudCstm->values);
}
/**
* @depends testMultiValueCustomFieldContentAfterCreateAndEditPlacedForAccountsModule
*/
public function testMassUpdateForMultiSelectFieldPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
$account = Account::getByName('myEditAccount');
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name, 'myEditAccount');
$this->assertContains('gg' , $account[0]->multiselectCstm->values);
$this->assertContains('hh' , $account[0]->multiselectCstm->values);
unset($account);
$secondAccount = Account::getByName('mySecondAccount');
$this->assertEquals(1, count($secondAccount));
$this->assertEquals($secondAccount[0]->name, 'mySecondAccount');
$this->assertContains('gg' , $secondAccount[0]->multiselectCstm->values);
$this->assertContains('ff' , $secondAccount[0]->multiselectCstm->values);
unset($secondAccount);
$this->resetPostArray();
$this->setGetArray(array('selectAll' => '1', 'Account_page' => '1', 'selectedIds' => null, 'ajax' => null));
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/massEdit');
$this->setPostArray(array('save' => 'Save',
'MassEdit' => array('multiselectCstm' => '1'),
'Account' => array('multiselectCstm' => array('values' => array('ff', 'rr')))
)
);
$this->runControllerWithRedirectExceptionAndGetContent('accounts/default/massEdit');
$account = Account::getByName('myEditAccount');
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name, 'myEditAccount');
$this->assertContains('ff' , $account[0]->multiselectCstm->values);
$this->assertContains('rr' , $account[0]->multiselectCstm->values);
$secondAccount = Account::getByName('mySecondAccount');
$this->assertEquals(1, count($secondAccount));
$this->assertEquals($secondAccount[0]->name, 'mySecondAccount');
$this->assertContains('ff' , $secondAccount[0]->multiselectCstm->values);
$this->assertContains('rr' , $secondAccount[0]->multiselectCstm->values);
}
/**
* @depends testMassUpdateForMultiSelectFieldPlacedForAccountsModule
*/
public function testMassUpdateForTagCloudFieldPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
$account = Account::getByName('myEditAccount');
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name, 'myEditAccount');
$this->assertContains('reading' , $account[0]->tagcloudCstm->values);
$this->assertContains('surfing' , $account[0]->tagcloudCstm->values);
unset($account);
$secondAccount = Account::getByName('mySecondAccount');
$this->assertEquals(1, count($secondAccount));
$this->assertEquals($secondAccount[0]->name, 'mySecondAccount');
$this->assertContains('reading' , $secondAccount[0]->tagcloudCstm->values);
$this->assertContains('writing' , $secondAccount[0]->tagcloudCstm->values);
unset($secondAccount);
$this->resetPostArray();
$this->setGetArray(array('selectAll' => '1', 'Account_page' => '1', 'selectedIds' => null, 'ajax' => null));
$this->runControllerWithNoExceptionsAndGetContent('accounts/default/massEdit');
$this->setPostArray(array('save' => 'Save',
'MassEdit' => array('tagcloudCstm' => '1'),
'Account' => array('tagcloudCstm' => array('values' => array('writing', 'gardening')))
)
);
$this->runControllerWithRedirectExceptionAndGetContent('accounts/default/massEdit');
$account = Account::getByName('myEditAccount');
$this->assertEquals(1, count($account));
$this->assertEquals($account[0]->name, 'myEditAccount');
$this->assertContains('writing' , $account[0]->tagcloudCstm->values);
$this->assertContains('gardening' , $account[0]->tagcloudCstm->values);
$secondAccount = Account::getByName('mySecondAccount');
$this->assertEquals(1, count($secondAccount));
$this->assertEquals($secondAccount[0]->name, 'mySecondAccount');
$this->assertContains('writing' , $secondAccount[0]->tagcloudCstm->values);
$this->assertContains('gardening' , $secondAccount[0]->tagcloudCstm->values);
}
/**
* @depends testMassUpdateForTagCloudFieldPlacedForAccountsModule
*/
public function testDeleteOfTheAccountUserForTheCustomFieldsPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Get the account id from the recently edited account.
$accountId = self::getModelIdByModelNameAndName('Account', 'myEditAccount');
//Set the account id so as to delete the account.
$this->setGetArray(array('id' => $accountId));
$this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/delete');
//Check whether the account is deleted.
$account = Account::getByName('myEditAccount');
$this->assertEquals(0, count($account));
}
/**
* @depends testDeleteOfTheAccountUserForTheCustomFieldsPlacedForAccountsModule
*/
public function testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleAfterDeletingTheAccount()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Search a created account using the customfield.
$this->resetGetArray();
$this->setGetArray(array(
'AccountsSearchForm' => AccountsDesignerWalkthroughHelperUtil::fetchAccountsSearchFormGetData(),
'ajax' => 'list-view')
);
$content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default');
//Assert that the edit account does not exits after the search.
$this->assertContains("No results found", $content);
$this->assertNotContains("26378 South Arlington Ave", $content);
}
/**
* @depends testWhetherSearchWorksForTheCustomFieldsPlacedForAccountsModuleAfterDeletingTheAccount
*/
public function testTypeAheadWorksForTheTagCloudFieldPlacedForAccountsModule()
{
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Search a list item by typing in tag cloud attribute.
$this->resetPostArray();
$this->setGetArray(array('name' => 'tagcloud',
'term' => 'rea'));
$content = $this->runControllerWithNoExceptionsAndGetContent('zurmo/default/autoCompleteCustomFieldData');
//Check if the returned content contains the expected vlaue
$this->assertContains("reading", $content);
}
/**
* @depends testTypeAheadWorksForTheTagCloudFieldPlacedForAccountsModule
*/
public function testLabelLocalizationForTheTagCloudFieldPlacedForAccountsModule()
{
Yii::app()->user->userModel = User::getByUsername('super');
$languageHelper = new ZurmoLanguageHelper();
$languageHelper->load();
$this->assertEquals('en', $languageHelper->getForCurrentUser());
Yii::app()->user->userModel->language = 'fr';
$this->assertTrue(Yii::app()->user->userModel->save());
$languageHelper->setActive('fr');
$this->assertEquals('fr', Yii::app()->user->getState('language'));
$super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
//Search a list item by typing in tag cloud attribute.
$this->resetPostArray();
$this->setGetArray(array('name' => 'tagcloud',
'term' => 'surf'));
$content = $this->runControllerWithNoExceptionsAndGetContent('zurmo/default/autoCompleteCustomFieldData');
//Check if the returned content contains the expected vlaue
$this->assertContains("surfing fr", $content);
}
}
?> | agpl-3.0 |
pruthvirajsinh/prlpks | build/src/github.com/pruthvirajsinh/go-Simap/README.md | 3422 | go-Simap
========
A simple Imap client which
--Fetches,Copies,Moves emails from mailboxes.
--Creates,Deletes Mboxes/Folders on the Server.
--Marks,Unmarks Imap Flags from the mails.
--Can Skip Certificate Verification of the IMAP Server. (Good for IMAP servers using SelfSigned Cerificates.)
Also outputs JSON of emails stored on Imap server.
It is based on https://github.com/sqs/go-synco
Following is a command line based example to Show usage of the package.
```go
package main
import (
"flag"
"fmt"
"github.com/pruthvirajsinh/go-Simap/Simap"
"os"
"strconv"
)
var query = flag.String("query", "after:2012/09/12", "query to limit fetch")
var mbox = flag.String("mbox", "inbox", "name of mail box/folder from which you want to get mail")
var destBox = flag.String("dbox", "", "name of mail box/folder where you want to move mail")
var jobSize = flag.Int("jobsize", 2, "Number of Emails to be processed at a time")
var move = flag.Bool("move", false, "Weateher to move or copy the mails while dbox is given")
var del = flag.Bool("delete", false, "Just Delete the fetched mails.Just to check Delete Functionality.")
var skipCerti = flag.Bool("skipCerti", false, "If your IMAP server uses self signed certi then make this true to skip Certification verification.")
var imapFlag = flag.String("imapflag", "", "Flag the emails")
func usage() {
fmt.Fprintf(os.Stderr, "usage: main [server] [port] [username] [password]\n")
flag.PrintDefaults()
os.Exit(2)
}
//Example
//To Copy all the Read mails since 1st,April 2014 fom inbox to processed.
//./main --skipCerti=false --query="SINCE 01-APR-2014 SEEN" --mbox=inbox --dbox=processed imap.gmail.com 993 [email protected] supersecretpassword
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) != 4 {
usage()
}
portI, _ := strconv.Atoi(args[1])
port := uint16(portI)
server := &Simap.IMAPServer{args[0], port}
acct := &Simap.IMAPAccount{args[2], args[3], server}
mails, err := Simap.GetEMails(acct, *query, *mbox, *jobSize, *skipCerti)
if err != nil {
fmt.Println("Error while Getting mails ", err)
return
}
var uids []uint32
fmt.Println("Fetched Mails ", len(mails))
fmt.Println("UID | From | To | Subject |Body | HTMLBODY |GPGBody")
for _, msg := range mails {
//PRocess Emails here
errP := processEmail(msg)
if errP != nil {
continue
}
//If successfull then append them to be moved to processed
uids = append(uids, msg.Imap_uid)
}
if *imapFlag != "" {
err = Simap.MarkEmails(acct, *mbox, *imapFlag, uids, *jobSize, *skipCerti)
if err != nil {
fmt.Println("Main : Error while Marking ", err)
}
}
if *del == true {
err = Simap.DeleteEmails(acct, *mbox, uids, *jobSize, *skipCerti)
if err != nil {
fmt.Println("Main : Error while Deleting ", err)
}
return
}
if *destBox != "" {
if *move == true {
err = Simap.MoveEmails(acct, *mbox, *destBox, uids, *jobSize, *skipCerti)
if err != nil {
fmt.Println("Eror while moving ", err)
}
} else {
err = Simap.CopyEmails(acct, *mbox, *destBox, uids, *jobSize, *skipCerti)
if err != nil {
fmt.Println("Eror while Copying ", err)
}
}
}
}
func processEmail(msg Simap.MsgData) (err error) {
fmt.Println("[" + strconv.Itoa(int(msg.Imap_uid)) + "] | " + msg.From + " | " + msg.To + " | " + msg.Subject + " | " +
msg.Body + " | " + msg.HtmlBody + " | " + msg.GpgBody)
return
}
```
| agpl-3.0 |
eduNEXT/edunext-ecommerce | ecommerce/static/js/test/specs/collections/catalog_collection_spec.js | 924 | define([
'collections/catalog_collection',
'test/mock_data/catalogs'
],
function(CatalogCollection,
MockCatalogs) {
'use strict';
var collection,
response = MockCatalogs;
beforeEach(function() {
collection = new CatalogCollection();
});
describe('Catalog collection', function() {
describe('parse', function() {
it('should fetch the next page of results', function() {
spyOn(collection, 'fetch').and.returnValue(null);
response.next = '/api/v2/catalogs/course_catalogs/?page=2';
collection.parse(response);
expect(collection.fetch).toHaveBeenCalledWith(
{remove: false, url: '/api/v2/catalogs/course_catalogs/?page=2'}
);
});
});
});
}
);
| agpl-3.0 |
annando/friendica | tests/src/Module/Api/Friendica/Photoalbum/UpdateTest.php | 2675 | <?php
/**
* @copyright Copyright (C) 2010-2022, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Module\Api\Friendica\Photoalbum;
use Friendica\App\Router;
use Friendica\DI;
use Friendica\Module\Api\Friendica\Photoalbum\Update;
use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Test\src\Module\Api\ApiTest;
class UpdateTest extends ApiTest
{
protected function setUp(): void
{
parent::setUp();
$this->useHttpMethod(Router::POST);
}
public function testEmpty()
{
$this->expectException(BadRequestException::class);
(new Update(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))
->run();
}
public function testTooFewArgs()
{
$this->expectException(BadRequestException::class);
(new Update(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))
->run([
'album' => 'album_name'
]);
}
public function testWrongUpdate()
{
$this->expectException(BadRequestException::class);
(new Update(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))
->run([
'album' => 'album_name',
'album_new' => 'album_name'
]);
}
public function testWithoutAuthenticatedUser()
{
self::markTestIncomplete('Needs BasicAuth as dynamic method for overriding first');
}
public function testValid()
{
$this->loadFixture(__DIR__ . '/../../../../../datasets/photo/photo.fixture.php', DI::dba());
$response = (new Update(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))
->run([
'album' => 'test_album',
'album_new' => 'test_album_2'
]);
$json = $this->toJson($response);
self::assertEquals('updated', $json->result);
self::assertEquals('album `test_album` with all containing photos has been renamed to `test_album_2`.', $json->message);
}
}
| agpl-3.0 |
hltn/opencps | themes/opencps-ux-theme/docroot/css/portlets/portlet_6.css | 5594 | .opencps-theme.ux .opencps-accountinfo-wrapper {
margin: 25px auto 0;
width: 100%;
background-color: white;
border-radius: 8px;
-webkit-box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, 0.2);
box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, 0.2);
padding: 15px 0 0
}
.opencps-theme.ux .opencps-accountinfo-wrapper .header {
border-bottom: 1px solid #e1e1e1;
padding: 0 30px
}
.opencps-theme.ux .opencps-accountinfo-wrapper .header p {
background: url(../images/custom/icon_thongtintaikhoan_blue.png) 0
center no-repeat;
padding-left: 20px;
text-transform: uppercase;
font-family: 'Roboto-Bold';
font-size: 18px;
line-height: 60px;
margin-bottom: 0
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left {
padding: 30px 50px 20px 30px;
display: inline-block;
vertical-align: top;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right {
padding: 30px 30px 20px;
display: inline-block;
vertical-align: top;
}
@media screen and (min-width: 760px) {
.opencps-theme.ux .opencps-accountinfo-wrapper .content {
display: flex;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left {
width: 43%;
border-right: 1px solid #ccc;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right {
width: 44%;
}
}
@media screen and (max-width: 760px) {
.opencps-theme.ux .opencps-accountinfo-wrapper .content {
display: block;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left {
width: 85%;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right {
width: 85%;
}
}
.account_info .row-fluid .span6 .box_scroll {
overflow: auto;
display: -webkit-box;
left: 0;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div {
position: relative;
margin-bottom: 20px
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div img {
float: left;
margin-right: 30px;
width: 80px;
height: 80px
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div p,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div p {
font-family: 'Roboto-Bold';
margin-bottom: 0;
position: relative;
text-transform: uppercase;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div .change_avatar
{
margin-top: 20px;
float: left;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div .name
{
text-transform: uppercase;
margin: 0 0 5px
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div a,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div a {
color: #0090ff !important
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div a.fix_avatar
{
top: 20px !important
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div a.fix,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div a.fix
{
position: absolute;
right: 0;
padding-left: 20px;
background: url(../images/custom/icon_edit_blue.png) 0 center no-repeat;
top: 0
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div a.add,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div a.add
{
position: absolute;
right: 0;
padding-left: 20px;
background: url(../images/custom/icon_dangnhap_hover.png) 0 center
no-repeat;
top: 0
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div p span
{
display: inline-block;
width: 110px;
font-family: 'Roboto-Regular'
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div p span
{
display: inline-block;
width: 130px;
font-family: 'Roboto-Regular'
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div button,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div button
{
color: white;
text-transform: uppercase;
background-color: #0090ff;
border: 0;
border-radius: 20px;
padding: 5px 15px;
position: absolute;
top: -5px;
right: 20px
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div a.fixing,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div a.fixing
{
background: none;
position: absolute;
right: 0;
top: 0;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div p input,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div p input
{
border: 0;
box-shadow: none;
padding: 0;
margin-bottom: 0
}
.opencps-theme.ux .opencps-accountinfo-wrapper .content .left>div p input:focus,
.opencps-theme.ux .opencps-accountinfo-wrapper .content .right>div p input:focus
{
outline: 1px solid #0090ff;
outline-color: rgba(7, 140, 244, 0.3);
}
.opencps-theme.ux .opencps-accountinfo-wrapper.account_company .left>div p span
{
width: 150px
}
.opencps-theme.ux .opencps-accountinfo-wrapper.account_company .right {
padding-top: 20px
}
.opencps-theme.ux .opencps-accountinfo-wrapper div>p>label {
display: inline-table;
width: 230px;
margin: 0
}
.opencps-theme.ux .opencps-accountinfo-wrapper.account_company .left>div>p>label span
{
padding-left: 20px;
background: url(../images/icon_checked.png) 0 center no-repeat;
font-family: 'Roboto-Bold';
margin-bottom: 10px
}
.opencps-theme.ux .opencps-accountinfo-wrapper.account_company .left>div>p>label span:last-child
{
margin-bottom: 0
}
.opencps-theme.ux .opencps-accountinfo-wrapper .box_scroll {
border: 1px solid #e1e1e1;
border-radius: 4px;
padding: 5px 15px;
height: 90px;
overflow: auto;
position: relative;
left: 150px;
display: inline-block;
}
.opencps-theme.ux .opencps-accountinfo-wrapper .fix_topleft {
position: absolute;
top: 0;
left: 0
} | agpl-3.0 |
jbruestle/aggregate_btree | tiny_boost/boost/mpl/aux_/preprocessed/no_ctps/quote.hpp | 2290 |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/quote.hpp" header
// -- DO NOT modify by hand!
namespace abt_boost{} namespace boost = abt_boost; namespace abt_boost{ namespace mpl {
template< bool > struct quote_impl
{
template< typename T > struct result_
: T
{
};
};
template<> struct quote_impl<false>
{
template< typename T > struct result_
{
typedef T type;
};
};
template<
template< typename P1 > class F
, typename Tag = void_
>
struct quote1
{
template< typename U1 > struct apply
: quote_impl< aux::has_type< F<U1> >::value >
::template result_< F<U1> >
{
};
};
template<
template< typename P1, typename P2 > class F
, typename Tag = void_
>
struct quote2
{
template< typename U1, typename U2 > struct apply
: quote_impl< aux::has_type< F< U1,U2 > >::value >
::template result_< F< U1,U2 > >
{
};
};
template<
template< typename P1, typename P2, typename P3 > class F
, typename Tag = void_
>
struct quote3
{
template< typename U1, typename U2, typename U3 > struct apply
: quote_impl< aux::has_type< F< U1,U2,U3 > >::value >
::template result_< F< U1,U2,U3 > >
{
};
};
template<
template< typename P1, typename P2, typename P3, typename P4 > class F
, typename Tag = void_
>
struct quote4
{
template<
typename U1, typename U2, typename U3, typename U4
>
struct apply
: quote_impl< aux::has_type< F< U1,U2,U3,U4 > >::value >
::template result_< F< U1,U2,U3,U4 > >
{
};
};
template<
template<
typename P1, typename P2, typename P3, typename P4
, typename P5
>
class F
, typename Tag = void_
>
struct quote5
{
template<
typename U1, typename U2, typename U3, typename U4
, typename U5
>
struct apply
: quote_impl< aux::has_type< F< U1,U2,U3,U4,U5 > >::value >
::template result_< F< U1,U2,U3,U4,U5 > >
{
};
};
}}
| agpl-3.0 |
madd15/snipe-it | resources/views/hardware/index.blade.php | 3507 | @extends('layouts/default')
@section('title0')
@if ((Input::get('company_id')) && ($company))
{{ $company->name }}
@endif
@if (Input::get('status'))
@if (Input::get('status')=='Pending')
{{ trans('general.pending') }}
@elseif (Input::get('status')=='RTD')
{{ trans('general.ready_to_deploy') }}
@elseif (Input::get('status')=='Deployed')
{{ trans('general.deployed') }}
@elseif (Input::get('status')=='Undeployable')
{{ trans('general.undeployable') }}
@elseif (Input::get('status')=='Deployable')
{{ trans('general.deployed') }}
@elseif (Input::get('status')=='Requestable')
{{ trans('admin/hardware/general.requestable') }}
@elseif (Input::get('status')=='Archived')
{{ trans('general.archived') }}
@elseif (Input::get('status')=='Deleted')
{{ trans('general.deleted') }}
@endif
@else
{{ trans('general.all') }}
@endif
{{ trans('general.assets') }}
@if (Input::has('order_number'))
: Order #{{ Input::get('order_number') }}
@endif
@stop
{{-- Page title --}}
@section('title')
@yield('title0') @parent
@stop
@section('header_right')
<a href="{{ route('reports.export.assets', ['status'=> e(Input::get('status'))]) }}" style="margin-right: 5px;" class="btn btn-default"><i class="fa fa-download icon-white"></i>
{{ trans('admin/hardware/table.dl_csv') }}</a>
<a href="{{ route('hardware.create') }}" class="btn btn-primary pull-right"></i> {{ trans('general.create') }}</a>
@stop
{{-- Page content --}}
@section('content')
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-body">
{{ Form::open([
'method' => 'POST',
'route' => ['hardware/bulkedit'],
'class' => 'form-inline',
'id' => 'bulkForm']) }}
<div class="row">
<div class="col-md-12">
@if (Input::get('status')!='Deleted')
<div id="toolbar">
<select name="bulk_actions" class="form-control select2">
<option value="edit">Edit</option>
<option value="delete">Delete</option>
<option value="labels">Generate Labels</option>
</select>
<button class="btn btn-primary" id="bulkEdit" disabled>Go</button>
</div>
@endif
<table
name="assets"
{{-- data-row-style="rowStyle" --}}
data-toolbar="#toolbar"
class="table table-striped snipe-table"
id="table"
data-advanced-search="true"
data-id-table="advancedTable"
data-url="{{ route('api.assets.index',
array('status' => e(Input::get('status')),
'order_number'=>e(Input::get('order_number')),
'company_id'=>e(Input::get('company_id')),
'status_id'=>e(Input::get('status_id'))))}}"
data-click-to-select="true"
data-cookie-id-table="{{ e(Input::get('status')) }}assetTable-{{ config('version.hash_version') }}">
</table>
</div><!-- /.col -->
</div><!-- /.row -->
{{ Form::close() }}
</div><!-- ./box-body -->
</div><!-- /.box -->
</div>
</div>
@stop
@section('moar_scripts')
@include ('partials.bootstrap-table', [
'exportFile' => 'assets-export',
'search' => true,
'showFooter' => true,
'columns' => \App\Presenters\AssetPresenter::dataTableLayout()
])
@stop
| agpl-3.0 |
KnzkDev/mastodon | CONTRIBUTING.md | 1688 | Contributing
============
Thank you for considering contributing to Mastodon 🐘
You can contribute in the following ways:
- Finding and reporting bugs
- Translating the Mastodon interface into various languages
- Contributing code to Mastodon by fixing bugs or implementing features
- Improving the documentation
If your contributions are accepted into Mastodon, you can request to be paid through [our OpenCollective](https://opencollective.com/mastodon).
## Bug reports
Bug reports and feature suggestions can be submitted to [GitHub Issues](https://github.com/tootsuite/mastodon/issues). Please make sure that you are not submitting duplicates, and that a similar report or request has not already been resolved or rejected in the past using the search function. Please also use descriptive, concise titles.
## Translations
You can submit translations via pull request.
## Pull requests
Please use clean, concise titles for your pull requests. We use commit squashing, so the final commit in the master branch will carry the title of the pull request.
The smaller the set of changes in the pull request is, the quicker it can be reviewed and merged. Splitting tasks into multiple smaller pull requests is often preferable.
**Pull requests that do not pass automated checks may not be reviewed**. In particular, you need to keep in mind:
- Unit and integration tests (rspec, jest)
- Code style rules (rubocop, eslint)
- Normalization of locale files (i18n-tasks)
## Documentation
The [Mastodon documentation](https://docs.joinmastodon.org) is a statically generated site. You can [submit merge requests to mastodon/docs](https://source.joinmastodon.org/mastodon/docs).
| agpl-3.0 |
MarStan/sugar_work | modules/OfficeReportsHistory/metadata/metafiles.php | 581 | <?php
$module_name = 'OfficeReportsHistory';
$metafiles[$module_name] = array(
'detailviewdefs' => 'modules/' . $module_name . '/metadata/detailviewdefs.php',
'editviewdefs' => 'modules/' . $module_name . '/metadata/editviewdefs.php',
'listviewdefs' => 'modules/' . $module_name . '/metadata/listviewdefs.php',
'searchdefs' => 'modules/' . $module_name . '/metadata/searchdefs.php',
'popupdefs' => 'modules/' . $module_name . '/metadata/popupdefs.php',
'searchfields' => 'modules/' . $module_name . '/metadata/SearchFields.php',
);
?>
| agpl-3.0 |
ibamacsr/casv | casv/core/migrations/0002_areasoltura.py | 2089 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='AreaSoltura',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),
('processo', models.IntegerField()),
('nome', models.CharField(verbose_name='Nome da propriedade', max_length=255)),
('endereco', models.CharField(verbose_name='Endereço', max_length=400)),
('municipio', models.CharField(verbose_name='Município', max_length=255)),
('uf', models.CharField(verbose_name='Unidade da Federação', max_length=2)),
('proprietario', models.CharField(verbose_name='Nome do proprietário', max_length=255)),
('cpf', models.IntegerField(verbose_name='CPF')),
('telefone', models.BigIntegerField()),
('email', models.EmailField(max_length=254)),
('area', models.FloatField(verbose_name='Área da Propriedade (ha)')),
('arl_app', models.FloatField(verbose_name='Área de reserva legal e proteção permanente')),
('bioma', models.CharField(verbose_name='Bioma', max_length=255)),
('fitofisionomia', models.CharField(max_length=255)),
('atividade', models.CharField(verbose_name='Atividade Econômica', max_length=255)),
('viveiro', models.IntegerField(verbose_name='Número de viveiros')),
('distancia', models.FloatField(verbose_name='Área da Propriedade (ha)')),
('tempo', models.FloatField(verbose_name='Tempo de viagem ao CETAS mais próximo')),
('vistoria', models.DateField()),
('geom', django.contrib.gis.db.models.fields.PolygonField(srid=4674)),
],
),
]
| agpl-3.0 |
pipauwel/IfcDoc | IfcKit/schemas/IfcKernel/IfcRelConnects.cs | 866 | // This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using BuildingSmart.IFC.IfcMeasureResource;
using BuildingSmart.IFC.IfcUtilityResource;
namespace BuildingSmart.IFC.IfcKernel
{
public abstract partial class IfcRelConnects : IfcRelationship
{
protected IfcRelConnects(IfcGloballyUniqueId __GlobalId, IfcOwnerHistory __OwnerHistory, IfcLabel? __Name, IfcText? __Description)
: base(__GlobalId, __OwnerHistory, __Name, __Description)
{
}
}
}
| agpl-3.0 |
fluks/mupdf-x11-bookmarks | source/fitz/load-bmp.c | 28370 | #include "mupdf/fitz.h"
#include <string.h>
#include <limits.h>
static const unsigned char web_palette[] = {
0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x66, 0x00, 0x00, 0x99, 0x00, 0x00, 0xCC, 0x00, 0x00, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x33, 0x33, 0x00, 0x33, 0x66, 0x00, 0x33, 0x99, 0x00, 0x33, 0xCC, 0x00, 0x33, 0xFF, 0x00, 0x33,
0x00, 0x00, 0x66, 0x33, 0x00, 0x66, 0x66, 0x00, 0x66, 0x99, 0x00, 0x66, 0xCC, 0x00, 0x66, 0xFF, 0x00, 0x66,
0x00, 0x00, 0x99, 0x33, 0x00, 0x99, 0x66, 0x00, 0x99, 0x99, 0x00, 0x99, 0xCC, 0x00, 0x99, 0xFF, 0x00, 0x99,
0x00, 0x00, 0xCC, 0x33, 0x00, 0xCC, 0x66, 0x00, 0xCC, 0x99, 0x00, 0xCC, 0xCC, 0x00, 0xCC, 0xFF, 0x00, 0xCC,
0x00, 0x00, 0xFF, 0x33, 0x00, 0xFF, 0x66, 0x00, 0xFF, 0x99, 0x00, 0xFF, 0xCC, 0x00, 0xFF, 0xFF, 0x00, 0xFF,
0x00, 0x33, 0x00, 0x33, 0x33, 0x00, 0x66, 0x33, 0x00, 0x99, 0x33, 0x00, 0xCC, 0x33, 0x00, 0xFF, 0x33, 0x00,
0x00, 0x33, 0x33, 0x33, 0x33, 0x33, 0x66, 0x33, 0x33, 0x99, 0x33, 0x33, 0xCC, 0x33, 0x33, 0xFF, 0x33, 0x33,
0x00, 0x33, 0x66, 0x33, 0x33, 0x66, 0x66, 0x33, 0x66, 0x99, 0x33, 0x66, 0xCC, 0x33, 0x66, 0xFF, 0x33, 0x66,
0x00, 0x33, 0x99, 0x33, 0x33, 0x99, 0x66, 0x33, 0x99, 0x99, 0x33, 0x99, 0xCC, 0x33, 0x99, 0xFF, 0x33, 0x99,
0x00, 0x33, 0xCC, 0x33, 0x33, 0xCC, 0x66, 0x33, 0xCC, 0x99, 0x33, 0xCC, 0xCC, 0x33, 0xCC, 0xFF, 0x33, 0xCC,
0x00, 0x33, 0xFF, 0x33, 0x33, 0xFF, 0x66, 0x33, 0xFF, 0x99, 0x33, 0xFF, 0xCC, 0x33, 0xFF, 0xFF, 0x33, 0xFF,
0x00, 0x66, 0x00, 0x33, 0x66, 0x00, 0x66, 0x66, 0x00, 0x99, 0x66, 0x00, 0xCC, 0x66, 0x00, 0xFF, 0x66, 0x00,
0x00, 0x66, 0x33, 0x33, 0x66, 0x33, 0x66, 0x66, 0x33, 0x99, 0x66, 0x33, 0xCC, 0x66, 0x33, 0xFF, 0x66, 0x33,
0x00, 0x66, 0x66, 0x33, 0x66, 0x66, 0x66, 0x66, 0x66, 0x99, 0x66, 0x66, 0xCC, 0x66, 0x66, 0xFF, 0x66, 0x66,
0x00, 0x66, 0x99, 0x33, 0x66, 0x99, 0x66, 0x66, 0x99, 0x99, 0x66, 0x99, 0xCC, 0x66, 0x99, 0xFF, 0x66, 0x99,
0x00, 0x66, 0xCC, 0x33, 0x66, 0xCC, 0x66, 0x66, 0xCC, 0x99, 0x66, 0xCC, 0xCC, 0x66, 0xCC, 0xFF, 0x66, 0xCC,
0x00, 0x66, 0xFF, 0x33, 0x66, 0xFF, 0x66, 0x66, 0xFF, 0x99, 0x66, 0xFF, 0xCC, 0x66, 0xFF, 0xFF, 0x66, 0xFF,
0x00, 0x99, 0x00, 0x33, 0x99, 0x00, 0x66, 0x99, 0x00, 0x99, 0x99, 0x00, 0xCC, 0x99, 0x00, 0xFF, 0x99, 0x00,
0x00, 0x99, 0x33, 0x33, 0x99, 0x33, 0x66, 0x99, 0x33, 0x99, 0x99, 0x33, 0xCC, 0x99, 0x33, 0xFF, 0x99, 0x33,
0x00, 0x99, 0x66, 0x33, 0x99, 0x66, 0x66, 0x99, 0x66, 0x99, 0x99, 0x66, 0xCC, 0x99, 0x66, 0xFF, 0x99, 0x66,
0x00, 0x99, 0x99, 0x33, 0x99, 0x99, 0x66, 0x99, 0x99, 0x99, 0x99, 0x99, 0xCC, 0x99, 0x99, 0xFF, 0x99, 0x99,
0x00, 0x99, 0xCC, 0x33, 0x99, 0xCC, 0x66, 0x99, 0xCC, 0x99, 0x99, 0xCC, 0xCC, 0x99, 0xCC, 0xFF, 0x99, 0xCC,
0x00, 0x99, 0xFF, 0x33, 0x99, 0xFF, 0x66, 0x99, 0xFF, 0x99, 0x99, 0xFF, 0xCC, 0x99, 0xFF, 0xFF, 0x99, 0xFF,
0x00, 0xCC, 0x00, 0x33, 0xCC, 0x00, 0x66, 0xCC, 0x00, 0x99, 0xCC, 0x00, 0xCC, 0xCC, 0x00, 0xFF, 0xCC, 0x00,
0x00, 0xCC, 0x33, 0x33, 0xCC, 0x33, 0x66, 0xCC, 0x33, 0x99, 0xCC, 0x33, 0xCC, 0xCC, 0x33, 0xFF, 0xCC, 0x33,
0x00, 0xCC, 0x66, 0x33, 0xCC, 0x66, 0x66, 0xCC, 0x66, 0x99, 0xCC, 0x66, 0xCC, 0xCC, 0x66, 0xFF, 0xCC, 0x66,
0x00, 0xCC, 0x99, 0x33, 0xCC, 0x99, 0x66, 0xCC, 0x99, 0x99, 0xCC, 0x99, 0xCC, 0xCC, 0x99, 0xFF, 0xCC, 0x99,
0x00, 0xCC, 0xCC, 0x33, 0xCC, 0xCC, 0x66, 0xCC, 0xCC, 0x99, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xFF, 0xCC, 0xCC,
0x00, 0xCC, 0xFF, 0x33, 0xCC, 0xFF, 0x66, 0xCC, 0xFF, 0x99, 0xCC, 0xFF, 0xCC, 0xCC, 0xFF, 0xFF, 0xCC, 0xFF,
0x00, 0xFF, 0x00, 0x33, 0xFF, 0x00, 0x66, 0xFF, 0x00, 0x99, 0xFF, 0x00, 0xCC, 0xFF, 0x00, 0xFF, 0xFF, 0x00,
0x00, 0xFF, 0x33, 0x33, 0xFF, 0x33, 0x66, 0xFF, 0x33, 0x99, 0xFF, 0x33, 0xCC, 0xFF, 0x33, 0xFF, 0xFF, 0x33,
0x00, 0xFF, 0x66, 0x33, 0xFF, 0x66, 0x66, 0xFF, 0x66, 0x99, 0xFF, 0x66, 0xCC, 0xFF, 0x66, 0xFF, 0xFF, 0x66,
0x00, 0xFF, 0x99, 0x33, 0xFF, 0x99, 0x66, 0xFF, 0x99, 0x99, 0xFF, 0x99, 0xCC, 0xFF, 0x99, 0xFF, 0xFF, 0x99,
0x00, 0xFF, 0xCC, 0x33, 0xFF, 0xCC, 0x66, 0xFF, 0xCC, 0x99, 0xFF, 0xCC, 0xCC, 0xFF, 0xCC, 0xFF, 0xFF, 0xCC,
0x00, 0xFF, 0xFF, 0x33, 0xFF, 0xFF, 0x66, 0xFF, 0xFF, 0x99, 0xFF, 0xFF, 0xCC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
static const unsigned char vga_palette[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x00, 0xAA, 0x00, 0x00, 0xAA, 0xAA,
0xAA, 0x00, 0x00, 0xAA, 0x00, 0xAA, 0xAA, 0x55, 0x00, 0xAA, 0xAA, 0xAA,
0x55, 0x55, 0x55, 0x55, 0x55, 0xFF, 0x55, 0xFF, 0x55, 0x55, 0xFF, 0xFF,
0xFF, 0x55, 0x55, 0xFF, 0x55, 0xFF, 0xFF, 0xFF, 0x55, 0xFF, 0xFF, 0xFF,
};
static const unsigned char gray_palette[] = {
0x00, 0x00, 0x00, 0x54, 0x54, 0x54,
0xA8, 0xA8, 0xA8, 0xFF, 0xFF, 0xFF,
};
static const unsigned char bw_palette[] = {
0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF,
};
enum {
BI_RLE24 = -1,
BI_RGB = 0,
BI_RLE8 = 1,
BI_RLE4 = 2,
BI_BITFIELDS = 3,
BI_JPEG = 4,
BI_PNG = 5,
BI_ALPHABITS = 6,
BI_UNSUPPORTED = 42,
};
struct info
{
int filesize;
int offset;
int topdown;
int width, height;
int xres, yres;
int bitcount;
int compression;
int colors;
int rmask, gmask, bmask, amask;
unsigned char palette[256 * 3];
int extramasks;
int palettetype;
unsigned char *samples;
int rshift, gshift, bshift, ashift;
int rbits, gbits, bbits, abits;
};
#define read8(p) ((p)[0])
#define read16(p) (((p)[1] << 8) | (p)[0])
#define read32(p) (((p)[3] << 24) | ((p)[2] << 16) | ((p)[1] << 8) | (p)[0])
static const unsigned char *
bmp_read_file_header(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char *end)
{
if (end - p < 14)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in file header in bmp image");
if (memcmp(&p[0], "BM", 2))
fz_throw(ctx, FZ_ERROR_GENERIC, "invalid signature in bmp image");
info->filesize = read32(p + 2);
info->offset = read32(p + 10);
return p + 14;
}
static const unsigned char *
bmp_read_bitmap_core_header(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char *end)
{
int size;
size = read32(p + 0);
if (size != 12)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported core header size in bmp image");
if (size >= 12)
{
if (end - p < 12)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap core header in bmp image");
info->width = read16(p + 4);
info->height = read16(p + 6);
info->bitcount = read16(p + 10);
}
info->xres = 2835;
info->yres = 2835;
info->compression = BI_RGB;
info->palettetype = 0;
return p + size;
}
static const unsigned char *
bmp_read_bitmap_os2_header(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char *end)
{
int size;
size = read32(p + 0);
if (size != 16 && size != 64)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported os2 header size in bmp image");
if (size >= 16)
{
if (end - p < 16)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap os2 header in bmp image");
info->width = read32(p + 4);
info->height = read32(p + 8);
info->bitcount = read16(p + 14);
info->compression = BI_RGB;
}
if (size >= 64)
{
if (end - p < 64)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap os2 header in bmp image");
info->compression = read32(p + 16);
info->xres = read32(p + 24);
info->yres = read32(p + 28);
info->colors = read32(p + 32);
/* 4 in this header is interpreted as 24 bit RLE encoding */
if (info->compression < 0)
info->compression = BI_UNSUPPORTED;
else if (info->compression == 4)
info->compression = BI_RLE24;
}
info->palettetype = 1;
return p + size;
}
static void maskinfo(unsigned int mask, int *shift, int *bits)
{
*bits = 0;
*shift = 0;
if (mask) {
while ((mask & 1) == 0) {
*shift += 1;
mask >>= 1;
}
while ((mask & 1) == 1) {
*bits += 1;
mask >>= 1;
}
}
}
static const unsigned char *
bmp_read_bitmap_info_header(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char *end)
{
int size;
size = read32(p + 0);
if (size != 40 && size != 52 && size != 56 && size != 64 &&
size != 108 && size != 124)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported info header size in bmp image");
if (size >= 40)
{
if (end - p < 40)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap info header in bmp image");
info->width = read32(p + 4);
info->topdown = (p[8 + 3] & 0x80) != 0;
if (info->topdown)
info->height = -read32(p + 8);
else
info->height = read32(p + 8);
info->bitcount = read16(p + 14);
info->compression = read32(p + 16);
info->xres = read32(p + 24);
info->yres = read32(p + 28);
info->colors = read32(p + 32);
if (size == 40 && info->compression == BI_BITFIELDS && (info->bitcount == 16 || info->bitcount == 32))
info->extramasks = 1;
else if (size == 40 && info->compression == BI_ALPHABITS && (info->bitcount == 16 || info->bitcount == 32))
info->extramasks = 1;
if (info->bitcount == 16) {
info->rmask = 0x00007c00;
info->gmask = 0x000003e0;
info->bmask = 0x0000001f;
info->amask = 0x00000000;
} else if (info->bitcount == 32) {
info->rmask = 0x00ff0000;
info->gmask = 0x0000ff00;
info->bmask = 0x000000ff;
info->amask = 0x00000000;
}
}
if (size >= 52)
{
if (end - p < 52)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap info header in bmp image");
if (info->compression == BI_BITFIELDS) {
info->rmask = read32(p + 40);
info->gmask = read32(p + 44);
info->bmask = read32(p + 48);
}
}
if (size >= 56)
{
if (end - p < 56)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap info header in bmp image");
if (info->compression == BI_BITFIELDS) {
info->amask = read32(p + 52);
}
}
info->palettetype = 1;
return p + size;
}
static const unsigned char *
bmp_read_extra_masks(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char *end)
{
int size = 0;
if (info->compression == BI_BITFIELDS)
{
size = 12;
if (end - p < 12)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in mask header in bmp image");
info->rmask = read32(p + 0);
info->gmask = read32(p + 4);
info->bmask = read32(p + 8);
}
else if (info->compression == BI_ALPHABITS)
{
size = 16;
if (end - p < 16)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in mask header in bmp image");
/* ignore alpha mask */
info->rmask = read32(p + 0);
info->gmask = read32(p + 4);
info->bmask = read32(p + 8);
}
return p + size;
}
static int
bmp_palette_is_gray(fz_context *ctx, struct info *info, int readcolors)
{
int i;
for (i = 0; i < readcolors; i++)
{
int rgdiff = fz_absi(info->palette[3 * i + 0] - info->palette[3 * i + 1]);
int gbdiff = fz_absi(info->palette[3 * i + 1] - info->palette[3 * i + 2]);
int rbdiff = fz_absi(info->palette[3 * i + 0] - info->palette[3 * i + 2]);
if (rgdiff > 2 || gbdiff > 2 || rbdiff > 2)
return 0;
}
return 1;
}
static void
bmp_load_default_palette(fz_context *ctx, struct info *info, int readcolors)
{
int i;
fz_warn(ctx, "color table too short; loading default palette");
if (info->bitcount == 8)
{
if (!bmp_palette_is_gray(ctx, info, readcolors))
memcpy(&info->palette[readcolors * 3], &web_palette[readcolors * 3],
sizeof(web_palette) - readcolors * 3);
else
for (i = readcolors; i < 256; i++)
{
info->palette[3 * i + 0] = i;
info->palette[3 * i + 1] = i;
info->palette[3 * i + 2] = i;
}
}
else if (info->bitcount == 4)
{
if (!bmp_palette_is_gray(ctx, info, readcolors))
memcpy(&info->palette[readcolors * 3], &vga_palette[readcolors * 3],
sizeof(vga_palette) - readcolors * 3);
else
for (i = readcolors; i < 16; i++)
{
info->palette[3 * i + 0] = (i << 4) | i;
info->palette[3 * i + 1] = (i << 4) | i;
info->palette[3 * i + 2] = (i << 4) | i;
}
}
else if (info->bitcount == 2)
memcpy(info->palette, gray_palette, sizeof(gray_palette));
else if (info->bitcount == 1)
memcpy(info->palette, bw_palette, sizeof(bw_palette));
}
static const unsigned char *
bmp_read_color_table(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char *end)
{
int i, colors, readcolors;
if (info->bitcount > 8)
return p;
if (info->colors == 0)
colors = 1 << info->bitcount;
else
colors = info->colors;
colors = fz_mini(colors, 1 << info->bitcount);
if (info->palettetype == 0)
{
readcolors = fz_mini(colors, (end - p) / 3);
for (i = 0; i < readcolors; i++)
{
info->palette[3 * i + 0] = read8(p + i * 3 + 2);
info->palette[3 * i + 1] = read8(p + i * 3 + 1);
info->palette[3 * i + 2] = read8(p + i * 3 + 0);
}
if (readcolors < colors)
bmp_load_default_palette(ctx, info, readcolors);
return p + readcolors * 3;
}
else
{
readcolors = fz_mini(colors, (end - p) / 4);
for (i = 0; i < readcolors; i++)
{
/* ignore alpha channel */
info->palette[3 * i + 0] = read8(p + i * 4 + 2);
info->palette[3 * i + 1] = read8(p + i * 4 + 1);
info->palette[3 * i + 2] = read8(p + i * 4 + 0);
}
if (readcolors < colors)
bmp_load_default_palette(ctx, info, readcolors);
return p + readcolors * 4;
}
return p;
}
static unsigned char *
bmp_decompress_rle24(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char **end)
{
const unsigned char *sp;
unsigned char *dp, *ep, *decompressed;
int width = info->width;
int height = info->height;
int stride;
int x, i;
stride = (width*3 + 3) / 4 * 4;
sp = p;
dp = decompressed = fz_calloc(ctx, height, stride);
ep = dp + height * stride;
x = 0;
while (sp + 2 <= *end)
{
if (sp[0] == 0 && sp[1] == 0)
{ /* end of line */
if (x*3 < stride)
dp += stride - x*3;
sp += 2;
x = 0;
}
else if (sp[0] == 0 && sp[1] == 1)
{ /* end of bitmap */
dp = ep;
break;
}
else if (sp[0] == 0 && sp[1] == 2)
{ /* delta */
int deltax, deltay;
if (sp + 4 > *end)
break;
deltax = sp[2];
deltay = sp[3];
dp += deltax*3 + deltay * stride;
sp += 4;
x += deltax;
}
else if (sp[0] == 0 && sp[1] >= 3)
{ /* absolute */
int n = sp[1] * 3;
int nn = (n + 1) / 2 * 2;
if (sp + 2 + nn > *end)
break;
if (dp + n > ep) {
fz_warn(ctx, "buffer overflow in bitmap data in bmp image");
break;
}
sp += 2;
for (i = 0; i < n; i++)
dp[i] = sp[i];
dp += n;
sp += (n + 1) / 2 * 2;
x += n;
}
else
{ /* encoded */
int n = sp[0] * 3;
if (sp + 1 + 3 > *end)
break;
if (dp + n > ep) {
fz_warn(ctx, "buffer overflow in bitmap data in bmp image");
break;
}
for (i = 0; i < n / 3; i++) {
dp[i * 3 + 0] = sp[1];
dp[i * 3 + 1] = sp[2];
dp[i * 3 + 2] = sp[3];
}
dp += n;
sp += 1 + 3;
x += n;
}
}
if (dp < ep)
fz_warn(ctx, "premature end of bitmap data in bmp image");
info->compression = BI_RGB;
info->bitcount = 24;
*end = ep;
return decompressed;
}
static unsigned char *
bmp_decompress_rle8(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char **end)
{
const unsigned char *sp;
unsigned char *dp, *ep, *decompressed;
int width = info->width;
int height = info->height;
int stride;
int x, i;
stride = (width + 3) / 4 * 4;
sp = p;
dp = decompressed = fz_calloc(ctx, height, stride);
ep = dp + height * stride;
x = 0;
while (sp + 2 <= *end)
{
if (sp[0] == 0 && sp[1] == 0)
{ /* end of line */
if (x < stride)
dp += stride - x;
sp += 2;
x = 0;
}
else if (sp[0] == 0 && sp[1] == 1)
{ /* end of bitmap */
dp = ep;
break;
}
else if (sp[0] == 0 && sp[1] == 2)
{ /* delta */
int deltax, deltay;
if (sp + 4 > *end)
break;
deltax = sp[2];
deltay = sp[3];
dp += deltax + deltay * stride;
sp += 4;
x += deltax;
}
else if (sp[0] == 0 && sp[1] >= 3)
{ /* absolute */
int n = sp[1];
int nn = (n + 1) / 2 * 2;
if (sp + 2 + nn > *end)
break;
if (dp + n > ep) {
fz_warn(ctx, "buffer overflow in bitmap data in bmp image");
break;
}
sp += 2;
for (i = 0; i < n; i++)
dp[i] = sp[i];
dp += n;
sp += (n + 1) / 2 * 2;
x += n;
}
else
{ /* encoded */
int n = sp[0];
if (dp + n > ep) {
fz_warn(ctx, "buffer overflow in bitmap data in bmp image");
break;
}
for (i = 0; i < n; i++)
dp[i] = sp[1];
dp += n;
sp += 2;
x += n;
}
}
if (dp < ep)
fz_warn(ctx, "premature end of bitmap data in bmp image");
info->compression = BI_RGB;
info->bitcount = 8;
*end = ep;
return decompressed;
}
static unsigned char *
bmp_decompress_rle4(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char **end)
{
const unsigned char *sp;
unsigned char *dp, *ep, *decompressed;
int width = info->width;
int height = info->height;
int stride;
int i, x;
stride = ((width + 1) / 2 + 3) / 4 * 4;
sp = p;
dp = decompressed = fz_calloc(ctx, height, stride);
ep = dp + height * stride;
x = 0;
while (sp + 2 <= *end)
{
if (sp[0] == 0 && sp[1] == 0)
{ /* end of line */
int xx = x / 2;
if (xx < stride)
dp += stride - xx;
sp += 2;
x = 0;
}
else if (sp[0] == 0 && sp[1] == 1)
{ /* end of bitmap */
dp = ep;
break;
}
else if (sp[0] == 0 && sp[1] == 2)
{ /* delta */
int deltax, deltay, startlow;
if (sp + 4 > *end)
break;
deltax = sp[2];
deltay = sp[3];
startlow = x & 1;
dp += (deltax + startlow) / 2 + deltay * stride;
sp += 4;
x += deltax;
}
else if (sp[0] == 0 && sp[1] >= 3)
{ /* absolute */
int n = sp[1];
int nn = ((n + 1) / 2 + 1) / 2 * 2;
if (sp + 2 + nn > *end)
break;
if (dp + n / 2 > ep) {
fz_warn(ctx, "buffer overflow in bitmap data in bmp image");
break;
}
sp += 2;
for (i = 0; i < n; i++, x++)
{
int val = i & 1 ? (sp[i/2]) & 0xF : (sp[i/2] >> 4) & 0xF;
if (x & 1)
*dp++ |= val;
else
*dp |= val << 4;
}
sp += nn;
}
else
{ /* encoded */
int n = sp[0];
int hi = (sp[1] >> 4) & 0xF;
int lo = sp[1] & 0xF;
if (dp + n / 2 + (x & 1) > ep) {
fz_warn(ctx, "buffer overflow in bitmap data in bmp image");
break;
}
for (i = 0; i < n; i++, x++)
{
int val = i & 1 ? lo : hi;
if (x & 1)
*dp++ |= val;
else
*dp |= val << 4;
}
sp += 2;
}
}
info->compression = BI_RGB;
info->bitcount = 4;
*end = ep;
return decompressed;
}
static fz_pixmap *
bmp_read_bitmap(fz_context *ctx, struct info *info, const unsigned char *p, const unsigned char *end)
{
const int mults[] = { 0, 8191, 2730, 1170, 546, 264, 130, 64 };
fz_pixmap *pix;
const unsigned char *ssp;
unsigned char *ddp;
unsigned char *decompressed = NULL;
int bitcount, width, height;
int sstride, dstride;
int rmult, gmult, bmult, amult;
int rtrunc, gtrunc, btrunc, atrunc;
int x, y;
if (info->compression == BI_RLE8)
ssp = decompressed = bmp_decompress_rle8(ctx, info, p, &end);
else if (info->compression == BI_RLE4)
ssp = decompressed = bmp_decompress_rle4(ctx, info, p, &end);
else if (info->compression == BI_RLE24)
ssp = decompressed = bmp_decompress_rle24(ctx, info, p, &end);
else
ssp = p;
bitcount = info->bitcount;
width = info->width;
height = info->height;
sstride = ((width * bitcount + 31) / 32) * 4;
if (ssp + sstride * height > end)
{
fz_free(ctx, decompressed);
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap data in bmp image");
}
fz_try(ctx)
pix = fz_new_pixmap(ctx, fz_device_rgb(ctx), width, height, NULL, 1);
fz_catch(ctx)
{
fz_free(ctx, decompressed);
fz_rethrow(ctx);
}
ddp = pix->samples;
dstride = pix->stride;
if (!info->topdown)
{
ddp = pix->samples + (height - 1) * dstride;
dstride = -dstride;
}
/* These only apply for components in 16-bit and 32-bit mode
1-bit (1 * 8191) / 32
2-bit (3 * 2730) / 32
3-bit (7 * 1170) / 32
4-bit (15 * 546) / 32
5-bit (31 * 264) / 32
6-bit (63 * 130) / 32
7-bit (127 * 64) / 32
*/
rmult = info->rbits < 8 ? mults[info->rbits] : 1;
gmult = info->gbits < 8 ? mults[info->gbits] : 1;
bmult = info->bbits < 8 ? mults[info->bbits] : 1;
amult = info->abits < 8 ? mults[info->abits] : 1;
rtrunc = info->rbits < 8 ? 5 : (info->rbits - 8);
gtrunc = info->gbits < 8 ? 5 : (info->gbits - 8);
btrunc = info->bbits < 8 ? 5 : (info->bbits - 8);
atrunc = info->abits < 8 ? 5 : (info->abits - 8);
for (y = 0; y < height; y++)
{
const unsigned char *sp = ssp + y * sstride;
unsigned char *dp = ddp + y * dstride;
switch (bitcount)
{
case 32:
for (x = 0; x < width; x++)
{
unsigned int sample = (sp[3] << 24) | (sp[2] << 16) | (sp[1] << 8) | sp[0];
unsigned int r = (sample & info->rmask) >> info->rshift;
unsigned int g = (sample & info->gmask) >> info->gshift;
unsigned int b = (sample & info->bmask) >> info->bshift;
unsigned int a = info->abits == 0 ? 255 : (sample & info->amask) >> info->ashift;
*dp++ = (r * rmult) >> rtrunc;
*dp++ = (g * gmult) >> gtrunc;
*dp++ = (b * bmult) >> btrunc;
*dp++ = info->abits == 0 ? a : (a * amult) >> atrunc;
sp += 4;
}
break;
case 24:
for (x = 0; x < width; x++)
{
*dp++ = sp[2];
*dp++ = sp[1];
*dp++ = sp[0];
*dp++ = 255;
sp += 3;
}
break;
case 16:
for (x = 0; x < width; x++)
{
unsigned int sample = (sp[1] << 8) | sp[0];
unsigned int r = (sample & info->rmask) >> info->rshift;
unsigned int g = (sample & info->gmask) >> info->gshift;
unsigned int b = (sample & info->bmask) >> info->bshift;
unsigned int a = (sample & info->amask) >> info->ashift;
*dp++ = (r * rmult) >> rtrunc;
*dp++ = (g * gmult) >> gtrunc;
*dp++ = (b * bmult) >> btrunc;
*dp++ = info->abits == 0 ? 255 : (a * amult) >> atrunc;
sp += 2;
}
break;
case 8:
for (x = 0; x < width; x++)
{
*dp++ = info->palette[3 * sp[0] + 0];
*dp++ = info->palette[3 * sp[0] + 1];
*dp++ = info->palette[3 * sp[0] + 2];
*dp++ = 255;
sp++;
}
break;
case 4:
for (x = 0; x < width; x++)
{
int idx;
switch (x & 1)
{
case 0: idx = (sp[0] >> 4) & 0x0f; break;
case 1: idx = (sp[0] >> 0) & 0x0f; sp++; break;
}
*dp++ = info->palette[3 * idx + 0];
*dp++ = info->palette[3 * idx + 1];
*dp++ = info->palette[3 * idx + 2];
*dp++ = 255;
}
break;
case 2:
for (x = 0; x < width; x++)
{
int idx;
switch (x & 3)
{
case 0: idx = (sp[0] >> 6) & 0x03; break;
case 1: idx = (sp[0] >> 4) & 0x03; break;
case 2: idx = (sp[0] >> 2) & 0x03; break;
case 3: idx = (sp[0] >> 0) & 0x03; sp++; break;
}
*dp++ = info->palette[3 * idx + 0];
*dp++ = info->palette[3 * idx + 1];
*dp++ = info->palette[3 * idx + 2];
*dp++ = 255;
}
break;
case 1:
for (x = 0; x < width; x++)
{
int idx;
switch (x & 7)
{
case 0: idx = (sp[0] >> 7) & 0x01; break;
case 1: idx = (sp[0] >> 6) & 0x01; break;
case 2: idx = (sp[0] >> 5) & 0x01; break;
case 3: idx = (sp[0] >> 4) & 0x01; break;
case 4: idx = (sp[0] >> 3) & 0x01; break;
case 5: idx = (sp[0] >> 2) & 0x01; break;
case 6: idx = (sp[0] >> 1) & 0x01; break;
case 7: idx = (sp[0] >> 0) & 0x01; sp++; break;
}
*dp++ = info->palette[3 * idx + 0];
*dp++ = info->palette[3 * idx + 1];
*dp++ = info->palette[3 * idx + 2];
*dp++ = 255;
}
break;
}
}
fz_free(ctx, decompressed);
fz_premultiply_pixmap(ctx, pix);
return pix;
}
static fz_pixmap *
bmp_read_image(fz_context *ctx, struct info *info, const unsigned char *p, size_t total, int only_metadata)
{
const unsigned char *begin = p;
const unsigned char *end = p + total;
int size;
memset(info, 0x00, sizeof (*info));
p = bmp_read_file_header(ctx, info, p, end);
info->filesize = fz_mini(info->filesize, (int)total);
if (end - p < 4)
fz_throw(ctx, FZ_ERROR_GENERIC, "premature end in bitmap core header in bmp image");
size = read32(p + 0);
if (size == 12)
p = bmp_read_bitmap_core_header(ctx, info, p, end);
else if (size == 40 || size == 52 || size == 56 || size == 108 || size == 124)
{
p = bmp_read_bitmap_info_header(ctx, info, p, end);
if (info->extramasks)
p = bmp_read_extra_masks(ctx, info, p, end);
}
else if (size == 16 || size == 64)
p = bmp_read_bitmap_os2_header(ctx, info, p, end);
else
fz_throw(ctx, FZ_ERROR_GENERIC, "invalid header size (%d) in bmp image", size);
maskinfo(info->rmask, &info->rshift, &info->rbits);
maskinfo(info->gmask, &info->gshift, &info->gbits);
maskinfo(info->bmask, &info->bshift, &info->bbits);
maskinfo(info->amask, &info->ashift, &info->abits);
if (info->width <= 0 || info->width > SHRT_MAX || info->height <= 0 || info->height > SHRT_MAX)
fz_throw(ctx, FZ_ERROR_GENERIC, "dimensions (%d x %d) out of range in bmp image",
info->width, info->height);
if (info->compression != BI_RGB && info->compression != BI_RLE8 &&
info->compression != BI_RLE4 && info->compression != BI_BITFIELDS &&
info->compression != BI_JPEG && info->compression != BI_PNG &&
info->compression != BI_ALPHABITS && info->compression != BI_RLE24)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported compression method (%d) in bmp image", info->compression);
if ((info->compression == BI_RGB && info->bitcount != 1 &&
info->bitcount != 2 && info->bitcount != 4 &&
info->bitcount != 8 && info->bitcount != 16 &&
info->bitcount != 24 && info->bitcount != 32) ||
(info->compression == BI_RLE8 && info->bitcount != 8) ||
(info->compression == BI_RLE4 && info->bitcount != 4) ||
(info->compression == BI_BITFIELDS && info->bitcount != 16 && info->bitcount != 32) ||
(info->compression == BI_JPEG && info->bitcount != 0) ||
(info->compression == BI_PNG && info->bitcount != 0) ||
(info->compression == BI_ALPHABITS && info->bitcount != 16 && info->bitcount != 32) ||
(info->compression == BI_RLE24 && info->bitcount != 24))
fz_throw(ctx, FZ_ERROR_GENERIC, "invalid bits per pixel (%d) for compression (%d) in bmp image",
info->bitcount, info->compression);
if (info->rbits < 0 || info->rbits > info->bitcount)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported %d bit red mask in bmp image", info->rbits);
if (info->gbits < 0 || info->gbits > info->bitcount)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported %d bit green mask in bmp image", info->gbits);
if (info->bbits < 0 || info->bbits > info->bitcount)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported %d bit blue mask in bmp image", info->bbits);
if (info->abits < 0 || info->abits > info->bitcount)
fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported %d bit alpha mask in bmp image", info->abits);
if (only_metadata)
return NULL;
if (info->compression == BI_JPEG)
{
if (p - begin < info->offset)
p = begin + info->offset;
return fz_load_jpeg(ctx, p, end - p);
}
else if (info->compression == BI_PNG)
{
if (p - begin < info->offset)
p = begin + info->offset;
return fz_load_png(ctx, p, end - p);
}
else
{
const unsigned char *color_table_end = begin + info->offset;
if (end - begin < info->offset)
color_table_end = end;
p = bmp_read_color_table(ctx, info, p, color_table_end);
if (p - begin < info->offset)
p = begin + info->offset;
return bmp_read_bitmap(ctx, info, p, end);
}
}
fz_pixmap *
fz_load_bmp(fz_context *ctx, const unsigned char *p, size_t total)
{
struct info bmp;
fz_pixmap *image;
image = bmp_read_image(ctx, &bmp, p, total, 0);
image->xres = bmp.xres / (1000.0f / 25.4f);
image->yres = bmp.yres / (1000.0f / 25.4f);
return image;
}
void
fz_load_bmp_info(fz_context *ctx, const unsigned char *p, size_t total, int *wp, int *hp, int *xresp, int *yresp, fz_colorspace **cspacep)
{
struct info bmp;
bmp_read_image(ctx, &bmp, p, total, 1);
*cspacep = fz_keep_colorspace(ctx, fz_device_rgb(ctx));
*wp = bmp.width;
*hp = bmp.height;
*xresp = bmp.xres / (1000.0f / 25.4f);
*yresp = bmp.yres / (1000.0f / 25.4f);
}
| agpl-3.0 |
AsherBond/MondocosmOS | grass_trunk/db/drivers/mk_dbdriver_h.sh | 541 | #!/bin/sh
# generates dbdriver.h
tmp=mk_dbdriver_h.tmp.$$
cat <<'EOT'> dbdriver.h
/* this file was automatically generated by ../mk_dbdriver_h.sh */
#ifndef DBDRIVER_H
#define DBDRIVER_H
#include <grass/dbstubs.h>
EOT
grep -h '^\( *int *\)\?db__driver' *.c | sed \
-e 's/^\( *int *\)*/int /' \
-e 's/ *(.*$/();/' > $tmp
cat $tmp >> dbdriver.h
cat <<'EOT' >> dbdriver.h
#define init_dbdriver() do{\
EOT
sed 's/^int *db__\([a-zA-Z_]*\).*$/db_\1 = db__\1;\\/' $tmp >> dbdriver.h
cat <<'EOT'>> dbdriver.h
}while(0)
#endif
EOT
rm $tmp
| agpl-3.0 |
Shamar/Epic.NET | Code/UnitTests/Epic.Core.UnitTests/Fakes/FakeEnvironment.cs | 1300 | //
// FakeEnvironment.cs
//
// Author:
// Giacomo Tesio <[email protected]>
//
// Copyright (c) 2010-2013 Giacomo Tesio
//
// This file is part of Epic.NET.
//
// Epic.NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Epic.NET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using Epic.Environment;
namespace Epic.Fakes
{
[Serializable]
public sealed class FakeEnvironment : EnvironmentBase
{
public FakeEnvironment ()
{
int i = Get<int>(new InstanceName<int>("CoverTheMethod"));
++i;
}
#region implemented abstract members of Epic.Environment.EnvironmentBase
public override TObject Get<TObject> (InstanceName<TObject> name)
{
return default(TObject);
}
#endregion
}
}
| agpl-3.0 |
cignoni/meshlabjs | js/mlj/plugins/rendering/Axes.js | 16533 |
(function (plugin, core, scene) {
var plug = new plugin.GlobalRendering({
name: "Axes",
tooltip: "Show world space axes",
icon: "img/icons/axis.png",
toggle: true,
on: false
});
var DEFAULTS = {
planeSize: 10,
gridSpacing: 10,
gridColor: new THREE.Color(0x000066),
ticksSpacing: 3
};
// Label parameters
var lblParameters = {
fontSize: 24,
borderColor : {r:0, g:0, b:0, a:0},
bgColor : {r:255, g:255, b:255, a:0}
};
var planeWidget, planeOrientationWidget, gridColorWidget, planeSizeWidget, gridSpacingWidget, ticksSpacingWidget;
plug._init = function (guiBuilder) {
planeWidget = guiBuilder.Choice({
label: "Grid Plane",
tooltip: "If on, a grid plane will be drawn",
options: [
{content: "Off", value: "0", selected: true},
{content: "On", value: "1"}
],
bindTo: (function() {
var bindToFun = function() {
plug._onAxesParamChange();
};
bindToFun.toString = function() {
return 'planeWidget';
}
return bindToFun;
}())
});
planeOrientationWidget = guiBuilder.Choice({
label: "Grid Plane Orientation",
tooltip: "Choose which plane to draw",
options: [
{content: "XZ", value: "0", selected: true},
{content: "XY", value: "1"},
{content: "YZ", value: "2"},
],
bindTo: (function() {
var bindToFun = function() {
if(parseInt(planeWidget.getValue()))
plug._onAxesParamChange();
};
bindToFun.toString = function() {
return 'planeOrientationWidget';
}
return bindToFun;
}())
});
gridColorWidget = guiBuilder.Color({
label: "Grid Color",
tooltip: "",
color: "#" + DEFAULTS.gridColor.getHexString(),
bindTo: (function() {
var bindToFun = function() {
if(parseInt(planeWidget.getValue()))
plug._onAxesParamChange();
};
bindToFun.toString = function() {
return 'gridColorWidget';
}
return bindToFun;
}())
});
planeSizeWidget = guiBuilder.Integer({
label: "Plane Size",
tooltip: "Defines the size of the plane",
step: 1,
defval: DEFAULTS.planeSize,
min: 0,
bindTo: (function() {
var bindToFun = function() {
if(planeSizeWidget.getValue() > 0 && parseInt(planeWidget.getValue()))
plug._onAxesParamChange();
};
bindToFun.toString = function() {
return "planeSizeWidget";
};
return bindToFun;
})()
});
gridSpacingWidget = guiBuilder.Integer({
label: "Grid Spacing",
tooltip: "Defines the spacing of the grid",
step: 1,
defval: DEFAULTS.planeSize,
min: 0,
bindTo: (function() {
var bindToFun = function() {
if(gridSpacingWidget.getValue() > 0 && parseInt(planeWidget.getValue()))
plug._onAxesParamChange();
};
bindToFun.toString = function() {
return "gridSpacingWidget";
};
return bindToFun;
})()
});
ticksSpacingWidget = guiBuilder.Float({
label: "Ticks Spacing",
tooltip: "Defines the spacing between the ticks",
step: 0.5,
defval: DEFAULTS.ticksSpacing,
min: 0,
bindTo: (function() {
var bindToFun = function() {
if(ticksSpacingWidget.getValue() > 0)
plug._onAxesParamChange();
};
bindToFun.toString = function() {
return "ticksSpacingWidget";
};
return bindToFun;
})()
});
};
plug._onAxesParamChange = function() {
// var currentLayer = MLJ.core.Scene.getSelectedLayer();
// if (currentLayer.properties.getByKey(plug.getName()) === true) {
if(scene._axes)
{
this._applyTo(false);
this._applyTo(true);
}
};
plug._applyTo = function (on) {
if (on) {
scene._axes = true;
var bbox = scene.getBBox();
var axisLength = bbox.min.distanceTo(bbox.max)/2;
// Creating the Object3D of the axes. The other parts (arrows, labels, ticks) will be added to this object
var axes = new THREE.AxisHelper(axisLength);
// Parameters needed to define the size of the arrows on the axes
var arrowLength = 1;
var headLength = 0.2 * arrowLength;
var headWidth = 0.5 * headLength;
// Array that will contain the colors of each axis
var colors = [];
// X arrow parameters
var arrowDirectionX = new THREE.Vector3(1, 0, 0);
var arrowOriginAxisX = new THREE.Vector3(axisLength, 0, 0);
colors.push(0xff9900);
// Y arrow parameters
var arrowDirectionY = new THREE.Vector3(0, 1, 0);
var arrowOriginAxisY = new THREE.Vector3(0, axisLength, 0);
colors.push(0x99ff00);
// Z arrow parameters
var arrowDirectionZ = new THREE.Vector3(0, 0, 1);
var arrowOriginAxisZ = new THREE.Vector3(0, 0, axisLength);
colors.push(0x0099ff);
var arrowAxisX = new THREE.ArrowHelper(arrowDirectionX, arrowOriginAxisX, arrowLength, colors[0], headLength, headWidth);
var arrowAxisY = new THREE.ArrowHelper(arrowDirectionY, arrowOriginAxisY, arrowLength, colors[1], headLength, headWidth);
var arrowAxisZ = new THREE.ArrowHelper(arrowDirectionZ, arrowOriginAxisZ, arrowLength, colors[2], headLength, headWidth);
axes.add(arrowAxisX);
axes.add(arrowAxisY);
axes.add(arrowAxisZ);
// Now we draw the labels as sprite; first, we compute the distance
var labelDistanceFromOrigin = axisLength + arrowLength + 0.1;
// Creating the sprite with the helper function
var spriteX = makeTextSprite("X", { 'x' : labelDistanceFromOrigin, 'y' : 0, 'z': 0}, lblParameters);
var spriteY = makeTextSprite("Y", { 'x' : 0, 'y' : labelDistanceFromOrigin, 'z': 0}, lblParameters);
var spriteZ = makeTextSprite("Z", { 'x' : 0, 'y' : 0, 'z': labelDistanceFromOrigin}, lblParameters);
axes.add(spriteX);
axes.add(spriteY);
axes.add(spriteZ);
// Now we draw the white ticks on the axes
var origin = new THREE.Vector3(0, 0, 0);
// Computing the distance between the ticks for each axis. Ticks will be displayed between the origin of the axis and the origin of the arrow
var tickDistanceX = ticksSpacingWidget.getValue();
var tickDistanceY = ticksSpacingWidget.getValue();
var tickDistanceZ = ticksSpacingWidget.getValue();
// Total length to consider when drawing the ticks
var totalLength = axisLength + headLength;
// Creating the ticks mesh only if the distance is below the total length (meaning that there is at least 1 tick)
if(tickDistanceX < totalLength)
{
var ticksMeshX = createTicksMesh(origin, arrowOriginAxisX, totalLength, tickDistanceX);
axes.add(ticksMeshX);
}
if(tickDistanceY < totalLength)
{
var ticksMeshY = createTicksMesh(origin, arrowOriginAxisY, totalLength, tickDistanceY);
axes.add(ticksMeshY);
}
if(tickDistanceZ < totalLength)
{
var ticksMeshZ = createTicksMesh(origin, arrowOriginAxisZ, totalLength, tickDistanceZ);
axes.add(ticksMeshZ);
}
// If the grid is enabled, it needs to be created
if(parseInt(planeWidget.getValue()))
{
// Grid size and spacing
var gridSize = planeSizeWidget.getValue();
var gridSpacing = gridSpacingWidget.getValue();
var planeOrientation = parseInt(planeOrientationWidget.getValue());
var grid = createGrid(gridSize, gridSpacing, planeOrientation, colors);
axes.add(grid);
}
scene.addSceneDecorator(plug.getName(), axes);
} else {
scene.removeSceneDecorator(plug.getName());
scene._axes = false;
}
};
/**
* Creates a grid rotated according to the plane orientation
*
* @param {integer} gridSize size of the grid
* @param {integer} gridSpacing spacing in the grid
* @param {integer} plane the orientation of the plane (0 == XZ, 1 == XY, 2 == YZ)
* @param {THREE.Color} colors
* @returns {THREE.GridHelper}
*/
function createGrid(gridSize, gridSpacing, plane, colors)
{
// Gird mesh and color
var grid = new THREE.GridHelper(gridSize, gridSize/gridSpacing);
grid.setColors(gridColorWidget.getColor(), gridColorWidget.getColor());
// Coordinate vectors and colors for the line to be drawn across the plane axes
var negativeVec1 = new THREE.Vector3(-gridSize, 0, 0);
var positiveVec1 = new THREE.Vector3(gridSize, 0, 0);
var negativeVec2 = new THREE.Vector3(0, 0, -gridSize);
var positiveVec2 = new THREE.Vector3(0, 0, gridSize);
var color1 = colors[0];
var color2 = colors[2];
// Depending on the plane orientation, the grid needs to be rotated around an axis
switch(plane)
{
case 1:
color2 = colors[1];
grid.rotation.x = Math.PI/2;
break;
case 2:
color1 = colors[1];
color2 = colors[2];
grid.rotation.z = Math.PI/2;
break;
}
// Creating the line along the first axis of the plane (for example if the plane is XY it will be the line
// across the X axis; if it's the YZ plane it will be the line across Y)
var geometry1 = new THREE.Geometry();
var material1 = new THREE.LineBasicMaterial({color: color1});
geometry1.vertices.push(negativeVec1, positiveVec1);
var line1 = new THREE.Line(geometry1, material1);
grid.add(line1);
// Second line along the second axis
var geometry2 = new THREE.Geometry();
var material2 = new THREE.LineBasicMaterial({color: color2});
geometry2.vertices.push(negativeVec2, positiveVec2);
var line2 = new THREE.Line(geometry2, material2);
grid.add(line2)
return grid;
}
/**
* Function that creates "ticks" from one point to another under a given dimension and with a fixed distance between the points
*
* @param {type} startPoint starting point
* @param {type} endPoint ending point
* @param {type} dim total size to consider
* @param {type} tickDistance distance between a tick and the next one
* @returns {THREE.Object3D|THREE.PointCloud}
*/
function createTicksMesh(startPoint, endPoint, dim, tickDistance)
{
// Considering the difference between the starting and ending point
var v = new THREE.Vector3();
v.subVectors(endPoint, startPoint);
// Normalizing without computing square roots and powers
v.divideScalar(dim);
var ticksMesh = new THREE.Object3D();
var ticksGeometry = new THREE.Geometry();
var i;
// Creating the points. Each point is separated by "tickDistance" pixels. Since the
for(i = tickDistance; i < dim; i += tickDistance)
ticksGeometry.vertices.push(new THREE.Vector3(startPoint.x + i*v.x, startPoint.y + i*v.y, startPoint.z + i*v.z));
var ticksMaterial = new THREE.PointCloudMaterial({
size: 3,
sizeAttenuation: false
});
// Creating the ticks as a cloud of points
ticksMesh = new THREE.PointCloud(ticksGeometry, ticksMaterial);
return ticksMesh;
}
/**
* Make a text texture <code>message</code> with HTML approach
* @param {String} message Message to be applied to texture
* @param {Vector3} position The position of the texture sprite
* @param {Object} parameters The sprite's parameters
* @memberOf MLJ.plugins.rendering.Box
* @author Stefano Giammori
*/
function makeTextSprite(message, position, parameters)
{
if ( parameters === undefined ) parameters = {};
//extract label params
var fontface = parameters.hasOwnProperty("fontFace") ?
parameters["fontFace"] : "Arial";
var fontsize = parameters.hasOwnProperty("fontSize") ?
parameters["fontSize"] : 10;
var fontweight = parameters.hasOwnProperty("fontWeight") ?
parameters["fontWeight"] : "normal" //white, visible
var borderThickness = parameters.hasOwnProperty("borderThickness") ?
parameters["borderThickness"] : 4;
var borderColor = parameters.hasOwnProperty("borderColor") ?
parameters["borderColor"] : { r:0, g:0, b:0, a:1.0 }; //black, visible
var backgroundColor = parameters.hasOwnProperty("bgColor") ?
parameters["bgColor"] : {r:255, g:255, b:255, a:1.0} //white, visible
//prepare label
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = fontweight + " " + fontsize + "px " + fontface;
// get size data (height depends only on font size)
var textWidth = context.measureText(message).width;
canvas.width = textWidth + borderThickness * 2;
canvas.height = fontsize + borderThickness * 2;
//set the param font into context
context.font = fontweight + " " + fontsize + "px " + fontface;
//set context background color
context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + ","
+ backgroundColor.b + "," + backgroundColor.a + ")";
//set context border color
context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + ","
+ borderColor.b + "," + borderColor.a + ")";
//set border thickness
context.lineWidth = borderThickness;
/** //MEMO : (add +x) ~~ go right; (add +y) ~~ go down) ]
Set the rectangular frame (ctx, top-left, top, width, height, radius of the 4 corners)
*/
context.fillStyle = "rgba(255, 255, 255, 1.0)";
/** Set starting point of text, in which pt(borderThickness, fontsize+borderThickness/2) represent the
top left of the top-left corner of the texture text in the canvas. */
context.fillText(message, borderThickness, fontsize + borderThickness/2);
//canvas contents will be used for create a texture
var texture = new THREE.Texture(canvas)
texture.needsUpdate = true;
texture.minFilter = THREE.LinearFilter;
var spriteMaterial = new THREE.SpriteMaterial({ map: texture, useScreenCoordinates: false, color: 0xffffff, fog: true } );
var sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set( textWidth/100, fontsize/100, 1 );
sprite.position.set( position.x , position.y, position.z);
return sprite;
}
plugin.Manager.install(plug);
})(MLJ.core.plugin, MLJ.core, MLJ.core.Scene);
| agpl-3.0 |
singularities/circular-works | frontend/app/controllers/organizations/show.js | 180 | import Ember from 'ember';
export default Ember.Controller.extend({
canCreateTask: Ember.computed('model.isAdmin', function() {
return this.get('model.isAdmin');
}),
});
| agpl-3.0 |
enjaz/enjaz | activities/migrations/0005_activity_is_approved.py | 587 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('activities', '0004_manytomany_not_null'),
]
operations = [
migrations.AddField(
model_name='activity',
name='is_approved',
field=models.NullBooleanField(verbose_name='\u0627\u0644\u062d\u0627\u0644\u0629', choices=[(True, '\u0645\u0639\u062a\u0645\u062f'), (False, '\u0645\u0631\u0641\u0648\u0636'), (None, '\u0645\u0639\u0644\u0642')]),
),
]
| agpl-3.0 |
xin3liang/platform_external_arduino-ide | hardware/arduino/sam/system/AndroidAccessory/AndroidAccessory.cpp | 9423 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/
#include <Max3421e.h>
#include <Usb.h>
#include <AndroidAccessory.h>
#define USB_ACCESSORY_VENDOR_ID 0x18D1
#define USB_ACCESSORY_PRODUCT_ID 0x2D00
#define USB_ACCESSORY_ADB_PRODUCT_ID 0x2D01
#define ACCESSORY_STRING_MANUFACTURER 0
#define ACCESSORY_STRING_MODEL 1
#define ACCESSORY_STRING_DESCRIPTION 2
#define ACCESSORY_STRING_VERSION 3
#define ACCESSORY_STRING_URI 4
#define ACCESSORY_STRING_SERIAL 5
#define ACCESSORY_GET_PROTOCOL 51
#define ACCESSORY_SEND_STRING 52
#define ACCESSORY_START 53
AndroidAccessory::AndroidAccessory(const char *manufacturer,
const char *model,
const char *description,
const char *version,
const char *uri,
const char *serial) : manufacturer(manufacturer),
model(model),
description(description),
version(version),
uri(uri),
serial(serial),
connected(false)
{
}
void AndroidAccessory::powerOn(void)
{
max.powerOn();
delay(200);
}
int AndroidAccessory::getProtocol(byte addr)
{
uint16_t protocol = -1;
usb.ctrlReq(addr, 0,
USB_SETUP_DEVICE_TO_HOST |
USB_SETUP_TYPE_VENDOR |
USB_SETUP_RECIPIENT_DEVICE,
ACCESSORY_GET_PROTOCOL, 0, 0, 0, 2, (char *)&protocol);
return protocol;
}
void AndroidAccessory::sendString(byte addr, int index, const char *str)
{
usb.ctrlReq(addr, 0,
USB_SETUP_HOST_TO_DEVICE |
USB_SETUP_TYPE_VENDOR |
USB_SETUP_RECIPIENT_DEVICE,
ACCESSORY_SEND_STRING, 0, 0, index,
strlen(str) + 1, (char *)str);
}
bool AndroidAccessory::switchDevice(byte addr)
{
int protocol = getProtocol(addr);
if (protocol == 1) {
Serial.print(F("device supports protcol 1\n"));
} else {
Serial.print(F("could not read device protocol version\n"));
return false;
}
sendString(addr, ACCESSORY_STRING_MANUFACTURER, manufacturer);
sendString(addr, ACCESSORY_STRING_MODEL, model);
sendString(addr, ACCESSORY_STRING_DESCRIPTION, description);
sendString(addr, ACCESSORY_STRING_VERSION, version);
sendString(addr, ACCESSORY_STRING_URI, uri);
sendString(addr, ACCESSORY_STRING_SERIAL, serial);
usb.ctrlReq(addr, 0,
USB_SETUP_HOST_TO_DEVICE |
USB_SETUP_TYPE_VENDOR |
USB_SETUP_RECIPIENT_DEVICE,
ACCESSORY_START, 0, 0, 0, 0, NULL);
while (usb.getUsbTaskState() != USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
max.Task();
usb.Task();
}
return true;
}
// Finds the first bulk IN and bulk OUT endpoints
bool AndroidAccessory::findEndpoints(byte addr, EP_RECORD *inEp, EP_RECORD *outEp)
{
int len;
byte err;
uint8_t *p;
err = usb.getConfDescr(addr, 0, 4, 0, (char *)descBuff);
if (err) {
Serial.print(F("Can't get config descriptor length\n"));
return false;
}
len = descBuff[2] | ((int)descBuff[3] << 8);
if (len > sizeof(descBuff)) {
Serial.print(F("config descriptor too large\n"));
/* might want to truncate here */
return false;
}
err = usb.getConfDescr(addr, 0, len, 0, (char *)descBuff);
if (err) {
Serial.print(F("Can't get config descriptor\n"));
return false;
}
p = descBuff;
inEp->epAddr = 0;
outEp->epAddr = 0;
while (p < (descBuff + len)){
uint8_t descLen = p[0];
uint8_t descType = p[1];
USB_ENDPOINT_DESCRIPTOR *epDesc;
EP_RECORD *ep;
switch (descType) {
case USB_DESCRIPTOR_CONFIGURATION:
Serial.print(F("config desc\n"));
break;
case USB_DESCRIPTOR_INTERFACE:
Serial.print(F("interface desc\n"));
break;
case USB_DESCRIPTOR_ENDPOINT:
epDesc = (USB_ENDPOINT_DESCRIPTOR *)p;
if (!inEp->epAddr && (epDesc->bEndpointAddress & 0x80))
ep = inEp;
else if (!outEp->epAddr)
ep = outEp;
else
ep = NULL;
if (ep) {
ep->epAddr = epDesc->bEndpointAddress & 0x7f;
ep->Attr = epDesc->bmAttributes;
ep->MaxPktSize = epDesc->wMaxPacketSize;
ep->sndToggle = bmSNDTOG0;
ep->rcvToggle = bmRCVTOG0;
}
break;
default:
Serial.print(F("unkown desc type "));
Serial.println( descType, HEX);
break;
}
p += descLen;
}
if (!(inEp->epAddr && outEp->epAddr))
Serial.println(F("can't find accessory endpoints"));
return inEp->epAddr && outEp->epAddr;
}
bool AndroidAccessory::configureAndroid(void)
{
byte err;
EP_RECORD inEp, outEp;
if (!findEndpoints(1, &inEp, &outEp))
return false;
memset(&epRecord, 0x0, sizeof(epRecord));
epRecord[inEp.epAddr] = inEp;
if (outEp.epAddr != inEp.epAddr)
epRecord[outEp.epAddr] = outEp;
in = inEp.epAddr;
out = outEp.epAddr;
Serial.println(inEp.epAddr, HEX);
Serial.println(outEp.epAddr, HEX);
epRecord[0] = *(usb.getDevTableEntry(0,0));
usb.setDevTableEntry(1, epRecord);
err = usb.setConf( 1, 0, 1 );
if (err) {
Serial.print(F("Can't set config to 1\n"));
return false;
}
usb.setUsbTaskState( USB_STATE_RUNNING );
return true;
}
bool AndroidAccessory::isConnected(void)
{
USB_DEVICE_DESCRIPTOR *devDesc = (USB_DEVICE_DESCRIPTOR *) descBuff;
byte err;
max.Task();
usb.Task();
if (!connected &&
usb.getUsbTaskState() >= USB_STATE_CONFIGURING &&
usb.getUsbTaskState() != USB_STATE_RUNNING) {
Serial.print(F("\nDevice addressed... "));
Serial.print(F("Requesting device descriptor.\n"));
err = usb.getDevDescr(1, 0, 0x12, (char *) devDesc);
if (err) {
Serial.print(F("\nDevice descriptor cannot be retrieved. Trying again\n"));
return false;
}
if (isAccessoryDevice(devDesc)) {
Serial.print(F("found android acessory device\n"));
connected = configureAndroid();
} else {
Serial.print(F("found possible device. swithcing to serial mode\n"));
switchDevice(1);
}
} else if (usb.getUsbTaskState() == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
if (connected)
Serial.println(F("disconnect\n"));
connected = false;
}
return connected;
}
bool AndroidAccessory::dataBufferIsEmpty() {
return (numBytesInDataBuff == nextByteInDataBuffOffset);
}
void AndroidAccessory::refillDataBuffer() {
int bytesRead = 0;
numBytesInDataBuff = nextByteInDataBuffOffset = 0;
// TODO: Add is connected check?
bytesRead = read(dataBuff, sizeof(dataBuff));
if (bytesRead >= 1) {
numBytesInDataBuff = bytesRead;
}
}
int AndroidAccessory::read() {
if (dataBufferIsEmpty()) {
refillDataBuffer();
}
return dataBufferIsEmpty() ? -1 : dataBuff[nextByteInDataBuffOffset++];
}
int AndroidAccessory::peek() {
if (dataBufferIsEmpty()) {
refillDataBuffer();
}
return dataBufferIsEmpty() ? -1 : dataBuff[nextByteInDataBuffOffset];
}
int AndroidAccessory::available() {
// Strictly speaking this doesn't meet the "This is only for bytes
// that have already arrived" definition from
// <http://arduino.cc/en/Reference/StreamAvailable> but since the
// data isn't handled by an ISR it's the only way to avoid hanging
// waiting for `available()` to return true.
if (dataBufferIsEmpty()) {
refillDataBuffer();
}
return numBytesInDataBuff - nextByteInDataBuffOffset;
}
int AndroidAccessory::read(void *buff, int len, unsigned int nakLimit)
{
return usb.newInTransfer(1, in, len, (char *)buff, nakLimit);
}
size_t AndroidAccessory::write(uint8_t *buff, size_t len)
{
usb.outTransfer(1, out, len, (char *)buff);
return len;
}
size_t AndroidAccessory::write(uint8_t c) {
return write(&c, 1);
}
void AndroidAccessory::flush() {
/*
"Waits for the transmission of outgoing [...] data to complete."
from <http://arduino.cc/en/Serial/Flush>
We're treating this as a no-op at the moment.
*/
}
| lgpl-2.1 |
igor-sfdc/qt-wk | src/xmlpatterns/expr/qvaluecomparison.cpp | 4779 | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qitem_p.h"
#include "qboolean_p.h"
#include "qbuiltintypes_p.h"
#include "qcommonsequencetypes_p.h"
#include "qemptysequence_p.h"
#include "qoptimizationpasses_p.h"
#include "qvaluecomparison_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
ValueComparison::ValueComparison(const Expression::Ptr &op1,
const AtomicComparator::Operator op,
const Expression::Ptr &op2) : PairContainer(op1, op2),
m_operator(op)
{
}
Item ValueComparison::evaluateSingleton(const DynamicContext::Ptr &context) const
{
const Item it1(m_operand1->evaluateSingleton(context));
if(!it1)
return Item();
const Item it2(m_operand2->evaluateSingleton(context));
if(!it2)
return Item();
return Boolean::fromValue(flexibleCompare(it1, it2, context));
}
Expression::Ptr ValueComparison::typeCheck(const StaticContext::Ptr &context,
const SequenceType::Ptr &reqType)
{
const Expression::Ptr me(PairContainer::typeCheck(context, reqType));
const ItemType::Ptr t1(m_operand1->staticType()->itemType());
const ItemType::Ptr t2(m_operand2->staticType()->itemType());
Q_ASSERT(t1);
Q_ASSERT(t2);
if(*CommonSequenceTypes::Empty == *t1 ||
*CommonSequenceTypes::Empty == *t2)
{
return EmptySequence::create(this, context);
}
else
{
prepareComparison(fetchComparator(t1, t2, context));
return me;
}
}
Expression::Ptr ValueComparison::compress(const StaticContext::Ptr &context)
{
const Expression::Ptr me(PairContainer::compress(context));
if(me != this)
return me;
if(isCaseInsensitiveCompare(m_operand1, m_operand2))
useCaseInsensitiveComparator();
return me;
}
bool ValueComparison::isCaseInsensitiveCompare(Expression::Ptr &op1, Expression::Ptr &op2)
{
Q_ASSERT(op1);
Q_ASSERT(op2);
const ID iD = op1->id();
if((iD == IDLowerCaseFN || iD == IDUpperCaseFN) && iD == op2->id())
{
/* Both are either fn:lower-case() or fn:upper-case(). */
/* Replace the calls to the functions with its operands. */
op1 = op1->operands().first();
op2 = op2->operands().first();
return true;
}
else
return false;
}
OptimizationPass::List ValueComparison::optimizationPasses() const
{
return OptimizationPasses::comparisonPasses;
}
SequenceType::List ValueComparison::expectedOperandTypes() const
{
SequenceType::List result;
result.append(CommonSequenceTypes::ZeroOrOneAtomicType);
result.append(CommonSequenceTypes::ZeroOrOneAtomicType);
return result;
}
SequenceType::Ptr ValueComparison::staticType() const
{
if(m_operand1->staticType()->cardinality().allowsEmpty() ||
m_operand2->staticType()->cardinality().allowsEmpty())
return CommonSequenceTypes::ZeroOrOneBoolean;
else
return CommonSequenceTypes::ExactlyOneBoolean;
}
ExpressionVisitorResult::Ptr ValueComparison::accept(const ExpressionVisitor::Ptr &visitor) const
{
return visitor->visit(this);
}
Expression::ID ValueComparison::id() const
{
return IDValueComparison;
}
QT_END_NAMESPACE
| lgpl-2.1 |
nonrational/qt-everywhere-opensource-src-4.8.6 | src/tools/uic/utils.h | 4079 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef UTILS_H
#define UTILS_H
#include "ui4.h"
#include <QtCore/QString>
#include <QtCore/QList>
#include <QtCore/QHash>
QT_BEGIN_NAMESPACE
inline bool toBool(const QString &str)
{ return str.toLower() == QLatin1String("true"); }
inline QString toString(const DomString *str)
{ return str ? str->text() : QString(); }
inline QString fixString(const QString &str, const QString &indent)
{
QString cursegment;
QStringList result;
const QByteArray utf8 = str.toUtf8();
const int utf8Length = utf8.length();
for (int i = 0; i < utf8Length; ++i) {
const uchar cbyte = utf8.at(i);
if (cbyte >= 0x80) {
cursegment += QLatin1Char('\\');
cursegment += QString::number(cbyte, 8);
} else {
switch(cbyte) {
case '\\':
cursegment += QLatin1String("\\\\"); break;
case '\"':
cursegment += QLatin1String("\\\""); break;
case '\r':
break;
case '\n':
cursegment += QLatin1String("\\n\"\n\""); break;
default:
cursegment += QLatin1Char(cbyte);
}
}
if (cursegment.length() > 1024) {
result << cursegment;
cursegment.clear();
}
}
if (!cursegment.isEmpty())
result << cursegment;
QString joinstr = QLatin1String("\"\n");
joinstr += indent;
joinstr += indent;
joinstr += QLatin1Char('"');
QString rc(QLatin1Char('"'));
rc += result.join(joinstr);
rc += QLatin1Char('"');
return rc;
}
inline QHash<QString, DomProperty *> propertyMap(const QList<DomProperty *> &properties)
{
QHash<QString, DomProperty *> map;
for (int i=0; i<properties.size(); ++i) {
DomProperty *p = properties.at(i);
map.insert(p->attributeName(), p);
}
return map;
}
inline QStringList unique(const QStringList &lst)
{
QHash<QString, bool> h;
for (int i=0; i<lst.size(); ++i)
h.insert(lst.at(i), true);
return h.keys();
}
QT_END_NAMESPACE
#endif // UTILS_H
| lgpl-2.1 |
kaltsi/qt-mobility | src/location/landmarks/qlandmarknamefilter.cpp | 4339 | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlandmarknamefilter.h"
#include "qlandmarknamefilter_p.h"
QTM_BEGIN_NAMESPACE
/*!
\class QLandmarkNameFilter
\brief The QLandmarkNameFilter class is used to search for landmarks by name.
\inmodule QtLocation
\since 1.1
\ingroup landmarks-filter
Please note that different platforms support different capabilities with the attribute filter.
\list
\o The S60 3.1, 3.2 and 5.0 platforms do not support the MatchContains flag while the Symbian
platform does.
\o Note also that MatchContains is supported using the sparql and sqlite \l {Landmark Managers and Plugins} {managers}.
\endlist
*/
Q_IMPLEMENT_LANDMARKFILTER_PRIVATE(QLandmarkNameFilter)
/*!
Creates a filter that selects landmarks by \a name.
\since 1.1
*/
QLandmarkNameFilter::QLandmarkNameFilter(const QString &name)
: QLandmarkFilter(new QLandmarkNameFilterPrivate(name)) {}
/*!
\fn QLandmarkNameFilter::QLandmarkNameFilter(const QLandmarkFilter &other)
Constructs a copy of \a other if possible, otherwise constructs a new name filter.
*/
/*!
Destroys the filter.
*/
QLandmarkNameFilter::~QLandmarkNameFilter()
{
// pointer deleted in superclass destructor
}
/*!
Returns the name that the filter will use to determine matches.
\since 1.1
*/
QString QLandmarkNameFilter::name() const
{
Q_D(const QLandmarkNameFilter);
return d->name;
}
/*!
Sets the \a name that the filter will use to determine matches.
\since 1.1
*/
void QLandmarkNameFilter::setName(const QString &name)
{
Q_D(QLandmarkNameFilter);
d->name = name;
}
/*!
Returns the matching criteria of the filter.
\since 1.1
*/
QLandmarkFilter::MatchFlags QLandmarkNameFilter::matchFlags() const
{
Q_D(const QLandmarkNameFilter);
return d->flags;
}
/*!
Sets the matching criteria to those defined in \a flags.
\since 1.1
*/
void QLandmarkNameFilter::setMatchFlags(QLandmarkFilter::MatchFlags flags)
{
Q_D(QLandmarkNameFilter);
d->flags = flags;
}
/*******************************************************************************
*******************************************************************************/
QLandmarkNameFilterPrivate::QLandmarkNameFilterPrivate(const QString &name)
: name(name),
flags(0)
{
type = QLandmarkFilter::NameFilter;
}
QLandmarkNameFilterPrivate::QLandmarkNameFilterPrivate(const QLandmarkNameFilterPrivate &other)
: QLandmarkFilterPrivate(other),
name(other.name),
flags(other.flags) {}
QLandmarkNameFilterPrivate::~QLandmarkNameFilterPrivate() {}
QTM_END_NAMESPACE
| lgpl-2.1 |
skyvers/wildcat | skyve-core/src/main/java/org/skyve/domain/PolymorphicPersistentBean.java | 752 | package org.skyve.domain;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This is an annotation used for indicating that the associated metadata document that generated the domain class
* has at least one sub-document in its hierarchy that uses an inheritance strategy of joined or single.
* This is useful to know when executing metadata document queries as the query evaluator needs to include
* the THIS projection to allow for polymorphic methods.
*
* @author mike
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) //on class level
public @interface PolymorphicPersistentBean {
// nothing to see here
} | lgpl-2.1 |
pararthshah/libavg-vaapi | src/player/ImageNode.h | 2260 | //
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#ifndef _ImageNode_H_
#define _ImageNode_H_
#include "../api.h"
#include "RasterNode.h"
#include "Image.h"
#include "../graphics/Bitmap.h"
#include "../base/UTF8String.h"
#include <string>
namespace avg {
class AVG_API ImageNode : public RasterNode
{
public:
static void registerType();
ImageNode(const ArgList& args);
virtual ~ImageNode();
virtual void connectDisplay();
virtual void connect(CanvasPtr pCanvas);
virtual void disconnect(bool bKill);
virtual void checkReload();
const UTF8String& getHRef() const;
void setHRef(const UTF8String& href);
const std::string getCompression() const;
void setBitmap(BitmapPtr pBmp);
virtual void preRender(const VertexArrayPtr& pVA, bool bIsParentActive,
float parentEffectiveOpacity);
virtual void render();
void getElementsByPos(const glm::vec2& pos, std::vector<NodePtr>& pElements);
virtual BitmapPtr getBitmap();
virtual IntPoint getMediaSize();
private:
bool isCanvasURL(const std::string& sURL);
void checkCanvasValid(const CanvasPtr& pCanvas);
UTF8String m_href;
Image::TextureCompression m_Compression;
ImagePtr m_pImage;
};
typedef boost::shared_ptr<ImageNode> ImageNodePtr;
}
#endif
| lgpl-2.1 |
openwayne/chaos_theory | mods/animalmaterials/mob_environments/init.lua | 944 | -------------------------------------------------------------------------------
-- mob_environments Mod by Sapier
--
--
--! @file init.lua
--! @brief main init file for environment definitions
--! @copyright Sapier
--! @author Sapier
--! @date 2014-08-11
--
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
local ar_version = "0.0.1"
core.log("action", "MOD: Loading mob_environments mod ...")
--!path of mod
local me_modpath = minetest.get_modpath("mob_environments")
dofile (me_modpath .. "/general_env_sets.lua")
dofile (me_modpath .. "/flight_1.lua")
dofile (me_modpath .. "/meadow.lua")
dofile (me_modpath .. "/on_ground_2.lua")
dofile (me_modpath .. "/open_waters.lua")
dofile (me_modpath .. "/shallow_waters.lua")
dofile (me_modpath .. "/deep_water.lua")
dofile (me_modpath .. "/simple_air.lua")
core.log("action", "MOD: mob_environments mod " .. ar_version .. " loaded.") | lgpl-2.1 |
awltech/org.parallelj | parallelj-core-parent/parallelj-core-api/src/main/java/org/parallelj/internal/kernel/join/package-info.java | 1144 | /*
* ParallelJ, framework for parallel computing
*
* Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* This package contains implementations of {@link org.parallelj.internal.kernel.KJoin}.
*/
package org.parallelj.internal.kernel.join; | lgpl-2.1 |
danwent/libvirt-ovs | tests/vmx2xmltest.c | 8078 | #include <config.h>
#ifdef WITH_VMX
# include <stdio.h>
# include <string.h>
# include <unistd.h>
# include "internal.h"
# include "memory.h"
# include "testutils.h"
# include "vmx/vmx.h"
static virCapsPtr caps;
static virVMXContext ctx;
static int testDefaultConsoleType(const char *ostype ATTRIBUTE_UNUSED)
{
return VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
}
static void
testCapsInit(void)
{
virCapsGuestPtr guest = NULL;
caps = virCapabilitiesNew("i686", 1, 1);
if (caps == NULL) {
return;
}
caps->defaultConsoleTargetType = testDefaultConsoleType;
virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
virCapabilitiesAddHostMigrateTransport(caps, "esx");
caps->hasWideScsiBus = true;
/* i686 guest */
guest =
virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0, NULL);
if (guest == NULL) {
goto failure;
}
if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
NULL) == NULL) {
goto failure;
}
/* x86_64 guest */
guest =
virCapabilitiesAddGuest(caps, "hvm", "x86_64", 64, NULL, NULL, 0, NULL);
if (guest == NULL) {
goto failure;
}
if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
NULL) == NULL) {
goto failure;
}
return;
failure:
virCapabilitiesFree(caps);
caps = NULL;
}
static int
testCompareFiles(const char *vmx, const char *xml)
{
int result = -1;
char *vmxData = NULL;
char *xmlData = NULL;
char *formatted = NULL;
virDomainDefPtr def = NULL;
virErrorPtr err = NULL;
if (virtTestLoadFile(vmx, &vmxData) < 0) {
goto failure;
}
if (virtTestLoadFile(xml, &xmlData) < 0) {
goto failure;
}
def = virVMXParseConfig(&ctx, caps, vmxData);
if (def == NULL) {
err = virGetLastError();
fprintf(stderr, "ERROR: %s\n", err != NULL ? err->message : "<unknown>");
goto failure;
}
formatted = virDomainDefFormat(def, VIR_DOMAIN_XML_SECURE);
if (formatted == NULL) {
err = virGetLastError();
fprintf(stderr, "ERROR: %s\n", err != NULL ? err->message : "<unknown>");
goto failure;
}
if (STRNEQ(xmlData, formatted)) {
virtTestDifference(stderr, xmlData, formatted);
goto failure;
}
result = 0;
failure:
VIR_FREE(vmxData);
VIR_FREE(xmlData);
VIR_FREE(formatted);
virDomainDefFree(def);
return result;
}
struct testInfo {
const char *input;
const char *output;
};
static int
testCompareHelper(const void *data)
{
int result = -1;
const struct testInfo *info = data;
char *vmx = NULL;
char *xml = NULL;
if (virAsprintf(&vmx, "%s/vmx2xmldata/vmx2xml-%s.vmx", abs_srcdir,
info->input) < 0 ||
virAsprintf(&xml, "%s/vmx2xmldata/vmx2xml-%s.xml", abs_srcdir,
info->output) < 0) {
goto cleanup;
}
result = testCompareFiles(vmx, xml);
cleanup:
VIR_FREE(vmx);
VIR_FREE(xml);
return result;
}
static char *
testParseVMXFileName(const char *fileName, void *opaque ATTRIBUTE_UNUSED)
{
char *copyOfFileName = NULL;
char *tmp = NULL;
char *saveptr = NULL;
char *datastoreName = NULL;
char *directoryAndFileName = NULL;
char *src = NULL;
if (STRPREFIX(fileName, "/vmfs/volumes/")) {
/* Found absolute path referencing a file inside a datastore */
copyOfFileName = strdup(fileName);
if (copyOfFileName == NULL) {
goto cleanup;
}
/* Expected format: '/vmfs/volumes/<datastore>/<path>' */
if ((tmp = STRSKIP(copyOfFileName, "/vmfs/volumes/")) == NULL ||
(datastoreName = strtok_r(tmp, "/", &saveptr)) == NULL ||
(directoryAndFileName = strtok_r(NULL, "", &saveptr)) == NULL) {
goto cleanup;
}
virAsprintf(&src, "[%s] %s", datastoreName, directoryAndFileName);
} else if (STRPREFIX(fileName, "/")) {
/* Found absolute path referencing a file outside a datastore */
src = strdup(fileName);
} else if (strchr(fileName, '/') != NULL) {
/* Found relative path, this is not supported */
src = NULL;
} else {
/* Found single file name referencing a file inside a datastore */
virAsprintf(&src, "[datastore] directory/%s", fileName);
}
cleanup:
VIR_FREE(copyOfFileName);
return src;
}
static int
mymain(void)
{
int result = 0;
# define DO_TEST(_in, _out) \
do { \
struct testInfo info = { _in, _out }; \
virResetLastError(); \
if (virtTestRun("VMware VMX-2-XML "_in" -> "_out, 1, \
testCompareHelper, &info) < 0) { \
result = -1; \
} \
} while (0)
testCapsInit();
if (caps == NULL) {
return EXIT_FAILURE;
}
ctx.opaque = NULL;
ctx.parseFileName = testParseVMXFileName;
ctx.formatFileName = NULL;
ctx.autodetectSCSIControllerModel = NULL;
DO_TEST("case-insensitive-1", "case-insensitive-1");
DO_TEST("case-insensitive-2", "case-insensitive-2");
DO_TEST("minimal", "minimal");
DO_TEST("minimal-64bit", "minimal-64bit");
DO_TEST("graphics-vnc", "graphics-vnc");
DO_TEST("scsi-driver", "scsi-driver");
DO_TEST("scsi-writethrough", "scsi-writethrough");
DO_TEST("harddisk-scsi-file", "harddisk-scsi-file");
DO_TEST("harddisk-ide-file", "harddisk-ide-file");
DO_TEST("cdrom-scsi-file", "cdrom-scsi-file");
DO_TEST("cdrom-scsi-device", "cdrom-scsi-device");
DO_TEST("cdrom-ide-file", "cdrom-ide-file");
DO_TEST("cdrom-ide-device", "cdrom-ide-device");
DO_TEST("floppy-file", "floppy-file");
DO_TEST("floppy-device", "floppy-device");
DO_TEST("ethernet-e1000", "ethernet-e1000");
DO_TEST("ethernet-vmxnet2", "ethernet-vmxnet2");
DO_TEST("ethernet-custom", "ethernet-custom");
DO_TEST("ethernet-bridged", "ethernet-bridged");
DO_TEST("ethernet-generated", "ethernet-generated");
DO_TEST("ethernet-static", "ethernet-static");
DO_TEST("ethernet-vpx", "ethernet-vpx");
DO_TEST("ethernet-other", "ethernet-other");
DO_TEST("serial-file", "serial-file");
DO_TEST("serial-device", "serial-device");
DO_TEST("serial-pipe-client-app", "serial-pipe");
DO_TEST("serial-pipe-server-vm", "serial-pipe");
DO_TEST("serial-pipe-client-app", "serial-pipe");
DO_TEST("serial-pipe-server-vm", "serial-pipe");
DO_TEST("serial-network-server", "serial-network-server");
DO_TEST("serial-network-client", "serial-network-client");
DO_TEST("parallel-file", "parallel-file");
DO_TEST("parallel-device", "parallel-device");
DO_TEST("esx-in-the-wild-1", "esx-in-the-wild-1");
DO_TEST("esx-in-the-wild-2", "esx-in-the-wild-2");
DO_TEST("esx-in-the-wild-3", "esx-in-the-wild-3");
DO_TEST("esx-in-the-wild-4", "esx-in-the-wild-4");
DO_TEST("esx-in-the-wild-5", "esx-in-the-wild-5");
DO_TEST("esx-in-the-wild-6", "esx-in-the-wild-6");
DO_TEST("gsx-in-the-wild-1", "gsx-in-the-wild-1");
DO_TEST("gsx-in-the-wild-2", "gsx-in-the-wild-2");
DO_TEST("gsx-in-the-wild-3", "gsx-in-the-wild-3");
DO_TEST("gsx-in-the-wild-4", "gsx-in-the-wild-4");
DO_TEST("annotation", "annotation");
DO_TEST("smbios", "smbios");
DO_TEST("svga", "svga");
virCapabilitiesFree(caps);
return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
VIRT_TEST_MAIN(mymain)
#else
# include "testutils.h"
int main(void)
{
return EXIT_AM_SKIP;
}
#endif /* WITH_VMX */
| lgpl-2.1 |
arcean/libmeegotouch-framework | src/include/mlabelmodel.h | 789 | /***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "../corelib/widgets/mlabelmodel.h"
| lgpl-2.1 |
trixmot/mod1 | build/tmp/recompileMc/sources/net/minecraft/inventory/InventoryLargeChest.java | 6532 | package net.minecraft.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode;
public class InventoryLargeChest implements ILockableContainer
{
/** Name of the chest. */
private String name;
/** Inventory object corresponding to double chest upper part */
private ILockableContainer upperChest;
/** Inventory object corresponding to double chest lower part */
private ILockableContainer lowerChest;
private static final String __OBFID = "CL_00001507";
public InventoryLargeChest(String p_i45905_1_, ILockableContainer p_i45905_2_, ILockableContainer p_i45905_3_)
{
this.name = p_i45905_1_;
if (p_i45905_2_ == null)
{
p_i45905_2_ = p_i45905_3_;
}
if (p_i45905_3_ == null)
{
p_i45905_3_ = p_i45905_2_;
}
this.upperChest = p_i45905_2_;
this.lowerChest = p_i45905_3_;
if (p_i45905_2_.isLocked())
{
p_i45905_3_.setLockCode(p_i45905_2_.getLockCode());
}
else if (p_i45905_3_.isLocked())
{
p_i45905_2_.setLockCode(p_i45905_3_.getLockCode());
}
}
/**
* Returns the number of slots in the inventory.
*/
public int getSizeInventory()
{
return this.upperChest.getSizeInventory() + this.lowerChest.getSizeInventory();
}
/**
* Return whether the given inventory is part of this large chest.
*/
public boolean isPartOfLargeChest(IInventory inventoryIn)
{
return this.upperChest == inventoryIn || this.lowerChest == inventoryIn;
}
/**
* Gets the name of this command sender (usually username, but possibly "Rcon")
*/
public String getName()
{
return this.upperChest.hasCustomName() ? this.upperChest.getName() : (this.lowerChest.hasCustomName() ? this.lowerChest.getName() : this.name);
}
/**
* Returns true if this thing is named
*/
public boolean hasCustomName()
{
return this.upperChest.hasCustomName() || this.lowerChest.hasCustomName();
}
public IChatComponent getDisplayName()
{
return (IChatComponent)(this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatComponentTranslation(this.getName(), new Object[0]));
}
/**
* Returns the stack in slot i
*/
public ItemStack getStackInSlot(int index)
{
return index >= this.upperChest.getSizeInventory() ? this.lowerChest.getStackInSlot(index - this.upperChest.getSizeInventory()) : this.upperChest.getStackInSlot(index);
}
/**
* Removes from an inventory slot (first arg) up to a specified number (second arg) of items and returns them in a
* new stack.
*/
public ItemStack decrStackSize(int index, int count)
{
return index >= this.upperChest.getSizeInventory() ? this.lowerChest.decrStackSize(index - this.upperChest.getSizeInventory(), count) : this.upperChest.decrStackSize(index, count);
}
/**
* When some containers are closed they call this on each slot, then drop whatever it returns as an EntityItem -
* like when you close a workbench GUI.
*/
public ItemStack getStackInSlotOnClosing(int index)
{
return index >= this.upperChest.getSizeInventory() ? this.lowerChest.getStackInSlotOnClosing(index - this.upperChest.getSizeInventory()) : this.upperChest.getStackInSlotOnClosing(index);
}
/**
* Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections).
*/
public void setInventorySlotContents(int index, ItemStack stack)
{
if (index >= this.upperChest.getSizeInventory())
{
this.lowerChest.setInventorySlotContents(index - this.upperChest.getSizeInventory(), stack);
}
else
{
this.upperChest.setInventorySlotContents(index, stack);
}
}
/**
* Returns the maximum stack size for a inventory slot. Seems to always be 64, possibly will be extended. *Isn't
* this more of a set than a get?*
*/
public int getInventoryStackLimit()
{
return this.upperChest.getInventoryStackLimit();
}
/**
* For tile entities, ensures the chunk containing the tile entity is saved to disk later - the game won't think it
* hasn't changed and skip it.
*/
public void markDirty()
{
this.upperChest.markDirty();
this.lowerChest.markDirty();
}
/**
* Do not make give this method the name canInteractWith because it clashes with Container
*/
public boolean isUseableByPlayer(EntityPlayer player)
{
return this.upperChest.isUseableByPlayer(player) && this.lowerChest.isUseableByPlayer(player);
}
public void openInventory(EntityPlayer player)
{
this.upperChest.openInventory(player);
this.lowerChest.openInventory(player);
}
public void closeInventory(EntityPlayer player)
{
this.upperChest.closeInventory(player);
this.lowerChest.closeInventory(player);
}
/**
* Returns true if automation is allowed to insert the given stack (ignoring stack size) into the given slot.
*/
public boolean isItemValidForSlot(int index, ItemStack stack)
{
return true;
}
public int getField(int id)
{
return 0;
}
public void setField(int id, int value) {}
public int getFieldCount()
{
return 0;
}
public boolean isLocked()
{
return this.upperChest.isLocked() || this.lowerChest.isLocked();
}
public void setLockCode(LockCode code)
{
this.upperChest.setLockCode(code);
this.lowerChest.setLockCode(code);
}
public LockCode getLockCode()
{
return this.upperChest.getLockCode();
}
public String getGuiID()
{
return this.upperChest.getGuiID();
}
public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn)
{
return new ContainerChest(playerInventory, this, playerIn);
}
public void clear()
{
this.upperChest.clear();
this.lowerChest.clear();
}
} | lgpl-2.1 |
cdmdotnet/CQRS | wiki/docs/4.1/html/classCqrs_1_1MongoDB_1_1DataStores_1_1MongoDbDataStore_af86a3df56e2df92fb9ef880ff4fa5f16.html | 6039 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://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.16"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.MongoDB.DataStores.MongoDbDataStore.Update</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="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(initResizable);
/* @license-end */</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/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></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 id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">4.1</span>
</div>
<div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.16 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('classCqrs_1_1MongoDB_1_1DataStores_1_1MongoDbDataStore_af86a3df56e2df92fb9ef880ff4fa5f16.html','');});
/* @license-end */
</script>
<div id="doc-content">
<!-- 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 class="contents">
<a id="af86a3df56e2df92fb9ef880ff4fa5f16"></a>
<h2 class="memtitle"><span class="permalink"><a href="#af86a3df56e2df92fb9ef880ff4fa5f16">◆ </a></span>Update()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual void <a class="el" href="classCqrs_1_1MongoDB_1_1DataStores_1_1MongoDbDataStore.html">Cqrs.MongoDB.DataStores.MongoDbDataStore</a>< TData >.Update </td>
<td>(</td>
<td class="paramtype">TData </td>
<td class="paramname"><em>data</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Update the provided <em>data</em> in the data store and persist the change. </p>
<p>Implements <a class="el" href="interfaceCqrs_1_1DataStores_1_1IDataStore_a6d5d4dd572de8db01ff0c48d37faefa7.html#a6d5d4dd572de8db01ff0c48d37faefa7">Cqrs.DataStores.IDataStore< TData ></a>.</p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1MongoDB.html">MongoDB</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1MongoDB_1_1DataStores.html">DataStores</a></li><li class="navelem"><a class="el" href="classCqrs_1_1MongoDB_1_1DataStores_1_1MongoDbDataStore.html">MongoDbDataStore</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li>
</ul>
</div>
</body>
</html>
| lgpl-2.1 |
saprykin/plib | platforms/unixware-gcc/platform.cmake | 285 | set (PLIBSYS_THREAD_MODEL posix)
set (PLIBSYS_IPC_MODEL sysv)
set (PLIBSYS_TIME_PROFILER_MODEL posix)
set (PLIBSYS_DIR_MODEL posix)
set (PLIBSYS_LIBRARYLOADER_MODEL posix)
set (PLIBSYS_PLATFORM_LINK_LIBRARIES socket nsl -pthread)
set (PLIBSYS_PLATFORM_DEFINES
-D_REENTRANT
)
| lgpl-2.1 |
lorddavy/TikiWiki-Improvement-Project | lib/test/phpunit.php | 752 | <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: phpunit.php 57962 2016-03-17 20:02:39Z jonnybradley $
/**
* A simple wrapper around /usr/bin/phpunit to enable debugging
* tests with Xdebug from within Aptana or Eclipse.
*
* Linux only (it should be simple to add support to other OSs).
*/
// Linux
require_once('/usr/bin/phpunit');
// Windows
// comment out the Linux require line (above) and uncomment the 2 lines below
//$pear_bin_path = getenv('PHP_PEAR_BIN_DIR').DIRECTORY_SEPARATOR;
//require_once($pear_bin_path."phpunit");
| lgpl-2.1 |
eric100lin/Qt-4.8.6 | tools/designer/src/lib/shared/shared_settings_p.h | 4567 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of Qt Designer. This header
// file may change from version to version without notice, or even be removed.
//
// We mean it.
//
#ifndef SHARED_SETTINGS_H
#define SHARED_SETTINGS_H
#include "shared_global_p.h"
#include "deviceprofile_p.h"
#include <QtCore/qglobal.h>
#include <QtCore/QList>
QT_BEGIN_NAMESPACE
class QDesignerFormEditorInterface;
class QDesignerSettingsInterface;
class QStringList;
class QSize;
namespace qdesigner_internal {
class Grid;
class PreviewConfiguration;
}
/*!
Auxiliary methods to store/retrieve settings
*/
namespace qdesigner_internal {
class QDESIGNER_SHARED_EXPORT QDesignerSharedSettings {
public:
typedef QList<DeviceProfile> DeviceProfileList;
explicit QDesignerSharedSettings(QDesignerFormEditorInterface *core);
Grid defaultGrid() const;
void setDefaultGrid(const Grid &grid);
QStringList formTemplatePaths() const;
void setFormTemplatePaths(const QStringList &paths);
void setAdditionalFormTemplatePaths(const QStringList &additionalPaths);
QStringList additionalFormTemplatePaths() const;
QString formTemplate() const;
void setFormTemplate(const QString &t);
QSize newFormSize() const;
void setNewFormSize(const QSize &s);
// Check with isCustomPreviewConfigurationEnabled if custom or default
// configuration should be used.
PreviewConfiguration customPreviewConfiguration() const;
void setCustomPreviewConfiguration(const PreviewConfiguration &configuration);
bool isCustomPreviewConfigurationEnabled() const;
void setCustomPreviewConfigurationEnabled(bool enabled);
QStringList userDeviceSkins() const;
void setUserDeviceSkins(const QStringList &userDeviceSkins);
bool zoomEnabled() const;
void setZoomEnabled(bool v);
// Zoom in percent
int zoom() const;
void setZoom(int z);
// Embedded Design
DeviceProfile currentDeviceProfile() const;
void setCurrentDeviceProfileIndex(int i);
int currentDeviceProfileIndex() const;
DeviceProfile deviceProfileAt(int idx) const;
DeviceProfileList deviceProfiles() const;
void setDeviceProfiles(const DeviceProfileList &dp);
static const QStringList &defaultFormTemplatePaths();
protected:
QDesignerSettingsInterface *settings() const { return m_settings; }
private:
QStringList deviceProfileXml() const;
QDesignerSettingsInterface *m_settings;
};
} // namespace qdesigner_internal
QT_END_NAMESPACE
#endif // SHARED_SETTINGS_H
| lgpl-2.1 |
Chinchilla-Software-Com/CQRS | NorthwindDemo/step-3/aspnet-mvc/Northwind.Domain/Northwind/Domain/Orders/Repositories/Queries/Strategies/IInvoicesQueryStrategyBuilder.generated.cs | 991 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#region Copyright
// -----------------------------------------------------------------------
// <copyright company="cdmdotnet Limited">
// Copyright cdmdotnet Limited. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
#endregion
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Cqrs.Repositories.Queries;
namespace Northwind.Domain.Orders.Repositories.Queries.Strategies
{
[GeneratedCode("CQRS UML Code Generator", "1.601.881")]
public partial interface IInvoicesQueryStrategyBuilder : IQueryBuilder<InvoicesQueryStrategy, Entities.InvoicesEntity>
{
}
}
| lgpl-2.1 |
cstb/ifc2x3-SDK | include/ifc2x3/IfcAxis1Placement.h | 3911 | // IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
#ifndef IFC2X3_IFCAXIS1PLACEMENT_H
#define IFC2X3_IFCAXIS1PLACEMENT_H
#include <ifc2x3/DefinedTypes.h>
#include <ifc2x3/Export.h>
#include <ifc2x3/IfcPlacement.h>
#include <Step/BaseVisitor.h>
#include <Step/ClassType.h>
#include <Step/Referenced.h>
#include <Step/SPFData.h>
#include <string>
namespace ifc2x3 {
class CopyOp;
class IfcDirection;
/**
* Generated class for the IfcAxis1Placement Entity.
*
*/
class IFC2X3_EXPORT IfcAxis1Placement : public IfcPlacement {
public:
/**
* Accepts a read/write Step::BaseVisitor.
*
* @param visitor the read/write Step::BaseVisitor to accept
*/
virtual bool acceptVisitor(Step::BaseVisitor *visitor);
/**
* Returns the class type as a human readable std::string.
*
*/
virtual const std::string &type() const;
/**
* Returns the Step::ClassType of this specific class. Useful to compare with the isOfType method for example.
*
*/
static const Step::ClassType &getClassType();
/**
* Returns the Step::ClassType of the instance of this class. (might be a subtype since it is virtual and overloaded).
*
*/
virtual const Step::ClassType &getType() const;
/**
* Compares this instance's Step::ClassType with the one passed as parameter. Checks the type recursively (to the mother classes).
*
* @param t
*/
virtual bool isOfType(const Step::ClassType &t) const;
/**
* Gets the value of the explicit attribute 'Axis'.
*
*/
virtual IfcDirection *getAxis();
/**
* (const) Returns the value of the explicit attribute 'Axis'.
*
* @return the value of the explicit attribute 'Axis'
*/
virtual const IfcDirection *getAxis() const;
/**
* Sets the value of the explicit attribute 'Axis'.
*
* @param value
*/
virtual void setAxis(const Step::RefPtr< IfcDirection > &value);
/**
* unset the attribute 'Axis'.
*
*/
virtual void unsetAxis();
/**
* Test if the attribute 'Axis' is set.
*
* @return true if set, false if unset
*/
virtual bool testAxis() const;
/**
* Gets the value of the derived attribute 'Z'.
*
*/
virtual IfcDirection *getZ() const;
friend class ExpressDataSet;
protected:
/**
* @param id
* @param args
*/
IfcAxis1Placement(Step::Id id, Step::SPFData *args);
virtual ~IfcAxis1Placement();
/**
*/
virtual bool init();
/**
* @param obj
* @param copyop
*/
virtual void copy(const IfcAxis1Placement &obj, const CopyOp ©op);
private:
/**
*/
static Step::ClassType s_type;
/**
*/
Step::RefPtr< IfcDirection > m_axis;
};
}
#endif // IFC2X3_IFCAXIS1PLACEMENT_H
| lgpl-2.1 |
chescock/libgit2 | CHANGELOG.md | 1845 | v0.21 + 1
------
* File unlocks are atomic again via rename. Read-only files on Windows are
made read-write if necessary.
* Share open packfiles across repositories to share descriptors and mmaps.
* Use a map for the treebuilder, making insertion O(1)
* LF -> CRLF filter refuses to handle mixed-EOL files
* LF -> CRLF filter now runs when * text = auto (with Git for Windows 1.9.4)
* The git_transport structure definition has moved into the sys/transport.h
file.
* The git_transport_register function no longer takes a priority and takes
a URL scheme name (eg "http") instead of a prefix like "http://"
* The git_remote_set_transport function now sets a transport factory function,
rather than a pre-existing transport instance.
* A factory function for ssh has been added which allows to change the
path of the programs to execute for receive-pack and upload-pack on
the server, git_transport_ssh_with_paths.
* The git_clone_options struct no longer provides the ignore_cert_errors or
remote_name members for remote customization.
Instead, the git_clone_options struct has two new members, remote_cb and
remote_cb_payload, which allow the caller to completely override the remote
creation process. If needed, the caller can use this callback to give their
remote a name other than the default (origin) or disable cert checking.
The remote_callbacks member has been preserved for convenience, although it
is not used when a remote creation callback is supplied.
* The git_clone_options struct now provides repository_cb and
repository_cb_payload to allow the user to create a repository with
custom options.
* git_clone_into and git_clone_local_into have been removed from the
public API in favour of git_clone callbacks
* Add support for refspecs with the asterisk in the middle of a
pattern.
| lgpl-2.1 |
kolyshkin/mosaic | include/util.h | 1751 | #ifndef __MOSAIC_UTIL_H__
#define __MOSAIC_UTIL_H__
#include "log.h"
int scan_mounts(char *path, char *device);
int remove_rec(int dir_fd);
int rmdirat_r(int basefd, const char *base, const char *dirs);
int get_subdir_size(int fd, unsigned long *sizep);
int copy_file(int src_dirfd, const char *src_dir,
int dst_dirfd, const char *dst_dir,
const char *name);
char *read_var(int dirfd, const char *dir, const char *name);
int write_var(int dirfd, const char *dir,
const char *name, const char *val);
int run_prg(char *const argv[]);
#define HIDE_STDOUT 1 << 0 /* hide process' stdout */
#define HIDE_STDERR 1 << 1 /* hide process' stderr */
int run_prg_rc(char *const argv[], int hide_mask, int *rc);
int path_exists(const char *path);
int mkdir_p(const char *path, int use_last_component, int mode);
/* Config parsing: check if val is set */
#define CHKVAL(key, val) \
do { \
if (!val) { \
loge("%s: can't parse \"%s\"\n", __func__, key);\
return -1; \
} \
} while (0)
/* Config parsing: check if val is set, and there's no duplicate */
#define CHKVALTO(key, val, to) CHKVAL(key, val); \
do { \
if (to) { \
loge("%s: duplicate \"%s\"\n", __func__, key); \
free(val); \
return -1; \
} \
} while (0)
/* Safer memory operations */
#define __xalloc(op, size, ...) \
({ \
void *___p = op( __VA_ARGS__ ); \
if (!___p) \
loge("%s: can't alloc %li bytes\n", \
__func__, (long)(size)); \
___p; \
})
#define xstrdup(str) __xalloc(strdup, strlen(str) + 1, str)
#define xmalloc(size) __xalloc(malloc, size, size)
#define xzalloc(size) __xalloc(calloc, size, 1, size)
#define xrealloc(p, size) __xalloc(realloc, size, p, size)
#endif
| lgpl-2.1 |
dsroche/flint2 | fmpz_poly/test/t-scalar_fdiv_mpz.c | 2119 | /*
Copyright (C) 2009 William Hart
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include "flint.h"
#include "fmpz.h"
#include "fmpz_poly.h"
#include "ulong_extras.h"
int
main(void)
{
int i, result;
FLINT_TEST_INIT(state);
flint_printf("scalar_fdiv_mpz....");
fflush(stdout);
/* Compare with fmpz_poly_scalar_fdiv_fmpz */
for (i = 0; i < 100 * flint_test_multiplier(); i++)
{
fmpz_poly_t a, b, c;
fmpz_t n;
mpz_t n1;
fmpz_init(n);
mpz_init(n1);
do {
fmpz_randtest(n, state, 200);
} while (fmpz_is_zero(n));
fmpz_get_mpz(n1, n);
fmpz_poly_init(a);
fmpz_poly_init(b);
fmpz_poly_init(c);
fmpz_poly_randtest(a, state, n_randint(state, 100), 200);
fmpz_poly_scalar_mul_fmpz(a, a, n);
fmpz_poly_scalar_fdiv_fmpz(b, a, n);
fmpz_poly_scalar_fdiv_mpz(c, a, n1);
result = (fmpz_poly_equal(b, c));
if (!result)
{
flint_printf("FAIL:\n");
fmpz_poly_print(a), flint_printf("\n\n");
fmpz_poly_print(b), flint_printf("\n\n");
fmpz_poly_print(c), flint_printf("\n\n");
abort();
}
/* aliasing */
fmpz_poly_scalar_fdiv_mpz(a, a, n1);
result = (fmpz_poly_equal(a, c));
if (!result)
{
flint_printf("FAIL:\n");
fmpz_poly_print(a), flint_printf("\n\n");
fmpz_poly_print(c), flint_printf("\n\n");
abort();
}
mpz_clear(n1);
fmpz_clear(n);
fmpz_poly_clear(a);
fmpz_poly_clear(b);
fmpz_poly_clear(c);
}
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
| lgpl-2.1 |
cdmdotnet/CQRS | wiki/docs/2.1/coverage-report/Azure/Cqrs.Azure.ServiceBus.Tests.Unit/index-sort-l.html | 4144 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LCOV - doc-coverage.info - Azure/Cqrs.Azure.ServiceBus.Tests.Unit</title>
<link rel="stylesheet" type="text/css" href="../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">LCOV - code coverage report</td></tr>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../index.html">top level</a> - Azure/Cqrs.Azure.ServiceBus.Tests.Unit</td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Test:</td>
<td class="headerValue">doc-coverage.info</td>
<td></td>
<td class="headerItem">Lines:</td>
<td class="headerCovTableEntry">1</td>
<td class="headerCovTableEntry">7</td>
<td class="headerCovTableEntryLo">14.3 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2017-07-26</td>
<td></td>
</tr>
<tr><td><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<center>
<table width="80%" cellpadding=1 cellspacing=1 border=0>
<tr>
<td width="40%"><br></td>
<td width="20%"></td>
<td width="20%"></td>
<td width="20%"></td>
</tr>
<tr>
<td class="tableHead">Filename <span class="tableHeadSort"><a href="index.html"><img src="../../updown.png" width=10 height=14 alt="Sort by name" title="Sort by name" border=0></a></span></td>
<td class="tableHead" colspan=3>Line Coverage <span class="tableHeadSort"><img src="../../glass.png" width=10 height=14 alt="Sort by line coverage" title="Sort by line coverage" border=0></span></td>
</tr>
<tr>
<td class="coverFile"><a href="TestEvent.cs.gcov.html">TestEvent.cs</a></td>
<td class="coverBar" align="center">
<table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../snow.png" width=100 height=10 alt="0.0%"></td></tr></table>
</td>
<td class="coverPerLo">0.0 %</td>
<td class="coverNumLo">0 / 1</td>
</tr>
<tr>
<td class="coverFile"><a href="TestCommand.cs.gcov.html">TestCommand.cs</a></td>
<td class="coverBar" align="center">
<table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../snow.png" width=100 height=10 alt="0.0%"></td></tr></table>
</td>
<td class="coverPerLo">0.0 %</td>
<td class="coverNumLo">0 / 1</td>
</tr>
<tr>
<td class="coverFile"><a href="MessageSerialiserTests.cs.gcov.html">MessageSerialiserTests.cs</a></td>
<td class="coverBar" align="center">
<table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../ruby.png" width=20 height=10 alt="20.0%"><img src="../../snow.png" width=80 height=10 alt="20.0%"></td></tr></table>
</td>
<td class="coverPerLo">20.0 %</td>
<td class="coverNumLo">1 / 5</td>
</tr>
</table>
</center>
<br>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php">LCOV version 1.10</a></td></tr>
</table>
<br>
</body>
</html>
| lgpl-2.1 |
SudiptaBiswas/Crow | include/materials/PFEigenStrainBaseMaterial.h | 1655 | #ifndef PFEIGENSTRAINBASEMATERIAL_H
#define PFEIGENSTRAINBASEMATERIAL_H
#include "LinearElasticMaterial.h"
#include "DerivativeMaterialInterface.h"
/**
* EigenStrainBaseMaterial is a base to construct material kernels that represent
* different eigenstrain - concentration relationships.
* It provides place holders for calculating eigenstrain and its 1st and 2nd
* order derivatives with respect to c, elasticity_tensor and its 1st and 2nd
* order derivatives wrt c if it is a function of c instead of a constant.
*/
class PFEigenStrainBaseMaterial : public DerivativeMaterialInterface<LinearElasticMaterial>
{
public:
PFEigenStrainBaseMaterial(const InputParameters & parameters);
protected:
virtual void computeEigenStrain() = 0;
virtual RankTwoTensor computeStressFreeStrain();
VariableValue & _c;
VariableName _c_name;
std::string _eigenstrain_name;
MaterialProperty<RankTwoTensor> & _eigenstrain;
MaterialProperty<RankTwoTensor> & _delastic_strain_dc;
MaterialProperty<RankTwoTensor> & _d2elastic_strain_dc2;
MaterialProperty<ElasticityTensorR4> & _delasticity_tensor_dc;
MaterialProperty<ElasticityTensorR4> & _d2elasticity_tensor_dc2;
std::vector<VariableValue *> _vals;
std::vector<VariableName> _v_name;
unsigned int _ncrys;
std::vector<MaterialProperty<RankTwoTensor> *> _delastic_strain_dv;
std::vector<MaterialProperty<ElasticityTensorR4> *> _delasticity_tensor_dv;
std::vector<std::vector<MaterialProperty<RankTwoTensor> *> > _d2elastic_strain_dv2;
std::vector<std::vector<MaterialProperty<ElasticityTensorR4> *> > _d2elasticity_tensor_dv2;
};
#endif //PFEIGENSTRAINBASEMATERIAL_H
| lgpl-2.1 |
carlos-lopez-garces/mapnik-trunk | plugins/input/osm/osm_datasource.cpp | 5406 | /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
#include <mapnik/query.hpp>
#include "osm_datasource.hpp"
#include "osm_featureset.hpp"
#include "dataset_deliverer.h"
#include "osmtagtypes.h"
#include "osmparser.h"
#include <set>
DATASOURCE_PLUGIN(osm_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
osm_datasource::osm_datasource(const parameters ¶ms, bool bind)
: datasource (params),
type_(datasource::Vector),
desc_(*params_.get<std::string>("type"), *params_.get<std::string>("encoding","utf-8"))
{
if (bind)
{
this->bind();
}
}
void osm_datasource::bind() const
{
if (is_bound_) return;
osm_data_ = NULL;
std::string osm_filename= *params_.get<std::string>("file","");
std::string parser = *params_.get<std::string>("parser","libxml2");
std::string url = *params_.get<std::string>("url","");
std::string bbox = *params_.get<std::string>("bbox","");
bool do_process=false;
// load the data
// if we supplied a filename, load from file
if (url!="" && bbox!="")
{
// otherwise if we supplied a url and a bounding box, load from the url
#ifdef MAPNIK_DEBUG
cerr<<"loading_from_url: url="<<url << " bbox="<<bbox<<endl;
#endif
if((osm_data_=dataset_deliverer::load_from_url
(url,bbox,parser))==NULL)
{
throw datasource_exception("Error loading from URL");
}
do_process=true;
}
else if(osm_filename!="")
{
if ((osm_data_=
dataset_deliverer::load_from_file(osm_filename,parser))==NULL)
{
throw datasource_exception("Error loading from file");
}
do_process=true;
}
if(do_process==true)
{
osm_tag_types tagtypes;
tagtypes.add_type("maxspeed",mapnik::Integer);
tagtypes.add_type("z_order",mapnik::Integer);
osm_data_->rewind();
// Need code to get the attributes of all the data
std::set<std::string> keys= osm_data_->get_keys();
// Add the attributes to the datasource descriptor - assume they are
// all of type String
for(std::set<std::string>::iterator i=keys.begin(); i!=keys.end(); i++)
desc_.add_descriptor(attribute_descriptor(*i,tagtypes.get_type(*i)));
// Get the bounds of the data and set extent_ accordingly
bounds b = osm_data_->get_bounds();
extent_ = box2d<double>(b.w,b.s,b.e,b.n);
}
is_bound_ = true;
}
osm_datasource::~osm_datasource()
{
// Do not do as is now static variable and cleaned up at exit
//delete osm_data_;
}
std::string osm_datasource::name()
{
return "osm";
}
int osm_datasource::type() const
{
return type_;
}
layer_descriptor osm_datasource::get_descriptor() const
{
return desc_;
}
featureset_ptr osm_datasource::features(const query& q) const
{
if (!is_bound_) bind();
filter_in_box filter(q.get_bbox());
// so we need to filter osm features by bbox here...
return featureset_ptr
(new osm_featureset<filter_in_box>(filter,
osm_data_,
q.property_names(),
desc_.get_encoding()));
}
featureset_ptr osm_datasource::features_at_point(coord2d const& pt) const
{
if (!is_bound_) bind();
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector =
desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
return featureset_ptr
(new osm_featureset<filter_at_point>(filter,
osm_data_,
names,
desc_.get_encoding()));
}
box2d<double> osm_datasource::envelope() const
{
if (!is_bound_) bind();
return extent_;
}
| lgpl-2.1 |
lorddavy/TikiWiki-Improvement-Project | lib/core/TikiDb/MasterSlaveDispatch.php | 3672 | <?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: MasterSlaveDispatch.php 57968 2016-03-17 20:06:57Z jonnybradley $
class TikiDb_MasterSlaveDispatch extends TikiDb
{
private $master;
private $slave;
private $lastUsed;
function __construct( TikiDb $master, TikiDb $slave )
{
$this->master = $master;
$this->slave = $slave;
$this->lastUsed = $slave;
}
function getReal()
{
return $this->slave;
}
function startTimer() // {{{
{
$this->getApplicable()->startTimer();
} // }}}
function stopTimer($starttime) // {{{
{
$this->getApplicable()->stopTimer($starttime);
} // }}}
function qstr( $str ) // {{{
{
return $this->getApplicable()->qstr($str);
} // }}}
function query( $query = null, $values = null, $numrows = -1, $offset = -1, $reporterrors = true ) // {{{
{
return $this->getApplicable($query)->query($query, $values, $numrows, $offset, $reporterrors);
} // }}}
function queryError( $query, &$error, $values = null, $numrows = -1, $offset = -1 ) // {{{
{
return $this->getApplicable($query)->queryError($query, $error, $values, $numrows, $offset);
} // }}}
function getOne( $query, $values = null, $reporterrors = true, $offset = 0 ) // {{{
{
return $this->getApplicable($query)->getOne($query, $values, $reporterrors, $offset);
} // }}}
function setErrorHandler( TikiDb_ErrorHandler $handler ) // {{{
{
$this->getApplicable()->setErrorHandler($handler);
} // }}}
function setTablePrefix( $prefix ) // {{{
{
$this->getApplicable()->setTablePrefix($prefix);
} // }}}
function setUsersTablePrefix( $prefix ) // {{{
{
$this->getApplicable()->setUsersTablePrefix($prefix);
} // }}}
function getServerType() // {{{
{
return $this->getApplicable()->getServerType();
} // }}}
function setServerType( $type ) // {{{
{
$this->getApplicable()->setServerType($type);
} // }}}
function getErrorMessage() // {{{
{
return $this->lastUsed->getErrorMessage();
} // }}}
protected function setErrorMessage( $message ) // {{{
{
$this->getApplicable()->setErrorMessage($message);
} // }}}
protected function handleQueryError( $query, $values, $result ) // {{{
{
$this->getApplicable()->handleQueryError($query, $values, $result);
} // }}}
protected function convertQueryTablePrefixes( &$query ) // {{{
{
$this->getApplicable($query)->convertQueryTablePrefixes($query);
} // }}}
function convertSortMode( $sort_mode ) // {{{
{
return $this->getApplicable()->convertSortMode($sort_mode);
} // }}}
function getQuery() // {{{
{
return $this->getApplicable()->getQuery();
} // }}}
function setQuery( $sql ) // {{{
{
return $this->getApplicable()->setQuery($sql);
} // }}}
function ifNull( $field, $ifNull ) // {{{
{
return $this->getApplicable()->ifNull($field, $ifNull);
} // }}}
function in( $field, $values, &$bindvars ) // {{{
{
return $this->getApplicable()->in($field, $values, $bindvars);
} // }}}
function concat() // {{{
{
$arr = func_get_args();
return call_user_func_array(array( $this->getApplicable(), 'concat' ), $arr);
} // }}}
private function getApplicable( $query = '' )
{
if ( empty($query) ) {
return $this->lastUsed = $this->slave;
}
// If it's a write
// regex is for things starting with select in any case with potential
// whitespace in front of it
if (!preg_match('/^\s*select/i', $query)) {
return $this->lastUsed = $this->master;
}
return $this->lastUsed = $this->slave;
}
}
| lgpl-2.1 |
Chinchilla-Software-Com/CQRS | wiki/docs/2.3/coverage-report/Cqrs/Domain/Exceptions/DuplicateEventException.cs.gcov.html | 8507 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LCOV - doc-coverage.info - Cqrs/Domain/Exceptions/DuplicateEventException.cs</title>
<link rel="stylesheet" type="text/css" href="../../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">Documentation Coverage Report</td></tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../../index.html">top level</a> - <a href="index.html">Cqrs/Domain/Exceptions</a> - DuplicateEventException.cs</td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Version:</td>
<td class="headerValue">2.2</td>
<td></td>
<td class="headerItem">Artefacts:</td>
<td class="headerCovTableEntry">2</td>
<td class="headerCovTableEntry">2</td>
<td class="headerCovTableEntryHi">100.0 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2018-02-20</td>
<td></td>
</tr>
<tr><td><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<table cellpadding=0 cellspacing=0 border=0>
<tr>
<td><br></td>
</tr>
<tr>
<td>
<pre class="sourceHeading"> Line data Source code</pre>
<pre class="source">
<span class="lineNum"> 1 </span> : #region Copyright
<span class="lineNum"> 2 </span> : // // -----------------------------------------------------------------------
<span class="lineNum"> 3 </span> : // // <copyright company="Chinchilla Software Limited">
<span class="lineNum"> 4 </span> : // // Copyright Chinchilla Software Limited. All rights reserved.
<span class="lineNum"> 5 </span> : // // </copyright>
<span class="lineNum"> 6 </span> : // // -----------------------------------------------------------------------
<span class="lineNum"> 7 </span> : #endregion
<span class="lineNum"> 8 </span> :
<span class="lineNum"> 9 </span> : using System;
<span class="lineNum"> 10 </span> : using System.Runtime.Serialization;
<span class="lineNum"> 11 </span> : using Cqrs.Events;
<span class="lineNum"> 12 </span> :
<span class="lineNum"> 13 </span> : namespace Cqrs.Domain.Exceptions
<span class="lineNum"> 14 </span> : {
<span class="lineNum"> 15 </span> : /// <summary>
<span class="lineNum"> 16 </span> : /// The <see cref="IEventStore{TAuthenticationToken}"/> gave more than one <see cref="IEvent{TAuthenticationToken}"/>.
<span class="lineNum"> 17 </span> : /// </summary>
<span class="lineNum"> 18 </span> : /// <typeparam name="TAggregateRoot">The <see cref="Type"/> of the <see cref="IAggregateRoot{TAuthenticationToken}"/> that wasn't found.</typeparam>
<span class="lineNum"> 19 </span> : /// <typeparam name="TAuthenticationToken">The <see cref="Type"/> of the authentication token.</typeparam>
<span class="lineNum"> 20 </span> : [Serializable]
<span class="lineNum"> 21 </span> : public class DuplicateEventException<TAggregateRoot, TAuthenticationToken> : Exception
<span class="lineNum"> 22 </span> : where TAggregateRoot : IAggregateRoot<TAuthenticationToken>
<span class="lineNum"> 23 </span><span class="lineCov"> 1 : {</span>
<span class="lineNum"> 24 </span> : /// <summary>
<span class="lineNum"> 25 </span> : /// Instantiate a new instance of <see cref="DuplicateEventException{TAggregateRoot,TAuthenticationToken}"/> with the provided identifier of the <see cref="IAggregateRoot{TAuthenticationToken}"/> that had duplicate <see cref="IEvent{TAuthenticationToken}">events</see>.
<span class="lineNum"> 26 </span> : /// and the <paramref name="version"/> that had more than one <see cref="IEvent{TAuthenticationToken}"/> provided.
<span class="lineNum"> 27 </span> : /// </summary>
<span class="lineNum"> 28 </span> : /// <param name="id">The identifier of the <see cref="IAggregateRoot{TAuthenticationToken}"/> that had <see cref="IEvent{TAuthenticationToken}">events</see>.</param>
<span class="lineNum"> 29 </span> : /// <param name="version">The version number of the duplicate <see cref="IEvent{TAuthenticationToken}">events</see></param>
<span class="lineNum"> 30 </span><span class="lineCov"> 1 : public DuplicateEventException(Guid id, int version)</span>
<span class="lineNum"> 31 </span> : : base(string.Format("Eventstore gave more than one event for aggregate '{0}' of type '{1}' for version {2}", id, typeof(TAggregateRoot).FullName, version))
<span class="lineNum"> 32 </span> : {
<span class="lineNum"> 33 </span> : Id = id;
<span class="lineNum"> 34 </span> : AggregateType = typeof (TAggregateRoot);
<span class="lineNum"> 35 </span> : }
<span class="lineNum"> 36 </span> :
<span class="lineNum"> 37 </span> : /// <summary>
<span class="lineNum"> 38 </span> : /// The identifier of the <see cref="IAggregateRoot{TAuthenticationToken}"/> that had duplicate <see cref="IEvent{TAuthenticationToken}">events</see>..
<span class="lineNum"> 39 </span> : /// </summary>
<span class="lineNum"> 40 </span> : [DataMember]
<span class="lineNum"> 41 </span> : public Guid Id { get; set; }
<span class="lineNum"> 42 </span> :
<span class="lineNum"> 43 </span> : /// <summary>
<span class="lineNum"> 44 </span> : /// The <see cref="Type"/> of the <see cref="IAggregateRoot{TAuthenticationToken}"/> that had duplicate <see cref="IEvent{TAuthenticationToken}">events</see>..
<span class="lineNum"> 45 </span> : /// </summary>
<span class="lineNum"> 46 </span> : [DataMember]
<span class="lineNum"> 47 </span> : public Type AggregateType { get; set; }
<span class="lineNum"> 48 </span> : }
<span class="lineNum"> 49 </span> : }
</pre>
</td>
</tr>
</table>
<br>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.10</a></td></tr>
</table>
<br>
</body>
</html>
| lgpl-2.1 |
tkemmer/ball | test/RepresentationManager_test.C | 7798 | // -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/CONCEPT/classTest.h>
#include <BALLTestConfig.h>
///////////////////////////
#include <BALL/VIEW/KERNEL/representationManager.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/clippingPlane.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/KERNEL/system.h>
///////////////////////////
/////////////////////////////////////////////////////////////
START_TEST(RepresentationManager)
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace BALL::VIEW;
using namespace std;
char* argv = "asd";
int args = 0;
// need a valid X-Context for the following code:
// QApplication app(args, &argv);
// MainControl mc;
// DisplayProperties* dp = new DisplayProperties(&mc);
// dp->initializeWidget(mc);
// dp->initializePreferencesTab(*mc.getPreferences());
CHECK(CSTR)
RepresentationManager rm;
RESULT
CHECK(RepresentationManager::BALL_CREATE(RepresentationManager))
// no copying support
RESULT
CHECK(RepresentationManager::RepresentationManager& operator = (const RepresentationManager& pm) throw())
// no copying support
RESULT
/*
CHECK(RepresentationManager::bool operator == (const RepresentationManager& pm) const throw())
RepresentationManager r1(&mc), r2(&mc);
TEST_EQUAL(r1 == r2, true)
Representation* rep = new Representation();
r1.insert(*rep);
TEST_EQUAL(r1 == r2, false)
RESULT
RepresentationManager rm(&mc);
*/
RepresentationManager rm;
CHECK(RepresentationManager::clear() throw())
rm.insert(*new Representation());
TEST_EQUAL(rm.getNumberOfRepresentations(), 1)
rm.clear();
TEST_EQUAL(rm.getNumberOfRepresentations(), 0)
RESULT
CHECK(RepresentationManager::remove(Representation& representation, bool send_message = true) throw())
Representation* rep = new Representation();
rm.insert(*rep);
TEST_EQUAL(rm.getNumberOfRepresentations(), 1)
rm.remove(*rep);
TEST_EQUAL(rm.getNumberOfRepresentations(), 0)
RESULT
CHECK(RepresentationManager::insert(Representation& representation, bool send_message = true) throw())
Representation* rep = new Representation();
rm.insert(*rep);
TEST_EQUAL(rm.getNumberOfRepresentations(), 1)
rm.clear();
RESULT
CHECK(RepresentationManager::getRepresentations() const throw())
Representation* rep = new Representation();
rm.clear();
rm.insert(*rep);
TEST_EQUAL(*rm.getRepresentations().begin(), rep)
rm.clear();
TEST_EQUAL(rm.getRepresentations().size(), 0)
RESULT
CHECK(RepresentationManager::createRepresentation() throw())
Representation* rep = rm.createRepresentation();
TEST_EQUAL(*rm.getRepresentations().begin(), rep);
RESULT
CHECK(RepresentationManager::has(const Representation& representation) const throw())
Representation* rep = new Representation;
TEST_EQUAL(rm.has(*rep), false)
rm.clear();
rm.insert(*rep);
TEST_EQUAL(rm.has(*rep), true)
RESULT
CHECK(RepresentationManager::dump(std::ostream& s, Size depth) const throw())
rm.clear();
Representation* rep = new Representation;
rm.insert(*rep);
String filename;
NEW_TMP_FILE(filename)
std::ofstream outfile(filename.c_str(), std::ios::out);
rm.dump(outfile);
outfile.close();
TEST_FILE_REGEXP(filename.c_str(), BALL_TEST_DATA_PATH(RepresentationManager.txt))
RESULT
CHECK(RepresentationManager::begin() throw())
rm.clear();
TEST_EQUAL(rm.begin() == rm.getRepresentations().end(), true)
Representation* rep = rm.createRepresentation();
TEST_EQUAL(*rm.begin(), rep)
RESULT
CHECK(RepresentationManager::end() throw())
rm.clear();
TEST_EQUAL(rm.begin() == rm.getRepresentations().end(), true)
RESULT
Composite composite;
List<const Composite*> cl;
cl.push_back(&composite);
CHECK(RepresentationManager::removedComposite(const Composite& composite, bool update = true) throw())
rm.clear();
Representation* rep = rm.createRepresentation();
rep->setComposites(cl);
Representation* rep2 = rm.createRepresentation();
TEST_EQUAL(rm.getNumberOfRepresentations(), 2)
rm.removedComposite(composite);
TEST_EQUAL(rm.getNumberOfRepresentations(), 1)
TEST_EQUAL(*rm.begin(), rep2);
RESULT
CHECK(RepresentationManager::getRepresentationsOf(const Composite& composite) throw())
rm.clear();
Representation* rep = rm.createRepresentation();
rep->setComposites(cl);
Representation* rep2 = rm.createRepresentation();
TEST_EQUAL(rm.getRepresentationsOf(composite).size(), 1)
TEST_EQUAL(*rm.getRepresentationsOf(composite).begin(), rep)
rm.remove(*rep2);
RESULT
CHECK(RepresentationManager::rebuildAllRepresentations() throw())
rm.clear();
Representation* rep = rm.createRepresentation();
rm.rebuildAllRepresentations();
TEST_EQUAL(rm.willBeUpdated(*rep), true)
Representation* rep2 = rm.createRepresentation();
TEST_EQUAL(rm.willBeUpdated(*rep2), false)
RESULT
CHECK(RepresentationManager::getClippingPlanes() const )
TEST_EQUAL(rm.getClippingPlanes().size(), 0)
RESULT
CHECK(removeClippingPlane(ClippingPlane*))
ClippingPlane pl;
TEST_EQUAL(rm.removeClippingPlane(&pl), false)
RESULT
CHECK(insertClippingPlane(ClippingPlane*))
ClippingPlane* plane = new ClippingPlane();
rm.insertClippingPlane(plane);
TEST_EQUAL(*rm.getClippingPlanes().begin(), plane)
rm.removeClippingPlane(plane);
TEST_EQUAL(rm.getClippingPlanes().size(), 0)
RESULT
/*
Representation rrep;
ClippingPlane rplane;
RepresentationManager& mrm = mc.getRepresentationManager();
System* system = new System();
CHECK(storeRepresentations(INIFile&))
mc.insert(*system);
List<const Composite*> cl;
cl.push_back(system);
mrm.clear();
Representation* rep = mrm.createRepresentation();
rep->setComposites(cl);
rep->setModelType(MODEL_SE_SURFACE);
rep->setColoringMethod(COLORING_TEMPERATURE_FACTOR);
rep->setTransparency(100);
rep->setDrawingMode(DRAWING_MODE_WIREFRAME);
rep->setHidden(true);
rrep = *rep;
rplane.setPoint(Vector3(1,2,3));
rplane.setNormal(Vector3(4,5,6));
rplane.setCappingEnabled(true);
rplane.setActive(true);
mrm.insertClippingPlane(new ClippingPlane(rplane));
String filename;
NEW_TMP_FILE(filename)
INIFile file(filename);
mrm.storeRepresentations(file);
file.write();
TEST_FILE(filename.c_str(), BALL_TEST_DATA_PATH(RepresentationManager2.txt))
RESULT
CHECK(restoreRepresentations(const INIFile& in, const vector<const Composite*>& new_systems))
mrm.clear();
INIFile infile(BALL_TEST_DATA_PATH(RepresentationManager2.txt));
infile.read();
vector<const Composite*> new_systems;
new_systems.push_back(system);
mrm.clear();
TEST_EQUAL(mrm.getNumberOfRepresentations(), 0);
mrm.restoreRepresentations(infile, new_systems);
TEST_EQUAL(mrm.getNumberOfRepresentations(), 1);
if (mrm.getNumberOfRepresentations() == 1)
{
Representation& rep = **mrm.begin();
TEST_EQUAL(rep.getModelType(), rrep.getModelType())
TEST_EQUAL(rep.getColoringMethod(), rrep.getColoringMethod())
TEST_EQUAL(rep.getTransparency(), rrep.getTransparency())
TEST_EQUAL(rep.getDrawingMode(), rrep.getDrawingMode())
TEST_EQUAL(rep.isHidden(), rrep.isHidden())
}
TEST_EQUAL(mrm.getClippingPlanes().size(), 1)
if (mrm.getClippingPlanes().size() == 1)
{
ClippingPlane* tp = *mrm.getClippingPlanes().begin();
TEST_EQUAL(tp->getNormal(), rplane.getNormal())
TEST_EQUAL(tp->getPoint(), rplane.getPoint())
TEST_EQUAL(tp->cappingEnabled(), rplane.cappingEnabled())
}
RESULT
*/
CHECK(focusRepresentation(const Representation&))
RESULT
CHECK(willBeUpdated(const Representation&) const)
RESULT
CHECK(updateRunning())
RESULT
CHECK(startedRendering(Representation*))
RESULT
CHECK(finishedRendering(Representation*))
RESULT
CHECK(isBeeingRendered(const Representation*) const)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| lgpl-2.1 |
oberluz/marble | src/lib/geodata/scene/GeoSceneItem.h | 1856 | /*
Copyright (C) 2008 Torsten Rahn <[email protected]>
This file is part of the KDE project
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef MARBLE_GEOSCENEITEM_H
#define MARBLE_GEOSCENEITEM_H
#include <QtCore/QString>
#include "GeoDocument.h"
namespace Marble
{
class GeoSceneIcon;
/**
* @short The section item in a legend of a GeoScene document.
*/
class GEODATA_EXPORT GeoSceneItem : public GeoNode
{
public:
explicit GeoSceneItem( const QString& name );
~GeoSceneItem();
virtual const char* nodeType() const;
QString name() const;
QString text() const;
void setText( const QString& text );
bool checkable() const;
void setCheckable( bool checkable );
QString connectTo() const;
void setConnectTo( const QString& text );
int spacing() const;
void setSpacing( int spacing );
const GeoSceneIcon* icon() const;
GeoSceneIcon* icon();
private:
Q_DISABLE_COPY( GeoSceneItem )
GeoSceneIcon* m_icon;
QString m_name;
QString m_text;
QString m_connectTo;
bool m_checkable;
int m_spacing;
};
}
#endif
| lgpl-2.1 |
flow123d/dealii | bundled/boost-1.56.0/include/boost/graph/detail/adjacency_list.hpp | 108267 | // -*- c++ -*-
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Copyright 2010 Thomas Claveirole
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek, Thomas Claveirole
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef BOOST_GRAPH_DETAIL_ADJACENCY_LIST_HPP
#define BOOST_GRAPH_DETAIL_ADJACENCY_LIST_HPP
#include <map> // for vertex_map in copy_impl
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/operators.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/pending/container_traits.hpp>
#include <boost/range/irange.hpp>
#include <boost/graph/graph_traits.hpp>
#include <memory>
#include <algorithm>
#include <boost/limits.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/and.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/pending/container_traits.hpp>
#include <boost/graph/detail/adj_list_edge_iterator.hpp>
#include <boost/graph/properties.hpp>
#include <boost/pending/property.hpp>
#include <boost/graph/adjacency_iterator.hpp>
#include <boost/static_assert.hpp>
#include <boost/assert.hpp>
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
#define BOOST_GRAPH_MOVE_IF_POSSIBLE(x) (x)
#else
#include <utility>
#define BOOST_GRAPH_MOVE_IF_POSSIBLE(x) (std::move((x)))
#endif
/*
Outline for this file:
out_edge_iterator and in_edge_iterator implementation
edge_iterator for undirected graph
stored edge types (these object live in the out-edge/in-edge lists)
directed edges helper class
directed graph helper class
undirected graph helper class
bidirectional graph helper class
bidirectional graph helper class (without edge properties)
bidirectional graph helper class (with edge properties)
adjacency_list helper class
adj_list_impl class
vec_adj_list_impl class
adj_list_gen class
vertex property map
edge property map
Note: it would be nice to merge some of the undirected and
bidirectional code... it is awful similar.
*/
namespace boost {
namespace detail {
template <typename DirectedS>
struct directed_category_traits {
typedef directed_tag directed_category;
};
template <>
struct directed_category_traits<directedS> {
typedef directed_tag directed_category;
};
template <>
struct directed_category_traits<undirectedS> {
typedef undirected_tag directed_category;
};
template <>
struct directed_category_traits<bidirectionalS> {
typedef bidirectional_tag directed_category;
};
template <class Vertex>
struct target_is {
target_is(const Vertex& v) : m_target(v) { }
template <class StoredEdge>
bool operator()(const StoredEdge& e) const {
return e.get_target() == m_target;
}
Vertex m_target;
};
// O(E/V)
template <class EdgeList, class vertex_descriptor>
void erase_from_incidence_list(EdgeList& el, vertex_descriptor v,
allow_parallel_edge_tag)
{
boost::graph_detail::erase_if(el, detail::target_is<vertex_descriptor>(v));
}
// O(log(E/V))
template <class EdgeList, class vertex_descriptor>
void erase_from_incidence_list(EdgeList& el, vertex_descriptor v,
disallow_parallel_edge_tag)
{
typedef typename EdgeList::value_type StoredEdge;
el.erase(StoredEdge(v));
}
//=========================================================================
// Out-Edge and In-Edge Iterator Implementation
template <class BaseIter, class VertexDescriptor, class EdgeDescriptor, class Difference>
struct out_edge_iter
: iterator_adaptor<
out_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
>
{
typedef iterator_adaptor<
out_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
> super_t;
inline out_edge_iter() { }
inline out_edge_iter(const BaseIter& i, const VertexDescriptor& src)
: super_t(i), m_src(src) { }
inline EdgeDescriptor
dereference() const
{
return EdgeDescriptor(m_src, (*this->base()).get_target(),
&(*this->base()).get_property());
}
VertexDescriptor m_src;
};
template <class BaseIter, class VertexDescriptor, class EdgeDescriptor, class Difference>
struct in_edge_iter
: iterator_adaptor<
in_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
>
{
typedef iterator_adaptor<
in_edge_iter<BaseIter, VertexDescriptor, EdgeDescriptor, Difference>
, BaseIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
> super_t;
inline in_edge_iter() { }
inline in_edge_iter(const BaseIter& i, const VertexDescriptor& src)
: super_t(i), m_src(src) { }
inline EdgeDescriptor
dereference() const
{
return EdgeDescriptor((*this->base()).get_target(), m_src,
&this->base()->get_property());
}
VertexDescriptor m_src;
};
//=========================================================================
// Undirected Edge Iterator Implementation
template <class EdgeIter, class EdgeDescriptor, class Difference>
struct undirected_edge_iter
: iterator_adaptor<
undirected_edge_iter<EdgeIter, EdgeDescriptor, Difference>
, EdgeIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
>
{
typedef iterator_adaptor<
undirected_edge_iter<EdgeIter, EdgeDescriptor, Difference>
, EdgeIter
, EdgeDescriptor
, use_default
, EdgeDescriptor
, Difference
> super_t;
undirected_edge_iter() {}
explicit undirected_edge_iter(EdgeIter i)
: super_t(i) {}
inline EdgeDescriptor
dereference() const {
return EdgeDescriptor(
(*this->base()).m_source
, (*this->base()).m_target
, &this->base()->get_property());
}
};
//=========================================================================
// Edge Storage Types (stored in the out-edge/in-edge lists)
template <class Vertex>
class stored_edge
: public boost::equality_comparable1< stored_edge<Vertex>,
boost::less_than_comparable1< stored_edge<Vertex> > >
{
public:
typedef no_property property_type;
inline stored_edge() { }
inline stored_edge(Vertex target, const no_property& = no_property())
: m_target(target) { }
// Need to write this explicitly so stored_edge_property can
// invoke Base::operator= (at least, for SGI MIPSPro compiler)
inline stored_edge& operator=(const stored_edge& x) {
m_target = x.m_target;
return *this;
}
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS)
// Copy-construct is not necessary since stored_edge_property is non-copyable (only movable)
// but it doesn't hurt to have it, does it?
stored_edge(const stored_edge&) = default;
stored_edge(stored_edge&&) = default;
stored_edge& operator=(stored_edge&&) = default;
#endif // If no rvalue support, no need to define move functions.
inline Vertex& get_target() const { return m_target; }
inline const no_property& get_property() const { return s_prop; }
inline bool operator==(const stored_edge& x) const
{ return m_target == x.get_target(); }
inline bool operator<(const stored_edge& x) const
{ return m_target < x.get_target(); }
//protected: need to add hash<> as a friend
static no_property s_prop;
// Sometimes target not used as key in the set, and in that case
// it is ok to change the target.
mutable Vertex m_target;
};
template <class Vertex>
no_property stored_edge<Vertex>::s_prop;
#if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) || defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS)
template <class Vertex, class Property>
class stored_edge_property : public stored_edge<Vertex> {
typedef stored_edge_property self;
typedef stored_edge<Vertex> Base;
public:
typedef Property property_type;
inline stored_edge_property() { }
inline stored_edge_property(Vertex target,
const Property& p = Property())
: stored_edge<Vertex>(target), m_property(new Property(p)) { }
stored_edge_property(const self& x)
: Base(x), m_property(const_cast<self&>(x).m_property) { }
self& operator=(const self& x) {
Base::operator=(x);
m_property = const_cast<self&>(x).m_property;
return *this;
}
inline Property& get_property() { return *m_property; }
inline const Property& get_property() const { return *m_property; }
protected:
// Holding the property by-value causes edge-descriptor
// invalidation for add_edge() with EdgeList=vecS. Instead we
// hold a pointer to the property. std::auto_ptr is not
// a perfect fit for the job, but it is darn close.
std::auto_ptr<Property> m_property;
};
#else
template <class Vertex, class Property>
class stored_edge_property : public stored_edge<Vertex> {
typedef stored_edge_property self;
typedef stored_edge<Vertex> Base;
public:
typedef Property property_type;
inline stored_edge_property() { }
inline stored_edge_property(Vertex target,
const Property& p = Property())
: stored_edge<Vertex>(target), m_property(new Property(p)) { }
#if defined(BOOST_MSVC) || (defined(BOOST_GCC) && (BOOST_GCC / 100) < 406)
stored_edge_property(self&& x) : Base(static_cast< Base const& >(x)) {
m_property.swap(x.m_property);
}
stored_edge_property(self const& x) : Base(static_cast< Base const& >(x)) {
m_property.swap(const_cast<self&>(x).m_property);
}
self& operator=(self&& x) {
Base::operator=(static_cast< Base const& >(x));
m_property = std::move(x.m_property);
return *this;
}
self& operator=(self const& x) {
Base::operator=(static_cast< Base const& >(x));
m_property = std::move(const_cast<self&>(x).m_property);
return *this;
}
#else
stored_edge_property(self&& x) = default;
self& operator=(self&& x) = default;
#endif
inline Property& get_property() { return *m_property; }
inline const Property& get_property() const { return *m_property; }
protected:
std::unique_ptr<Property> m_property;
};
#endif
template <class Vertex, class Iter, class Property>
class stored_edge_iter
: public stored_edge<Vertex>
{
public:
typedef Property property_type;
inline stored_edge_iter() { }
inline stored_edge_iter(Vertex v)
: stored_edge<Vertex>(v) { }
inline stored_edge_iter(Vertex v, Iter i, void* = 0)
: stored_edge<Vertex>(v), m_iter(i) { }
inline Property& get_property() { return m_iter->get_property(); }
inline const Property& get_property() const {
return m_iter->get_property();
}
inline Iter get_iter() const { return m_iter; }
protected:
Iter m_iter;
};
// For when the EdgeList is a std::vector.
// Want to make the iterator stable, so use an offset
// instead of an iterator into a std::vector
template <class Vertex, class EdgeVec, class Property>
class stored_ra_edge_iter
: public stored_edge<Vertex>
{
typedef typename EdgeVec::iterator Iter;
public:
typedef Property property_type;
inline stored_ra_edge_iter() { }
inline explicit stored_ra_edge_iter(Vertex v) // Only used for comparisons
: stored_edge<Vertex>(v), m_i(0), m_vec(0){ }
inline stored_ra_edge_iter(Vertex v, Iter i, EdgeVec* edge_vec)
: stored_edge<Vertex>(v), m_i(i - edge_vec->begin()), m_vec(edge_vec){ }
inline Property& get_property() { BOOST_ASSERT ((m_vec != 0)); return (*m_vec)[m_i].get_property(); }
inline const Property& get_property() const {
BOOST_ASSERT ((m_vec != 0));
return (*m_vec)[m_i].get_property();
}
inline Iter get_iter() const { BOOST_ASSERT ((m_vec != 0)); return m_vec->begin() + m_i; }
protected:
std::size_t m_i;
EdgeVec* m_vec;
};
} // namespace detail
template <class Tag, class Vertex, class Property>
const typename property_value<Property,Tag>::type&
get(Tag property_tag,
const detail::stored_edge_property<Vertex, Property>& e)
{
return get_property_value(e.get_property(), property_tag);
}
template <class Tag, class Vertex, class Iter, class Property>
const typename property_value<Property,Tag>::type&
get(Tag property_tag,
const detail::stored_edge_iter<Vertex, Iter, Property>& e)
{
return get_property_value(e.get_property(), property_tag);
}
template <class Tag, class Vertex, class EdgeVec, class Property>
const typename property_value<Property,Tag>::type&
get(Tag property_tag,
const detail::stored_ra_edge_iter<Vertex, EdgeVec, Property>& e)
{
return get_property_value(e.get_property(), property_tag);
}
//=========================================================================
// Directed Edges Helper Class
namespace detail {
// O(E/V)
template <class edge_descriptor, class EdgeList, class StoredProperty>
inline void
remove_directed_edge_dispatch(edge_descriptor, EdgeList& el,
StoredProperty& p)
{
for (typename EdgeList::iterator i = el.begin();
i != el.end(); ++i)
if (&(*i).get_property() == &p) {
el.erase(i);
return;
}
}
template <class incidence_iterator, class EdgeList, class Predicate>
inline void
remove_directed_edge_if_dispatch(incidence_iterator first,
incidence_iterator last,
EdgeList& el, Predicate pred,
boost::allow_parallel_edge_tag)
{
// remove_if
while (first != last && !pred(*first))
++first;
incidence_iterator i = first;
if (first != last)
for (++i; i != last; ++i)
if (!pred(*i)) {
*first.base() = BOOST_GRAPH_MOVE_IF_POSSIBLE(*i.base());
++first;
}
el.erase(first.base(), el.end());
}
template <class incidence_iterator, class EdgeList, class Predicate>
inline void
remove_directed_edge_if_dispatch(incidence_iterator first,
incidence_iterator last,
EdgeList& el,
Predicate pred,
boost::disallow_parallel_edge_tag)
{
for (incidence_iterator next = first;
first != last; first = next) {
++next;
if (pred(*first))
el.erase( first.base() );
}
}
template <class PropT, class Graph, class incidence_iterator,
class EdgeList, class Predicate>
inline void
undirected_remove_out_edge_if_dispatch(Graph& g,
incidence_iterator first,
incidence_iterator last,
EdgeList& el, Predicate pred,
boost::allow_parallel_edge_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
// remove_if
while (first != last && !pred(*first))
++first;
incidence_iterator i = first;
bool self_loop_removed = false;
if (first != last)
for (; i != last; ++i) {
if (self_loop_removed) {
/* With self loops, the descriptor will show up
* twice. The first time it will be removed, and now it
* will be skipped.
*/
self_loop_removed = false;
}
else if (!pred(*i)) {
*first.base() = BOOST_GRAPH_MOVE_IF_POSSIBLE(*i.base());
++first;
} else {
if (source(*i, g) == target(*i, g)) self_loop_removed = true;
else {
// Remove the edge from the target
detail::remove_directed_edge_dispatch
(*i,
g.out_edge_list(target(*i, g)),
*(PropT*)(*i).get_property());
}
// Erase the edge property
g.m_edges.erase( (*i.base()).get_iter() );
}
}
el.erase(first.base(), el.end());
}
template <class PropT, class Graph, class incidence_iterator,
class EdgeList, class Predicate>
inline void
undirected_remove_out_edge_if_dispatch(Graph& g,
incidence_iterator first,
incidence_iterator last,
EdgeList& el,
Predicate pred,
boost::disallow_parallel_edge_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
for (incidence_iterator next = first;
first != last; first = next) {
++next;
if (pred(*first)) {
if (source(*first, g) != target(*first, g)) {
// Remove the edge from the target
detail::remove_directed_edge_dispatch
(*first,
g.out_edge_list(target(*first, g)),
*(PropT*)(*first).get_property());
}
// Erase the edge property
g.m_edges.erase( (*first.base()).get_iter() );
// Erase the edge in the source
el.erase( first.base() );
}
}
}
// O(E/V)
template <class edge_descriptor, class EdgeList, class StoredProperty>
inline void
remove_directed_edge_dispatch(edge_descriptor e, EdgeList& el,
no_property&)
{
for (typename EdgeList::iterator i = el.begin();
i != el.end(); ++i)
if ((*i).get_target() == e.m_target) {
el.erase(i);
return;
}
}
} // namespace detail
template <class Config>
struct directed_edges_helper {
// Placement of these overloaded remove_edge() functions
// inside the class avoids a VC++ bug.
// O(E/V)
inline void
remove_edge(typename Config::edge_descriptor e)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(*this);
typename Config::OutEdgeList& el = g.out_edge_list(source(e, g));
typedef typename Config::OutEdgeList::value_type::property_type PType;
detail::remove_directed_edge_dispatch(e, el,
*(PType*)e.get_property());
}
// O(1)
inline void
remove_edge(typename Config::out_edge_iterator iter)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(*this);
typename Config::edge_descriptor e = *iter;
typename Config::OutEdgeList& el = g.out_edge_list(source(e, g));
el.erase(iter.base());
}
};
// O(1)
template <class Config>
inline std::pair<typename Config::edge_iterator,
typename Config::edge_iterator>
edges(const directed_edges_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_iterator edge_iterator;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
return std::make_pair( edge_iterator(g.vertex_set().begin(),
g.vertex_set().begin(),
g.vertex_set().end(), g),
edge_iterator(g.vertex_set().begin(),
g.vertex_set().end(),
g.vertex_set().end(), g) );
}
//=========================================================================
// Directed Graph Helper Class
struct adj_list_dir_traversal_tag :
public virtual vertex_list_graph_tag,
public virtual incidence_graph_tag,
public virtual adjacency_graph_tag,
public virtual edge_list_graph_tag { };
template <class Config>
struct directed_graph_helper
: public directed_edges_helper<Config> {
typedef typename Config::edge_descriptor edge_descriptor;
typedef adj_list_dir_traversal_tag traversal_category;
};
// O(E/V)
template <class Config>
inline void
remove_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
detail::erase_from_incidence_list(g.out_edge_list(u), v, Cat());
}
template <class Config, class Predicate>
inline void
remove_out_edge_if(typename Config::vertex_descriptor u, Predicate pred,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::out_edge_iterator first, last;
boost::tie(first, last) = out_edges(u, g);
typedef typename Config::edge_parallel_category edge_parallel_category;
detail::remove_directed_edge_if_dispatch
(first, last, g.out_edge_list(u), pred, edge_parallel_category());
}
template <class Config, class Predicate>
inline void
remove_edge_if(Predicate pred, directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
remove_out_edge_if(*vi, pred, g);
}
template <class EdgeOrIter, class Config>
inline void
remove_edge(EdgeOrIter e_or_iter, directed_graph_helper<Config>& g_)
{
g_.remove_edge(e_or_iter);
}
// O(V + E) for allow_parallel_edges
// O(V * log(E/V)) for disallow_parallel_edges
template <class Config>
inline void
clear_vertex(typename Config::vertex_descriptor u,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::vertex_iterator vi, viend;
for (boost::tie(vi, viend) = vertices(g); vi != viend; ++vi)
detail::erase_from_incidence_list(g.out_edge_list(*vi), u, Cat());
g.out_edge_list(u).clear();
// clear() should be a req of Sequence and AssociativeContainer,
// or maybe just Container
}
template <class Config>
inline void
clear_out_edges(typename Config::vertex_descriptor u,
directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
g.out_edge_list(u).clear();
// clear() should be a req of Sequence and AssociativeContainer,
// or maybe just Container
}
// O(V), could do better...
template <class Config>
inline typename Config::edges_size_type
num_edges(const directed_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
typename Config::edges_size_type num_e = 0;
typename Config::vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
num_e += out_degree(*vi, g);
return num_e;
}
// O(1) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline std::pair<typename directed_graph_helper<Config>::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
directed_graph_helper<Config>& g_)
{
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::graph_type graph_type;
typedef typename Config::StoredEdge StoredEdge;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList::iterator i;
bool inserted;
boost::tie(i, inserted) = boost::graph_detail::push(g.out_edge_list(u),
StoredEdge(v, p));
return std::make_pair(edge_descriptor(u, v, &(*i).get_property()),
inserted);
}
// Did not use default argument here because that
// causes Visual C++ to get confused.
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
directed_graph_helper<Config>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
//=========================================================================
// Undirected Graph Helper Class
template <class Config>
struct undirected_graph_helper;
struct undir_adj_list_traversal_tag :
public virtual vertex_list_graph_tag,
public virtual incidence_graph_tag,
public virtual adjacency_graph_tag,
public virtual edge_list_graph_tag,
public virtual bidirectional_graph_tag { };
namespace detail {
// using class with specialization for dispatch is a VC++ workaround.
template <class StoredProperty>
struct remove_undirected_edge_dispatch {
// O(E/V)
template <class edge_descriptor, class Config>
static void
apply(edge_descriptor e,
undirected_graph_helper<Config>& g_,
StoredProperty& p)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList& out_el = g.out_edge_list(source(e, g));
typename Config::OutEdgeList::iterator out_i = out_el.begin();
typename Config::EdgeIter edge_iter_to_erase;
for (; out_i != out_el.end(); ++out_i)
if (&(*out_i).get_property() == &p) {
edge_iter_to_erase = (*out_i).get_iter();
out_el.erase(out_i);
break;
}
typename Config::OutEdgeList& in_el = g.out_edge_list(target(e, g));
typename Config::OutEdgeList::iterator in_i = in_el.begin();
for (; in_i != in_el.end(); ++in_i)
if (&(*in_i).get_property() == &p) {
in_el.erase(in_i);
break;
}
g.m_edges.erase(edge_iter_to_erase);
}
};
template <>
struct remove_undirected_edge_dispatch<no_property> {
// O(E/V)
template <class edge_descriptor, class Config>
static void
apply(edge_descriptor e,
undirected_graph_helper<Config>& g_,
no_property&)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
no_property* p = (no_property*)e.get_property();
typename Config::OutEdgeList& out_el = g.out_edge_list(source(e, g));
typename Config::OutEdgeList::iterator out_i = out_el.begin();
typename Config::EdgeIter edge_iter_to_erase;
for (; out_i != out_el.end(); ++out_i)
if (&(*out_i).get_property() == p) {
edge_iter_to_erase = (*out_i).get_iter();
out_el.erase(out_i);
break;
}
typename Config::OutEdgeList& in_el = g.out_edge_list(target(e, g));
typename Config::OutEdgeList::iterator in_i = in_el.begin();
for (; in_i != in_el.end(); ++in_i)
if (&(*in_i).get_property() == p) {
in_el.erase(in_i);
break;
}
g.m_edges.erase(edge_iter_to_erase);
}
};
// O(E/V)
template <class Graph, class EdgeList, class Vertex>
inline void
remove_edge_and_property(Graph& g, EdgeList& el, Vertex v,
boost::allow_parallel_edge_tag cat)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typename EdgeList::iterator i = el.begin(), end = el.end();
for (; i != end; ++i) {
if ((*i).get_target() == v) {
// NOTE: Wihtout this skip, this loop will double-delete properties
// of loop edges. This solution is based on the observation that
// the incidence edges of a vertex with a loop are adjacent in the
// out edge list. This *may* actually hold for multisets also.
bool skip = (boost::next(i) != end && i->get_iter() == boost::next(i)->get_iter());
g.m_edges.erase((*i).get_iter());
if (skip) ++i;
}
}
detail::erase_from_incidence_list(el, v, cat);
}
// O(log(E/V))
template <class Graph, class EdgeList, class Vertex>
inline void
remove_edge_and_property(Graph& g, EdgeList& el, Vertex v,
boost::disallow_parallel_edge_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename EdgeList::value_type StoredEdge;
typename EdgeList::iterator i = el.find(StoredEdge(v)), end = el.end();
if (i != end) {
g.m_edges.erase((*i).get_iter());
el.erase(i);
}
}
} // namespace detail
template <class Vertex, class EdgeProperty>
struct list_edge // short name due to VC++ truncation and linker problems
: public boost::detail::edge_base<boost::undirected_tag, Vertex>
{
typedef EdgeProperty property_type;
typedef boost::detail::edge_base<boost::undirected_tag, Vertex> Base;
list_edge(Vertex u, Vertex v, const EdgeProperty& p = EdgeProperty())
: Base(u, v), m_property(p) { }
EdgeProperty& get_property() { return m_property; }
const EdgeProperty& get_property() const { return m_property; }
// the following methods should never be used, but are needed
// to make SGI MIPSpro C++ happy
list_edge() { }
bool operator==(const list_edge&) const { return false; }
bool operator<(const list_edge&) const { return false; }
EdgeProperty m_property;
};
template <class Config>
struct undirected_graph_helper {
typedef undir_adj_list_traversal_tag traversal_category;
// Placement of these overloaded remove_edge() functions
// inside the class avoids a VC++ bug.
// O(E/V)
inline void
remove_edge(typename Config::edge_descriptor e)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::OutEdgeList::value_type::property_type PType;
detail::remove_undirected_edge_dispatch<PType>::apply
(e, *this, *(PType*)e.get_property());
}
// O(E/V)
inline void
remove_edge(typename Config::out_edge_iterator iter)
{
this->remove_edge(*iter);
}
};
// Had to make these non-members to avoid accidental instantiation
// on SGI MIPSpro C++
template <class C>
inline typename C::InEdgeList&
in_edge_list(undirected_graph_helper<C>&,
typename C::vertex_descriptor v)
{
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_out_edges;
}
template <class C>
inline const typename C::InEdgeList&
in_edge_list(const undirected_graph_helper<C>&,
typename C::vertex_descriptor v) {
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_out_edges;
}
// O(E/V)
template <class EdgeOrIter, class Config>
inline void
remove_edge(EdgeOrIter e, undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
g_.remove_edge(e);
}
// O(E/V) or O(log(E/V))
template <class Config>
void
remove_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::edge_parallel_category Cat;
detail::remove_edge_and_property(g, g.out_edge_list(u), v, Cat());
detail::erase_from_incidence_list(g.out_edge_list(v), u, Cat());
}
template <class Config, class Predicate>
void
remove_out_edge_if(typename Config::vertex_descriptor u, Predicate pred,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::OutEdgeList::value_type::property_type PropT;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::out_edge_iterator first, last;
boost::tie(first, last) = out_edges(u, g);
typedef typename Config::edge_parallel_category Cat;
detail::undirected_remove_out_edge_if_dispatch<PropT>
(g, first, last, g.out_edge_list(u), pred, Cat());
}
template <class Config, class Predicate>
void
remove_in_edge_if(typename Config::vertex_descriptor u, Predicate pred,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
remove_out_edge_if(u, pred, g_);
}
// O(E/V * E) or O(log(E/V) * E)
template <class Predicate, class Config>
void
remove_edge_if(Predicate pred, undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::edge_iterator ei, ei_end, next;
boost::tie(ei, ei_end) = edges(g);
for (next = ei; ei != ei_end; ei = next) {
++next;
if (pred(*ei))
remove_edge(*ei, g);
}
}
// O(1)
template <class Config>
inline std::pair<typename Config::edge_iterator,
typename Config::edge_iterator>
edges(const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_iterator edge_iterator;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
return std::make_pair( edge_iterator(g.m_edges.begin()),
edge_iterator(g.m_edges.end()) );
}
// O(1)
template <class Config>
inline typename Config::edges_size_type
num_edges(const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
return g.m_edges.size();
}
// O(E/V * E/V)
template <class Config>
inline void
clear_vertex(typename Config::vertex_descriptor u,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
while (true) {
typename Config::out_edge_iterator ei, ei_end;
boost::tie(ei, ei_end) = out_edges(u, g);
if (ei == ei_end) break;
remove_edge(*ei, g);
}
}
// O(1) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
undirected_graph_helper<Config>& g_)
{
typedef typename Config::StoredEdge StoredEdge;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
bool inserted;
typename Config::EdgeContainer::value_type e(u, v, p);
typename Config::EdgeContainer::iterator p_iter
= graph_detail::push(g.m_edges, e).first;
typename Config::OutEdgeList::iterator i;
boost::tie(i, inserted) = boost::graph_detail::push(g.out_edge_list(u),
StoredEdge(v, p_iter, &g.m_edges));
if (inserted) {
boost::graph_detail::push(g.out_edge_list(v), StoredEdge(u, p_iter, &g.m_edges));
return std::make_pair(edge_descriptor(u, v, &p_iter->get_property()),
true);
} else {
g.m_edges.erase(p_iter);
return std::make_pair
(edge_descriptor(u, v, &i->get_iter()->get_property()), false);
}
}
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
undirected_graph_helper<Config>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
// O(1)
template <class Config>
inline typename Config::degree_size_type
degree(typename Config::vertex_descriptor u,
const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type Graph;
const Graph& g = static_cast<const Graph&>(g_);
return out_degree(u, g);
}
template <class Config>
inline std::pair<typename Config::in_edge_iterator,
typename Config::in_edge_iterator>
in_edges(typename Config::vertex_descriptor u,
const undirected_graph_helper<Config>& g_)
{
typedef typename Config::graph_type Graph;
const Graph& cg = static_cast<const Graph&>(g_);
Graph& g = const_cast<Graph&>(cg);
typedef typename Config::in_edge_iterator in_edge_iterator;
return
std::make_pair(in_edge_iterator(g.out_edge_list(u).begin(), u),
in_edge_iterator(g.out_edge_list(u).end(), u));
}
template <class Config>
inline typename Config::degree_size_type
in_degree(typename Config::vertex_descriptor u,
const undirected_graph_helper<Config>& g_)
{ return degree(u, g_); }
//=========================================================================
// Bidirectional Graph Helper Class
struct bidir_adj_list_traversal_tag :
public virtual vertex_list_graph_tag,
public virtual incidence_graph_tag,
public virtual adjacency_graph_tag,
public virtual edge_list_graph_tag,
public virtual bidirectional_graph_tag { };
template <class Config>
struct bidirectional_graph_helper
: public directed_edges_helper<Config> {
typedef bidir_adj_list_traversal_tag traversal_category;
};
// Had to make these non-members to avoid accidental instantiation
// on SGI MIPSpro C++
template <class C>
inline typename C::InEdgeList&
in_edge_list(bidirectional_graph_helper<C>&,
typename C::vertex_descriptor v)
{
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_in_edges;
}
template <class C>
inline const typename C::InEdgeList&
in_edge_list(const bidirectional_graph_helper<C>&,
typename C::vertex_descriptor v) {
typename C::stored_vertex* sv = (typename C::stored_vertex*)v;
return sv->m_in_edges;
}
template <class Predicate, class Config>
inline void
remove_edge_if(Predicate pred, bidirectional_graph_helper<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::edge_iterator ei, ei_end, next;
boost::tie(ei, ei_end) = edges(g);
for (next = ei; ei != ei_end; ei = next) {
++next;
if (pred(*ei))
remove_edge(*ei, g);
}
}
template <class Config>
inline std::pair<typename Config::in_edge_iterator,
typename Config::in_edge_iterator>
in_edges(typename Config::vertex_descriptor u,
const bidirectional_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
typedef typename Config::in_edge_iterator in_edge_iterator;
return
std::make_pair(in_edge_iterator(in_edge_list(g, u).begin(), u),
in_edge_iterator(in_edge_list(g, u).end(), u));
}
// O(1)
template <class Config>
inline std::pair<typename Config::edge_iterator,
typename Config::edge_iterator>
edges(const bidirectional_graph_helper<Config>& g_)
{
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_iterator edge_iterator;
const graph_type& cg = static_cast<const graph_type&>(g_);
graph_type& g = const_cast<graph_type&>(cg);
return std::make_pair( edge_iterator(g.m_edges.begin()),
edge_iterator(g.m_edges.end()) );
}
//=========================================================================
// Bidirectional Graph Helper Class (with edge properties)
template <class Config>
struct bidirectional_graph_helper_with_property
: public bidirectional_graph_helper<Config>
{
typedef typename Config::graph_type graph_type;
typedef typename Config::out_edge_iterator out_edge_iterator;
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
void*)
{ return out_edges(source(e, g), g); }
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
setS*)
{ return edge_range(source(e, g), target(e, g), g); }
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
multisetS*)
{ return edge_range(source(e, g), target(e, g), g); }
std::pair<out_edge_iterator, out_edge_iterator>
get_parallel_edge_sublist(typename Config::edge_descriptor e,
const graph_type& g,
hash_setS*)
{ return edge_range(source(e, g), target(e, g), g); }
// Placement of these overloaded remove_edge() functions
// inside the class avoids a VC++ bug.
// O(E/V) or O(log(E/V))
void
remove_edge(typename Config::edge_descriptor e)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
graph_type& g = static_cast<graph_type&>(*this);
typedef typename Config::edgelist_selector OutEdgeListS;
std::pair<out_edge_iterator, out_edge_iterator> rng =
get_parallel_edge_sublist(e, g, (OutEdgeListS*)(0));
rng.first = std::find(rng.first, rng.second, e);
BOOST_ASSERT(rng.first != rng.second);
remove_edge(rng.first);
}
inline void
remove_edge(typename Config::out_edge_iterator iter)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(*this);
typename Config::edge_descriptor e = *iter;
typename Config::OutEdgeList& oel = g.out_edge_list(source(e, g));
typename Config::InEdgeList& iel = in_edge_list(g, target(e, g));
typedef typename Config::OutEdgeList::value_type::property_type PType;
PType& p = *(PType*)e.get_property();
detail::remove_directed_edge_dispatch(*iter, iel, p);
g.m_edges.erase(iter.base()->get_iter());
oel.erase(iter.base());
}
};
// O(E/V) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline void
remove_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::edge_parallel_category Cat;
detail::remove_edge_and_property(g, g.out_edge_list(u), v, Cat());
detail::erase_from_incidence_list(in_edge_list(g, v), u, Cat());
}
// O(E/V) or O(log(E/V))
template <class EdgeOrIter, class Config>
inline void
remove_edge(EdgeOrIter e,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
g_.remove_edge(e);
}
template <class Config, class Predicate>
inline void
remove_out_edge_if(typename Config::vertex_descriptor u, Predicate pred,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::OutEdgeList::value_type::property_type PropT;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::EdgeIter EdgeIter;
typedef std::vector<EdgeIter> Garbage;
Garbage garbage;
// First remove the edges from the targets' in-edge lists and
// from the graph's edge set list.
typename Config::out_edge_iterator out_i, out_end;
for (boost::tie(out_i, out_end) = out_edges(u, g); out_i != out_end; ++out_i)
if (pred(*out_i)) {
detail::remove_directed_edge_dispatch
(*out_i, in_edge_list(g, target(*out_i, g)),
*(PropT*)(*out_i).get_property());
// Put in garbage to delete later. Will need the properties
// for the remove_if of the out-edges.
garbage.push_back((*out_i.base()).get_iter());
}
// Now remove the edges from this out-edge list.
typename Config::out_edge_iterator first, last;
boost::tie(first, last) = out_edges(u, g);
typedef typename Config::edge_parallel_category Cat;
detail::remove_directed_edge_if_dispatch
(first, last, g.out_edge_list(u), pred, Cat());
// Now delete the edge properties from the g.m_edges list
for (typename Garbage::iterator i = garbage.begin();
i != garbage.end(); ++i)
g.m_edges.erase(*i);
}
template <class Config, class Predicate>
inline void
remove_in_edge_if(typename Config::vertex_descriptor v, Predicate pred,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::OutEdgeList::value_type::property_type PropT;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::EdgeIter EdgeIter;
typedef std::vector<EdgeIter> Garbage;
Garbage garbage;
// First remove the edges from the sources' out-edge lists and
// from the graph's edge set list.
typename Config::in_edge_iterator in_i, in_end;
for (boost::tie(in_i, in_end) = in_edges(v, g); in_i != in_end; ++in_i)
if (pred(*in_i)) {
typename Config::vertex_descriptor u = source(*in_i, g);
detail::remove_directed_edge_dispatch
(*in_i, g.out_edge_list(u), *(PropT*)(*in_i).get_property());
// Put in garbage to delete later. Will need the properties
// for the remove_if of the out-edges.
garbage.push_back((*in_i.base()).get_iter());
}
// Now remove the edges from this in-edge list.
typename Config::in_edge_iterator first, last;
boost::tie(first, last) = in_edges(v, g);
typedef typename Config::edge_parallel_category Cat;
detail::remove_directed_edge_if_dispatch
(first, last, in_edge_list(g, v), pred, Cat());
// Now delete the edge properties from the g.m_edges list
for (typename Garbage::iterator i = garbage.begin();
i != garbage.end(); ++i)
g.m_edges.erase(*i);
}
// O(1)
template <class Config>
inline typename Config::edges_size_type
num_edges(const bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
return g.m_edges.size();
}
// O(E/V * E/V) for allow_parallel_edge_tag
// O(E/V * log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline void
clear_vertex(typename Config::vertex_descriptor u,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::iterator
ei = el.begin(), ei_end = el.end();
for (; ei != ei_end; ++ei) {
detail::erase_from_incidence_list
(in_edge_list(g, (*ei).get_target()), u, Cat());
g.m_edges.erase((*ei).get_iter());
}
typename Config::InEdgeList& in_el = in_edge_list(g, u);
typename Config::InEdgeList::iterator
in_ei = in_el.begin(), in_ei_end = in_el.end();
for (; in_ei != in_ei_end; ++in_ei) {
detail::erase_from_incidence_list
(g.out_edge_list((*in_ei).get_target()), u, Cat());
g.m_edges.erase((*in_ei).get_iter());
}
g.out_edge_list(u).clear();
in_edge_list(g, u).clear();
}
template <class Config>
inline void
clear_out_edges(typename Config::vertex_descriptor u,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::iterator
ei = el.begin(), ei_end = el.end();
for (; ei != ei_end; ++ei) {
detail::erase_from_incidence_list
(in_edge_list(g, (*ei).get_target()), u, Cat());
g.m_edges.erase((*ei).get_iter());
}
g.out_edge_list(u).clear();
}
template <class Config>
inline void
clear_in_edges(typename Config::vertex_descriptor u,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Config::graph_type graph_type;
typedef typename Config::edge_parallel_category Cat;
graph_type& g = static_cast<graph_type&>(g_);
typename Config::InEdgeList& in_el = in_edge_list(g, u);
typename Config::InEdgeList::iterator
in_ei = in_el.begin(), in_ei_end = in_el.end();
for (; in_ei != in_ei_end; ++in_ei) {
detail::erase_from_incidence_list
(g.out_edge_list((*in_ei).get_target()), u, Cat());
g.m_edges.erase((*in_ei).get_iter());
}
in_edge_list(g, u).clear();
}
// O(1) for allow_parallel_edge_tag
// O(log(E/V)) for disallow_parallel_edge_tag
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::graph_type graph_type;
graph_type& g = static_cast<graph_type&>(g_);
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::StoredEdge StoredEdge;
bool inserted;
typename Config::EdgeContainer::value_type e(u, v, p);
typename Config::EdgeContainer::iterator p_iter
= graph_detail::push(g.m_edges, e).first;
typename Config::OutEdgeList::iterator i;
boost::tie(i, inserted) = boost::graph_detail::push(g.out_edge_list(u),
StoredEdge(v, p_iter, &g.m_edges));
if (inserted) {
boost::graph_detail::push(in_edge_list(g, v), StoredEdge(u, p_iter, &g.m_edges));
return std::make_pair(edge_descriptor(u, v, &p_iter->m_property),
true);
} else {
g.m_edges.erase(p_iter);
return std::make_pair(edge_descriptor(u, v,
&i->get_iter()->get_property()),
false);
}
}
template <class Config>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
bidirectional_graph_helper_with_property<Config>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
// O(1)
template <class Config>
inline typename Config::degree_size_type
degree(typename Config::vertex_descriptor u,
const bidirectional_graph_helper_with_property<Config>& g_)
{
typedef typename Config::graph_type graph_type;
const graph_type& g = static_cast<const graph_type&>(g_);
return in_degree(u, g) + out_degree(u, g);
}
//=========================================================================
// Adjacency List Helper Class
template <class Config, class Base>
struct adj_list_helper : public Base
{
typedef typename Config::graph_type AdjList;
typedef typename Config::vertex_descriptor vertex_descriptor;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::out_edge_iterator out_edge_iterator;
typedef typename Config::in_edge_iterator in_edge_iterator;
typedef typename Config::adjacency_iterator adjacency_iterator;
typedef typename Config::inv_adjacency_iterator inv_adjacency_iterator;
typedef typename Config::vertex_iterator vertex_iterator;
typedef typename Config::edge_iterator edge_iterator;
typedef typename Config::directed_category directed_category;
typedef typename Config::edge_parallel_category edge_parallel_category;
typedef typename Config::vertices_size_type vertices_size_type;
typedef typename Config::edges_size_type edges_size_type;
typedef typename Config::degree_size_type degree_size_type;
typedef typename Config::StoredEdge StoredEdge;
typedef typename Config::vertex_property_type vertex_property_type;
typedef typename Config::edge_property_type edge_property_type;
typedef typename Config::graph_property_type graph_property_type;
typedef typename Config::global_edgelist_selector
global_edgelist_selector;
typedef typename lookup_one_property<vertex_property_type, vertex_bundle_t>::type vertex_bundled;
typedef typename lookup_one_property<edge_property_type, edge_bundle_t>::type edge_bundled;
typedef typename lookup_one_property<graph_property_type, graph_bundle_t>::type graph_bundled;
};
template <class Config, class Base>
inline std::pair<typename Config::adjacency_iterator,
typename Config::adjacency_iterator>
adjacent_vertices(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
typedef typename Config::adjacency_iterator adjacency_iterator;
typename Config::out_edge_iterator first, last;
boost::tie(first, last) = out_edges(u, g);
return std::make_pair(adjacency_iterator(first, &g),
adjacency_iterator(last, &g));
}
template <class Config, class Base>
inline std::pair<typename Config::inv_adjacency_iterator,
typename Config::inv_adjacency_iterator>
inv_adjacent_vertices(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
typedef typename Config::inv_adjacency_iterator inv_adjacency_iterator;
typename Config::in_edge_iterator first, last;
boost::tie(first, last) = in_edges(u, g);
return std::make_pair(inv_adjacency_iterator(first, &g),
inv_adjacency_iterator(last, &g));
}
template <class Config, class Base>
inline std::pair<typename Config::out_edge_iterator,
typename Config::out_edge_iterator>
out_edges(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
typedef typename Config::out_edge_iterator out_edge_iterator;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
return
std::make_pair(out_edge_iterator(g.out_edge_list(u).begin(), u),
out_edge_iterator(g.out_edge_list(u).end(), u));
}
template <class Config, class Base>
inline std::pair<typename Config::vertex_iterator,
typename Config::vertex_iterator>
vertices(const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& cg = static_cast<const AdjList&>(g_);
AdjList& g = const_cast<AdjList&>(cg);
return std::make_pair( g.vertex_set().begin(), g.vertex_set().end() );
}
template <class Config, class Base>
inline typename Config::vertices_size_type
num_vertices(const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& g = static_cast<const AdjList&>(g_);
return g.vertex_set().size();
}
template <class Config, class Base>
inline typename Config::degree_size_type
out_degree(typename Config::vertex_descriptor u,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type AdjList;
const AdjList& g = static_cast<const AdjList&>(g_);
return g.out_edge_list(u).size();
}
template <class Config, class Base>
inline std::pair<typename Config::edge_descriptor, bool>
edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type Graph;
typedef typename Config::StoredEdge StoredEdge;
const Graph& cg = static_cast<const Graph&>(g_);
const typename Config::OutEdgeList& el = cg.out_edge_list(u);
typename Config::OutEdgeList::const_iterator it = graph_detail::
find(el, StoredEdge(v));
return std::make_pair(
typename Config::edge_descriptor
(u, v, (it == el.end() ? 0 : &(*it).get_property())),
(it != el.end()));
}
template <class Config, class Base>
inline std::pair<typename Config::out_edge_iterator,
typename Config::out_edge_iterator>
edge_range(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const adj_list_helper<Config, Base>& g_)
{
typedef typename Config::graph_type Graph;
typedef typename Config::StoredEdge StoredEdge;
const Graph& cg = static_cast<const Graph&>(g_);
Graph& g = const_cast<Graph&>(cg);
typedef typename Config::out_edge_iterator out_edge_iterator;
typename Config::OutEdgeList& el = g.out_edge_list(u);
typename Config::OutEdgeList::iterator first, last;
typename Config::EdgeContainer fake_edge_container;
boost::tie(first, last) = graph_detail::
equal_range(el, StoredEdge(v));
return std::make_pair(out_edge_iterator(first, u),
out_edge_iterator(last, u));
}
template <class Config>
inline typename Config::degree_size_type
in_degree(typename Config::vertex_descriptor u,
const directed_edges_helper<Config>& g_)
{
typedef typename Config::graph_type Graph;
const Graph& cg = static_cast<const Graph&>(g_);
Graph& g = const_cast<Graph&>(cg);
return in_edge_list(g, u).size();
}
namespace detail {
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::type
get_dispatch(adj_list_helper<Config,Base>&, Property p,
boost::edge_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::type PA;
return PA(p);
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::const_type
get_dispatch(const adj_list_helper<Config,Base>&, Property p,
boost::edge_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::const_type PA;
return PA(p);
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::type
get_dispatch(adj_list_helper<Config,Base>& g, Property p,
boost::vertex_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::type PA;
return PA(&static_cast<Graph&>(g), p);
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::const_type
get_dispatch(const adj_list_helper<Config, Base>& g, Property p,
boost::vertex_property_tag) {
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::const_type PA;
const Graph& cg = static_cast<const Graph&>(g);
return PA(&cg, p);
}
} // namespace detail
// Implementation of the PropertyGraph interface
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type, Property>::type
get(Property p, adj_list_helper<Config, Base>& g) {
typedef typename detail::property_kind_from_graph<adj_list_helper<Config, Base>, Property>::type Kind;
return detail::get_dispatch(g, p, Kind());
}
template <class Config, class Base, class Property>
inline
typename boost::property_map<typename Config::graph_type,
Property>::const_type
get(Property p, const adj_list_helper<Config, Base>& g) {
typedef typename detail::property_kind_from_graph<adj_list_helper<Config, Base>, Property>::type Kind;
return detail::get_dispatch(g, p, Kind());
}
template <class Config, class Base, class Property, class Key>
inline
typename boost::property_traits<
typename boost::property_map<typename Config::graph_type,
Property>::type
>::reference
get(Property p, adj_list_helper<Config, Base>& g, const Key& key) {
return get(get(p, g), key);
}
template <class Config, class Base, class Property, class Key>
inline
typename boost::property_traits<
typename boost::property_map<typename Config::graph_type,
Property>::const_type
>::reference
get(Property p, const adj_list_helper<Config, Base>& g, const Key& key) {
return get(get(p, g), key);
}
template <class Config, class Base, class Property, class Key,class Value>
inline void
put(Property p, adj_list_helper<Config, Base>& g,
const Key& key, const Value& value)
{
typedef typename Config::graph_type Graph;
typedef typename boost::property_map<Graph, Property>::type Map;
Map pmap = get(p, static_cast<Graph&>(g));
put(pmap, key, value);
}
//=========================================================================
// Generalize Adjacency List Implementation
struct adj_list_tag { };
template <class Derived, class Config, class Base>
class adj_list_impl
: public adj_list_helper<Config, Base>
{
typedef typename Config::OutEdgeList OutEdgeList;
typedef typename Config::InEdgeList InEdgeList;
typedef typename Config::StoredVertexList StoredVertexList;
public:
typedef typename Config::stored_vertex stored_vertex;
typedef typename Config::EdgeContainer EdgeContainer;
typedef typename Config::vertex_descriptor vertex_descriptor;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::vertex_iterator vertex_iterator;
typedef typename Config::edge_iterator edge_iterator;
typedef typename Config::edge_parallel_category edge_parallel_category;
typedef typename Config::vertices_size_type vertices_size_type;
typedef typename Config::edges_size_type edges_size_type;
typedef typename Config::degree_size_type degree_size_type;
typedef typename Config::edge_property_type edge_property_type;
typedef adj_list_tag graph_tag;
static vertex_descriptor null_vertex()
{
return 0;
}
inline adj_list_impl() { }
inline adj_list_impl(const adj_list_impl& x) {
copy_impl(x);
}
inline adj_list_impl& operator=(const adj_list_impl& x) {
this->clear();
copy_impl(x);
return *this;
}
inline void clear() {
for (typename StoredVertexList::iterator i = m_vertices.begin();
i != m_vertices.end(); ++i)
delete (stored_vertex*)*i;
m_vertices.clear();
m_edges.clear();
}
inline adj_list_impl(vertices_size_type num_vertices) {
for (vertices_size_type i = 0; i < num_vertices; ++i)
add_vertex(static_cast<Derived&>(*this));
}
template <class EdgeIterator>
inline adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last)
{
vertex_descriptor* v = new vertex_descriptor[num_vertices];
for (vertices_size_type i = 0; i < num_vertices; ++i)
v[i] = add_vertex(static_cast<Derived&>(*this));
while (first != last) {
add_edge(v[(*first).first], v[(*first).second], *this);
++first;
}
delete [] v;
}
template <class EdgeIterator, class EdgePropertyIterator>
inline adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last,
EdgePropertyIterator ep_iter)
{
vertex_descriptor* v = new vertex_descriptor[num_vertices];
for (vertices_size_type i = 0; i < num_vertices; ++i)
v[i] = add_vertex(static_cast<Derived&>(*this));
while (first != last) {
add_edge(v[(*first).first], v[(*first).second], *ep_iter, *this);
++first;
++ep_iter;
}
delete [] v;
}
~adj_list_impl() {
for (typename StoredVertexList::iterator i = m_vertices.begin();
i != m_vertices.end(); ++i)
delete (stored_vertex*)*i;
}
// protected:
inline OutEdgeList& out_edge_list(vertex_descriptor v) {
stored_vertex* sv = (stored_vertex*)v;
return sv->m_out_edges;
}
inline const OutEdgeList& out_edge_list(vertex_descriptor v) const {
stored_vertex* sv = (stored_vertex*)v;
return sv->m_out_edges;
}
inline StoredVertexList& vertex_set() { return m_vertices; }
inline const StoredVertexList& vertex_set() const { return m_vertices; }
inline void copy_impl(const adj_list_impl& x_)
{
const Derived& x = static_cast<const Derived&>(x_);
// Would be better to have a constant time way to get from
// vertices in x to the corresponding vertices in *this.
std::map<stored_vertex*,stored_vertex*> vertex_map;
// Copy the stored vertex objects by adding each vertex
// and copying its property object.
vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(x); vi != vi_end; ++vi) {
stored_vertex* v = (stored_vertex*)add_vertex(*this);
v->m_property = ((stored_vertex*)*vi)->m_property;
vertex_map[(stored_vertex*)*vi] = v;
}
// Copy the edges by adding each edge and copying its
// property object.
edge_iterator ei, ei_end;
for (boost::tie(ei, ei_end) = edges(x); ei != ei_end; ++ei) {
edge_descriptor e;
bool inserted;
vertex_descriptor s = source(*ei,x), t = target(*ei,x);
boost::tie(e, inserted) = add_edge(vertex_map[(stored_vertex*)s],
vertex_map[(stored_vertex*)t], *this);
*((edge_property_type*)e.m_eproperty)
= *((edge_property_type*)(*ei).m_eproperty);
}
}
typename Config::EdgeContainer m_edges;
StoredVertexList m_vertices;
};
// O(1)
template <class Derived, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(adj_list_impl<Derived, Config, Base>& g_)
{
Derived& g = static_cast<Derived&>(g_);
typedef typename Config::stored_vertex stored_vertex;
stored_vertex* v = new stored_vertex;
typename Config::StoredVertexList::iterator pos;
bool inserted;
boost::tie(pos,inserted) = boost::graph_detail::push(g.m_vertices, v);
v->m_position = pos;
g.added_vertex(v);
return v;
}
// O(1)
template <class Derived, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(const typename Config::vertex_property_type& p,
adj_list_impl<Derived, Config, Base>& g_)
{
typedef typename Config::vertex_descriptor vertex_descriptor;
Derived& g = static_cast<Derived&>(g_);
if (optional<vertex_descriptor> v
= g.vertex_by_property(get_property_value(p, vertex_bundle)))
return *v;
typedef typename Config::stored_vertex stored_vertex;
stored_vertex* v = new stored_vertex(p);
typename Config::StoredVertexList::iterator pos;
bool inserted;
boost::tie(pos,inserted) = boost::graph_detail::push(g.m_vertices, v);
v->m_position = pos;
g.added_vertex(v);
return v;
}
// O(1)
template <class Derived, class Config, class Base>
inline void remove_vertex(typename Config::vertex_descriptor u,
adj_list_impl<Derived, Config, Base>& g_)
{
typedef typename Config::stored_vertex stored_vertex;
Derived& g = static_cast<Derived&>(g_);
g.removing_vertex(u, boost::graph_detail::iterator_stability(g_.m_vertices));
stored_vertex* su = (stored_vertex*)u;
g.m_vertices.erase(su->m_position);
delete su;
}
// O(V)
template <class Derived, class Config, class Base>
inline typename Config::vertex_descriptor
vertex(typename Config::vertices_size_type n,
const adj_list_impl<Derived, Config, Base>& g_)
{
const Derived& g = static_cast<const Derived&>(g_);
typename Config::vertex_iterator i = vertices(g).first;
while (n--) ++i; // std::advance(i, n); (not VC++ portable)
return *i;
}
//=========================================================================
// Vector-Backbone Adjacency List Implementation
namespace detail {
template <class Graph, class vertex_descriptor>
inline void
remove_vertex_dispatch(Graph& g, vertex_descriptor u,
boost::directed_tag)
{
typedef typename Graph::edge_parallel_category edge_parallel_category;
g.m_vertices.erase(g.m_vertices.begin() + u);
vertex_descriptor V = num_vertices(g);
if (u != V) {
for (vertex_descriptor v = 0; v < V; ++v)
reindex_edge_list(g.out_edge_list(v), u, edge_parallel_category());
}
}
template <class Graph, class vertex_descriptor>
inline void
remove_vertex_dispatch(Graph& g, vertex_descriptor u,
boost::undirected_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Graph::edge_parallel_category edge_parallel_category;
g.m_vertices.erase(g.m_vertices.begin() + u);
vertex_descriptor V = num_vertices(g);
for (vertex_descriptor v = 0; v < V; ++v)
reindex_edge_list(g.out_edge_list(v), u,
edge_parallel_category());
typedef typename Graph::EdgeContainer Container;
typedef typename Container::iterator Iter;
Iter ei = g.m_edges.begin(), ei_end = g.m_edges.end();
for (; ei != ei_end; ++ei) {
if (ei->m_source > u)
--ei->m_source;
if (ei->m_target > u)
--ei->m_target;
}
}
template <class Graph, class vertex_descriptor>
inline void
remove_vertex_dispatch(Graph& g, vertex_descriptor u,
boost::bidirectional_tag)
{
typedef typename Graph::global_edgelist_selector EdgeListS;
BOOST_STATIC_ASSERT((!is_same<EdgeListS, vecS>::value));
typedef typename Graph::edge_parallel_category edge_parallel_category;
g.m_vertices.erase(g.m_vertices.begin() + u);
vertex_descriptor V = num_vertices(g);
vertex_descriptor v;
if (u != V) {
for (v = 0; v < V; ++v)
reindex_edge_list(g.out_edge_list(v), u,
edge_parallel_category());
for (v = 0; v < V; ++v)
reindex_edge_list(in_edge_list(g, v), u,
edge_parallel_category());
typedef typename Graph::EdgeContainer Container;
typedef typename Container::iterator Iter;
Iter ei = g.m_edges.begin(), ei_end = g.m_edges.end();
for (; ei != ei_end; ++ei) {
if (ei->m_source > u)
--ei->m_source;
if (ei->m_target > u)
--ei->m_target;
}
}
}
template <class EdgeList, class vertex_descriptor>
inline void
reindex_edge_list(EdgeList& el, vertex_descriptor u,
boost::allow_parallel_edge_tag)
{
typename EdgeList::iterator ei = el.begin(), e_end = el.end();
for (; ei != e_end; ++ei)
if ((*ei).get_target() > u)
--(*ei).get_target();
}
template <class EdgeList, class vertex_descriptor>
inline void
reindex_edge_list(EdgeList& el, vertex_descriptor u,
boost::disallow_parallel_edge_tag)
{
typename EdgeList::iterator ei = el.begin(), e_end = el.end();
while (ei != e_end) {
typename EdgeList::value_type ce = *ei;
++ei;
if (ce.get_target() > u) {
el.erase(ce);
--ce.get_target();
el.insert(ce);
}
}
}
} // namespace detail
struct vec_adj_list_tag { };
template <class Graph, class Config, class Base>
class vec_adj_list_impl
: public adj_list_helper<Config, Base>
{
typedef typename Config::OutEdgeList OutEdgeList;
typedef typename Config::InEdgeList InEdgeList;
typedef typename Config::StoredVertexList StoredVertexList;
public:
typedef typename Config::vertex_descriptor vertex_descriptor;
typedef typename Config::edge_descriptor edge_descriptor;
typedef typename Config::out_edge_iterator out_edge_iterator;
typedef typename Config::edge_iterator edge_iterator;
typedef typename Config::directed_category directed_category;
typedef typename Config::vertices_size_type vertices_size_type;
typedef typename Config::edges_size_type edges_size_type;
typedef typename Config::degree_size_type degree_size_type;
typedef typename Config::StoredEdge StoredEdge;
typedef typename Config::stored_vertex stored_vertex;
typedef typename Config::EdgeContainer EdgeContainer;
typedef typename Config::edge_property_type edge_property_type;
typedef vec_adj_list_tag graph_tag;
static vertex_descriptor null_vertex()
{
return (std::numeric_limits<vertex_descriptor>::max)();
}
inline vec_adj_list_impl() { }
inline vec_adj_list_impl(const vec_adj_list_impl& x) {
copy_impl(x);
}
inline vec_adj_list_impl& operator=(const vec_adj_list_impl& x) {
this->clear();
copy_impl(x);
return *this;
}
inline void clear() {
m_vertices.clear();
m_edges.clear();
}
inline vec_adj_list_impl(vertices_size_type _num_vertices)
: m_vertices(_num_vertices) { }
template <class EdgeIterator>
inline vec_adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last)
: m_vertices(num_vertices)
{
while (first != last) {
add_edge((*first).first, (*first).second,
static_cast<Graph&>(*this));
++first;
}
}
template <class EdgeIterator, class EdgePropertyIterator>
inline vec_adj_list_impl(vertices_size_type num_vertices,
EdgeIterator first, EdgeIterator last,
EdgePropertyIterator ep_iter)
: m_vertices(num_vertices)
{
while (first != last) {
add_edge((*first).first, (*first).second, *ep_iter,
static_cast<Graph&>(*this));
++first;
++ep_iter;
}
}
// protected:
inline boost::integer_range<vertex_descriptor> vertex_set() const {
return boost::integer_range<vertex_descriptor>(0, m_vertices.size());
}
inline OutEdgeList& out_edge_list(vertex_descriptor v) {
return m_vertices[v].m_out_edges;
}
inline const OutEdgeList& out_edge_list(vertex_descriptor v) const {
return m_vertices[v].m_out_edges;
}
inline void copy_impl(const vec_adj_list_impl& x_)
{
const Graph& x = static_cast<const Graph&>(x_);
// Copy the stored vertex objects by adding each vertex
// and copying its property object.
for (vertices_size_type i = 0; i < num_vertices(x); ++i) {
vertex_descriptor v = add_vertex(*this);
m_vertices[v].m_property = x.m_vertices[i].m_property;
}
// Copy the edges by adding each edge and copying its
// property object.
edge_iterator ei, ei_end;
for (boost::tie(ei, ei_end) = edges(x); ei != ei_end; ++ei) {
edge_descriptor e;
bool inserted;
boost::tie(e, inserted) = add_edge(source(*ei,x), target(*ei,x) , *this);
*((edge_property_type*)e.m_eproperty)
= *((edge_property_type*)(*ei).m_eproperty);
}
}
typename Config::EdgeContainer m_edges;
StoredVertexList m_vertices;
};
// Had to make these non-members to avoid accidental instantiation
// on SGI MIPSpro C++
template <class G, class C, class B>
inline typename C::InEdgeList&
in_edge_list(vec_adj_list_impl<G,C,B>& g,
typename C::vertex_descriptor v) {
return g.m_vertices[v].m_in_edges;
}
template <class G, class C, class B>
inline const typename C::InEdgeList&
in_edge_list(const vec_adj_list_impl<G,C,B>& g,
typename C::vertex_descriptor v) {
return g.m_vertices[v].m_in_edges;
}
// O(1)
template <class Graph, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(vec_adj_list_impl<Graph, Config, Base>& g_) {
Graph& g = static_cast<Graph&>(g_);
g.m_vertices.resize(g.m_vertices.size() + 1);
g.added_vertex(g.m_vertices.size() - 1);
return g.m_vertices.size() - 1;
}
template <class Graph, class Config, class Base>
inline typename Config::vertex_descriptor
add_vertex(const typename Config::vertex_property_type& p,
vec_adj_list_impl<Graph, Config, Base>& g_) {
typedef typename Config::vertex_descriptor vertex_descriptor;
Graph& g = static_cast<Graph&>(g_);
if (optional<vertex_descriptor> v
= g.vertex_by_property(get_property_value(p, vertex_bundle)))
return *v;
typedef typename Config::stored_vertex stored_vertex;
g.m_vertices.push_back(stored_vertex(p));
g.added_vertex(g.m_vertices.size() - 1);
return g.m_vertices.size() - 1;
}
// Here we override the directed_graph_helper add_edge() function
// so that the number of vertices is automatically changed if
// either u or v is greater than the number of vertices.
template <class Graph, class Config, class Base>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
const typename Config::edge_property_type& p,
vec_adj_list_impl<Graph, Config, Base>& g_)
{
BOOST_USING_STD_MAX();
typename Config::vertex_descriptor x = max BOOST_PREVENT_MACRO_SUBSTITUTION(u, v);
if (x >= num_vertices(g_))
g_.m_vertices.resize(x + 1);
adj_list_helper<Config, Base>& g = g_;
return add_edge(u, v, p, g);
}
template <class Graph, class Config, class Base>
inline std::pair<typename Config::edge_descriptor, bool>
add_edge(typename Config::vertex_descriptor u,
typename Config::vertex_descriptor v,
vec_adj_list_impl<Graph, Config, Base>& g_)
{
typename Config::edge_property_type p;
return add_edge(u, v, p, g_);
}
// O(V + E)
template <class Graph, class Config, class Base>
inline void remove_vertex(typename Config::vertex_descriptor v,
vec_adj_list_impl<Graph, Config, Base>& g_)
{
typedef typename Config::directed_category Cat;
Graph& g = static_cast<Graph&>(g_);
g.removing_vertex(v, boost::graph_detail::iterator_stability(g_.m_vertices));
detail::remove_vertex_dispatch(g, v, Cat());
}
// O(1)
template <class Graph, class Config, class Base>
inline typename Config::vertex_descriptor
vertex(typename Config::vertices_size_type n,
const vec_adj_list_impl<Graph, Config, Base>&)
{
return n;
}
namespace detail {
//=========================================================================
// Adjacency List Generator
template <class Graph, class VertexListS, class OutEdgeListS,
class DirectedS, class VertexProperty, class EdgeProperty,
class GraphProperty, class EdgeListS>
struct adj_list_gen
{
typedef typename detail::is_random_access<VertexListS>::type
is_rand_access;
typedef typename has_property<EdgeProperty>::type has_edge_property;
typedef typename DirectedS::is_directed_t DirectedT;
typedef typename DirectedS::is_bidir_t BidirectionalT;
struct config
{
typedef OutEdgeListS edgelist_selector;
typedef EdgeListS global_edgelist_selector;
typedef Graph graph_type;
typedef EdgeProperty edge_property_type;
typedef VertexProperty vertex_property_type;
typedef GraphProperty graph_property_type;
typedef std::size_t vertices_size_type;
typedef adjacency_list_traits<OutEdgeListS, VertexListS, DirectedS>
Traits;
typedef typename Traits::directed_category directed_category;
typedef typename Traits::edge_parallel_category edge_parallel_category;
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef typename Traits::edge_descriptor edge_descriptor;
typedef void* vertex_ptr;
// need to reorganize this to avoid instantiating stuff
// that doesn't get used -JGS
// VertexList and vertex_iterator
typedef typename container_gen<VertexListS,
vertex_ptr>::type SeqVertexList;
typedef boost::integer_range<vertex_descriptor> RandVertexList;
typedef typename mpl::if_<is_rand_access,
RandVertexList, SeqVertexList>::type VertexList;
typedef typename VertexList::iterator vertex_iterator;
// EdgeContainer and StoredEdge
typedef typename container_gen<EdgeListS,
list_edge<vertex_descriptor, EdgeProperty> >::type EdgeContainer;
typedef typename mpl::and_<DirectedT,
typename mpl::not_<BidirectionalT>::type >::type on_edge_storage;
typedef typename mpl::if_<on_edge_storage,
std::size_t, typename EdgeContainer::size_type
>::type edges_size_type;
typedef typename EdgeContainer::iterator EdgeIter;
typedef typename detail::is_random_access<EdgeListS>::type is_edge_ra;
typedef typename mpl::if_<on_edge_storage,
stored_edge_property<vertex_descriptor, EdgeProperty>,
typename mpl::if_<is_edge_ra,
stored_ra_edge_iter<vertex_descriptor, EdgeContainer, EdgeProperty>,
stored_edge_iter<vertex_descriptor, EdgeIter, EdgeProperty>
>::type
>::type StoredEdge;
// Adjacency Types
typedef typename container_gen<OutEdgeListS, StoredEdge>::type
OutEdgeList;
typedef typename OutEdgeList::size_type degree_size_type;
typedef typename OutEdgeList::iterator OutEdgeIter;
typedef boost::detail::iterator_traits<OutEdgeIter> OutEdgeIterTraits;
typedef typename OutEdgeIterTraits::iterator_category OutEdgeIterCat;
typedef typename OutEdgeIterTraits::difference_type OutEdgeIterDiff;
typedef out_edge_iter<
OutEdgeIter, vertex_descriptor, edge_descriptor, OutEdgeIterDiff
> out_edge_iterator;
typedef typename adjacency_iterator_generator<graph_type,
vertex_descriptor, out_edge_iterator>::type adjacency_iterator;
typedef OutEdgeList InEdgeList;
typedef OutEdgeIter InEdgeIter;
typedef OutEdgeIterCat InEdgeIterCat;
typedef OutEdgeIterDiff InEdgeIterDiff;
typedef in_edge_iter<
InEdgeIter, vertex_descriptor, edge_descriptor, InEdgeIterDiff
> in_edge_iterator;
typedef typename inv_adjacency_iterator_generator<graph_type,
vertex_descriptor, in_edge_iterator>::type inv_adjacency_iterator;
// Edge Iterator
typedef boost::detail::iterator_traits<EdgeIter> EdgeIterTraits;
typedef typename EdgeIterTraits::iterator_category EdgeIterCat;
typedef typename EdgeIterTraits::difference_type EdgeIterDiff;
typedef undirected_edge_iter<
EdgeIter
, edge_descriptor
, EdgeIterDiff
> UndirectedEdgeIter; // also used for bidirectional
typedef adj_list_edge_iterator<vertex_iterator, out_edge_iterator,
graph_type> DirectedEdgeIter;
typedef typename mpl::if_<on_edge_storage,
DirectedEdgeIter, UndirectedEdgeIter>::type edge_iterator;
// stored_vertex and StoredVertexList
typedef typename container_gen<VertexListS, vertex_ptr>::type
SeqStoredVertexList;
struct seq_stored_vertex {
seq_stored_vertex() { }
seq_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
VertexProperty m_property;
typename SeqStoredVertexList::iterator m_position;
};
struct bidir_seq_stored_vertex {
bidir_seq_stored_vertex() { }
bidir_seq_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
InEdgeList m_in_edges;
VertexProperty m_property;
typename SeqStoredVertexList::iterator m_position;
};
struct rand_stored_vertex {
rand_stored_vertex() { }
rand_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
VertexProperty m_property;
};
struct bidir_rand_stored_vertex {
bidir_rand_stored_vertex() { }
bidir_rand_stored_vertex(const VertexProperty& p) : m_property(p) { }
OutEdgeList m_out_edges;
InEdgeList m_in_edges;
VertexProperty m_property;
};
typedef typename mpl::if_<is_rand_access,
typename mpl::if_<BidirectionalT,
bidir_rand_stored_vertex, rand_stored_vertex>::type,
typename mpl::if_<BidirectionalT,
bidir_seq_stored_vertex, seq_stored_vertex>::type
>::type StoredVertex;
struct stored_vertex : public StoredVertex {
stored_vertex() { }
stored_vertex(const VertexProperty& p) : StoredVertex(p) { }
};
typedef typename container_gen<VertexListS, stored_vertex>::type
RandStoredVertexList;
typedef typename mpl::if_< is_rand_access,
RandStoredVertexList, SeqStoredVertexList>::type StoredVertexList;
}; // end of config
typedef typename mpl::if_<BidirectionalT,
bidirectional_graph_helper_with_property<config>,
typename mpl::if_<DirectedT,
directed_graph_helper<config>,
undirected_graph_helper<config>
>::type
>::type DirectedHelper;
typedef typename mpl::if_<is_rand_access,
vec_adj_list_impl<Graph, config, DirectedHelper>,
adj_list_impl<Graph, config, DirectedHelper>
>::type type;
};
} // namespace detail
//=========================================================================
// Vertex Property Maps
template <class Graph, class ValueType, class Reference, class Tag>
struct adj_list_vertex_property_map
: public boost::put_get_helper<
Reference,
adj_list_vertex_property_map<Graph, ValueType, Reference, Tag>
>
{
typedef typename Graph::stored_vertex StoredVertex;
typedef ValueType value_type;
typedef Reference reference;
typedef typename Graph::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
inline adj_list_vertex_property_map(const Graph* = 0, Tag tag = Tag()): m_tag(tag) { }
inline Reference operator[](key_type v) const {
StoredVertex* sv = (StoredVertex*)v;
return get_property_value(sv->m_property, m_tag);
}
inline Reference operator()(key_type v) const {
return this->operator[](v);
}
Tag m_tag;
};
template <class Graph, class Property, class PropRef>
struct adj_list_vertex_all_properties_map
: public boost::put_get_helper<PropRef,
adj_list_vertex_all_properties_map<Graph, Property, PropRef>
>
{
typedef typename Graph::stored_vertex StoredVertex;
typedef Property value_type;
typedef PropRef reference;
typedef typename Graph::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
inline adj_list_vertex_all_properties_map(const Graph* = 0, vertex_all_t = vertex_all_t()) { }
inline PropRef operator[](key_type v) const {
StoredVertex* sv = (StoredVertex*)v;
return sv->m_property;
}
inline PropRef operator()(key_type v) const {
return this->operator[](v);
}
};
template <class Graph, class GraphPtr, class ValueType, class Reference,
class Tag>
struct vec_adj_list_vertex_property_map
: public boost::put_get_helper<
Reference,
vec_adj_list_vertex_property_map<Graph,GraphPtr,ValueType,Reference,
Tag>
>
{
typedef ValueType value_type;
typedef Reference reference;
typedef typename boost::graph_traits<Graph>::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
vec_adj_list_vertex_property_map(GraphPtr g = 0, Tag tag = Tag()) : m_g(g), m_tag(tag) { }
inline Reference operator[](key_type v) const {
return get_property_value(m_g->m_vertices[v].m_property, m_tag);
}
inline Reference operator()(key_type v) const {
return this->operator[](v);
}
GraphPtr m_g;
Tag m_tag;
};
template <class Graph, class GraphPtr, class Property, class PropertyRef>
struct vec_adj_list_vertex_all_properties_map
: public boost::put_get_helper<PropertyRef,
vec_adj_list_vertex_all_properties_map<Graph,GraphPtr,Property,
PropertyRef>
>
{
typedef Property value_type;
typedef PropertyRef reference;
typedef typename boost::graph_traits<Graph>::vertex_descriptor key_type;
typedef boost::lvalue_property_map_tag category;
vec_adj_list_vertex_all_properties_map(GraphPtr g = 0, vertex_all_t = vertex_all_t()) : m_g(g) { }
inline PropertyRef operator[](key_type v) const {
return m_g->m_vertices[v].m_property;
}
inline PropertyRef operator()(key_type v) const {
return this->operator[](v);
}
GraphPtr m_g;
};
struct adj_list_any_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename property_value<Property, Tag>::type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef adj_list_vertex_property_map
<Graph, value_type, reference, Tag> type;
typedef adj_list_vertex_property_map
<Graph, value_type, const_reference, Tag> const_type;
};
};
struct adj_list_all_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename Graph::vertex_descriptor Vertex;
typedef adj_list_vertex_all_properties_map<Graph,Property,
Property&> type;
typedef adj_list_vertex_all_properties_map<Graph,Property,
const Property&> const_type;
};
};
template <class Property, class Vertex>
struct vec_adj_list_vertex_id_map
: public boost::put_get_helper<
Vertex, vec_adj_list_vertex_id_map<Property, Vertex>
>
{
typedef Vertex value_type;
typedef Vertex key_type;
typedef Vertex reference;
typedef boost::readable_property_map_tag category;
inline vec_adj_list_vertex_id_map() { }
template <class Graph>
inline vec_adj_list_vertex_id_map(const Graph&, vertex_index_t) { }
inline value_type operator[](key_type v) const { return v; }
inline value_type operator()(key_type v) const { return v; }
};
struct vec_adj_list_any_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename property_value<Property, Tag>::type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef vec_adj_list_vertex_property_map
<Graph, Graph*, value_type, reference, Tag> type;
typedef vec_adj_list_vertex_property_map
<Graph, const Graph*, value_type, const_reference, Tag> const_type;
};
};
struct vec_adj_list_id_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename Graph::vertex_descriptor Vertex;
typedef vec_adj_list_vertex_id_map<Property, Vertex> type;
typedef vec_adj_list_vertex_id_map<Property, Vertex> const_type;
};
};
struct vec_adj_list_all_vertex_pa {
template <class Tag, class Graph, class Property>
struct bind_ {
typedef typename Graph::vertex_descriptor Vertex;
typedef vec_adj_list_vertex_all_properties_map
<Graph, Graph*, Property, Property&> type;
typedef vec_adj_list_vertex_all_properties_map
<Graph, const Graph*, Property, const Property&> const_type;
};
};
namespace detail {
template <class Tag, class Graph, class Property>
struct adj_list_choose_vertex_pa
: boost::mpl::if_<
boost::is_same<Tag, vertex_all_t>,
adj_list_all_vertex_pa,
adj_list_any_vertex_pa>::type
::template bind_<Tag, Graph, Property>
{};
template <class Tag>
struct vec_adj_list_choose_vertex_pa_helper {
typedef vec_adj_list_any_vertex_pa type;
};
template <>
struct vec_adj_list_choose_vertex_pa_helper<vertex_index_t> {
typedef vec_adj_list_id_vertex_pa type;
};
template <>
struct vec_adj_list_choose_vertex_pa_helper<vertex_all_t> {
typedef vec_adj_list_all_vertex_pa type;
};
template <class Tag, class Graph, class Property>
struct vec_adj_list_choose_vertex_pa
: vec_adj_list_choose_vertex_pa_helper<Tag>::type::template bind_<Tag,Graph,Property>
{};
} // namespace detail
//=========================================================================
// Edge Property Map
template <class Directed, class Value, class Ref, class Vertex,
class Property, class Tag>
struct adj_list_edge_property_map
: public put_get_helper<
Ref,
adj_list_edge_property_map<Directed, Value, Ref, Vertex, Property,
Tag>
>
{
Tag tag;
explicit adj_list_edge_property_map(Tag tag = Tag()): tag(tag) {}
typedef Value value_type;
typedef Ref reference;
typedef detail::edge_desc_impl<Directed, Vertex> key_type;
typedef boost::lvalue_property_map_tag category;
inline Ref operator[](key_type e) const {
Property& p = *(Property*)e.get_property();
return get_property_value(p, tag);
}
inline Ref operator()(key_type e) const {
return this->operator[](e);
}
};
template <class Directed, class Property, class PropRef, class PropPtr,
class Vertex>
struct adj_list_edge_all_properties_map
: public put_get_helper<PropRef,
adj_list_edge_all_properties_map<Directed, Property, PropRef,
PropPtr, Vertex>
>
{
explicit adj_list_edge_all_properties_map(edge_all_t = edge_all_t()) {}
typedef Property value_type;
typedef PropRef reference;
typedef detail::edge_desc_impl<Directed, Vertex> key_type;
typedef boost::lvalue_property_map_tag category;
inline PropRef operator[](key_type e) const {
return *(PropPtr)e.get_property();
}
inline PropRef operator()(key_type e) const {
return this->operator[](e);
}
};
// Edge Property Maps
namespace detail {
struct adj_list_any_edge_pmap {
template <class Graph, class Property, class Tag>
struct bind_ {
typedef typename property_value<Property,Tag>::type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef adj_list_edge_property_map
<typename Graph::directed_category, value_type, reference,
typename Graph::vertex_descriptor,Property,Tag> type;
typedef adj_list_edge_property_map
<typename Graph::directed_category, value_type, const_reference,
typename Graph::vertex_descriptor,const Property, Tag> const_type;
};
};
struct adj_list_all_edge_pmap {
template <class Graph, class Property, class Tag>
struct bind_ {
typedef adj_list_edge_all_properties_map
<typename Graph::directed_category, Property, Property&, Property*,
typename Graph::vertex_descriptor> type;
typedef adj_list_edge_all_properties_map
<typename Graph::directed_category, Property, const Property&,
const Property*, typename Graph::vertex_descriptor> const_type;
};
};
template <class Tag>
struct adj_list_choose_edge_pmap_helper {
typedef adj_list_any_edge_pmap type;
};
template <>
struct adj_list_choose_edge_pmap_helper<edge_all_t> {
typedef adj_list_all_edge_pmap type;
};
template <class Tag, class Graph, class Property>
struct adj_list_choose_edge_pmap
: adj_list_choose_edge_pmap_helper<Tag>::type::template bind_<Graph, Property, Tag>
{};
struct adj_list_edge_property_selector {
template <class Graph, class Property, class Tag>
struct bind_: adj_list_choose_edge_pmap<Tag, Graph, Property> {};
};
} // namespace detail
template <>
struct edge_property_selector<adj_list_tag> {
typedef detail::adj_list_edge_property_selector type;
};
template <>
struct edge_property_selector<vec_adj_list_tag> {
typedef detail::adj_list_edge_property_selector type;
};
// Vertex Property Maps
struct adj_list_vertex_property_selector {
template <class Graph, class Property, class Tag>
struct bind_
: detail::adj_list_choose_vertex_pa<Tag,Graph,Property>
{};
};
template <>
struct vertex_property_selector<adj_list_tag> {
typedef adj_list_vertex_property_selector type;
};
struct vec_adj_list_vertex_property_selector {
template <class Graph, class Property, class Tag>
struct bind_: detail::vec_adj_list_choose_vertex_pa<Tag,Graph,Property> {};
};
template <>
struct vertex_property_selector<vec_adj_list_tag> {
typedef vec_adj_list_vertex_property_selector type;
};
} // namespace boost
namespace boost {
template <typename V>
struct hash< boost::detail::stored_edge<V> >
{
std::size_t
operator()(const boost::detail::stored_edge<V>& e) const
{
return hash<V>()(e.m_target);
}
};
template <typename V, typename P>
struct hash< boost::detail::stored_edge_property <V,P> >
{
std::size_t
operator()(const boost::detail::stored_edge_property<V,P>& e) const
{
return hash<V>()(e.m_target);
}
};
template <typename V, typename I, typename P>
struct hash< boost::detail::stored_edge_iter<V,I, P> >
{
std::size_t
operator()(const boost::detail::stored_edge_iter<V,I,P>& e) const
{
return hash<V>()(e.m_target);
}
};
}
#endif // BOOST_GRAPH_DETAIL_DETAIL_ADJACENCY_LIST_CCT
/*
Implementation Notes:
Many of the public interface functions in this file would have been
more conveniently implemented as inline friend functions.
However there are a few compiler bugs that make that approach
non-portable.
1. g++ inline friend in namespace bug
2. g++ using clause doesn't work with inline friends
3. VC++ doesn't have Koenig lookup
For these reasons, the functions were all written as non-inline free
functions, and static cast was used to convert from the helper
class to the adjacency_list derived class.
Looking back, it might have been better to write out all functions
in terms of the adjacency_list, and then use a tag to dispatch
to the various helpers instead of using inheritance.
*/
| lgpl-2.1 |
FSMaxB/molch | outcome/include/outcome/quickcpplib/doc/html/search/classes_9.js | 369 | var searchData=
[
['narrowing_5ferror',['narrowing_error',['../structgsl_1_1narrowing__error.html',1,'gsl']]],
['not_5fnull',['not_null',['../classgsl_1_1not__null.html',1,'gsl']]],
['null_5fspin_5fpolicy',['null_spin_policy',['../structquickcpplib_1_1__xxx_1_1configurable__spinlock_1_1null__spin__policy.html',1,'quickcpplib::_xxx::configurable_spinlock']]]
];
| lgpl-2.1 |
cdmdotnet/CQRS | wiki/docs/4.2/html/namespaceCqrs_1_1Ninject_1_1InProcess.html | 6151 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://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.16"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.Ninject.InProcess 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="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(initResizable);
/* @license-end */</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/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></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 id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">4.2</span>
</div>
<div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.16 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('namespaceCqrs_1_1Ninject_1_1InProcess.html','');});
/* @license-end */
</script>
<div id="doc-content">
<!-- 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 class="header">
<div class="summary">
<a href="#namespaces">Namespaces</a> </div>
<div class="headertitle">
<div class="title">Cqrs.Ninject.InProcess Namespace Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a>
Namespaces</h2></td></tr>
<tr class="memitem:namespaceCqrs_1_1Ninject_1_1InProcess_1_1CommandBus"><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceCqrs_1_1Ninject_1_1InProcess_1_1CommandBus.html">CommandBus</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:namespaceCqrs_1_1Ninject_1_1InProcess_1_1EventBus"><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceCqrs_1_1Ninject_1_1InProcess_1_1EventBus.html">EventBus</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:namespaceCqrs_1_1Ninject_1_1InProcess_1_1EventStore"><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceCqrs_1_1Ninject_1_1InProcess_1_1EventStore.html">EventStore</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Ninject.html">Ninject</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Ninject_1_1InProcess.html">InProcess</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li>
</ul>
</div>
</body>
</html>
| lgpl-2.1 |
sairajat/dealii | include/deal.II/lac/solver_minres.h | 10018 | // ---------------------------------------------------------------------
//
// Copyright (C) 2000 - 2017 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#ifndef dealii_solver_minres_h
#define dealii_solver_minres_h
#include <deal.II/base/config.h>
#include <deal.II/lac/solver.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/base/logstream.h>
#include <cmath>
#include <deal.II/base/subscriptor.h>
#include <deal.II/base/signaling_nan.h>
DEAL_II_NAMESPACE_OPEN
/*!@addtogroup Solvers */
/*@{*/
/**
* Minimal residual method for symmetric matrices.
*
* For the requirements on matrices and vectors in order to work with this
* class, see the documentation of the Solver base class.
*
* Like all other solver classes, this class has a local structure called @p
* AdditionalData which is used to pass additional parameters to the solver,
* like damping parameters or the number of temporary vectors. We use this
* additional structure instead of passing these values directly to the
* constructor because this makes the use of the @p SolverSelector and other
* classes much easier and guarantees that these will continue to work even if
* number or type of the additional parameters for a certain solver changes.
*
* However, since the MinRes method does not need additional data, the
* respective structure is empty and does not offer any functionality. The
* constructor has a default argument, so you may call it without the
* additional parameter.
*
* The preconditioner has to be positive definite and symmetric
*
* The algorithm is taken from the Master thesis of Astrid Battermann with
* some changes. The full text can be found at
* http://scholar.lib.vt.edu/theses/public/etd-12164379662151/etd-title.html
*
*
* <h3>Observing the progress of linear solver iterations</h3>
*
* The solve() function of this class uses the mechanism described in the
* Solver base class to determine convergence. This mechanism can also be used
* to observe the progress of the iteration.
*
*
* @author Thomas Richter, 2000, Luca Heltai, 2006
*/
template <class VectorType = Vector<double> >
class SolverMinRes : public Solver<VectorType>
{
public:
/**
* Standardized data struct to pipe additional data to the solver. This
* solver does not need additional data yet.
*/
struct AdditionalData
{
};
/**
* Constructor.
*/
SolverMinRes (SolverControl &cn,
VectorMemory<VectorType> &mem,
const AdditionalData &data=AdditionalData());
/**
* Constructor. Use an object of type GrowingVectorMemory as a default to
* allocate memory.
*/
SolverMinRes (SolverControl &cn,
const AdditionalData &data=AdditionalData());
/**
* Virtual destructor.
*/
virtual ~SolverMinRes () = default;
/**
* Solve the linear system $Ax=b$ for x.
*/
template <typename MatrixType, typename PreconditionerType>
void
solve (const MatrixType &A,
VectorType &x,
const VectorType &b,
const PreconditionerType &preconditioner);
/**
* @addtogroup Exceptions
* @{
*/
/**
* Exception
*/
DeclException0 (ExcPreconditionerNotDefinite);
//@}
protected:
/**
* Implementation of the computation of the norm of the residual.
*/
virtual double criterion();
/**
* Interface for derived class. This function gets the current iteration
* vector, the residual and the update vector in each step. It can be used
* for graphical output of the convergence history.
*/
virtual void print_vectors(const unsigned int step,
const VectorType &x,
const VectorType &r,
const VectorType &d) const;
/**
* Within the iteration loop, the square of the residual vector is stored in
* this variable. The function @p criterion uses this variable to compute
* the convergence value, which in this class is the norm of the residual
* vector and thus the square root of the @p res2 value.
*/
double res2;
};
/*@}*/
/*------------------------- Implementation ----------------------------*/
#ifndef DOXYGEN
template <class VectorType>
SolverMinRes<VectorType>::SolverMinRes (SolverControl &cn,
VectorMemory<VectorType> &mem,
const AdditionalData &)
:
Solver<VectorType>(cn,mem)
{}
template <class VectorType>
SolverMinRes<VectorType>::SolverMinRes (SolverControl &cn,
const AdditionalData &)
:
Solver<VectorType>(cn),
res2(numbers::signaling_nan<double>())
{}
template <class VectorType>
double
SolverMinRes<VectorType>::criterion()
{
return res2;
}
template <class VectorType>
void
SolverMinRes<VectorType>::print_vectors(const unsigned int,
const VectorType &,
const VectorType &,
const VectorType &) const
{}
template <class VectorType>
template <typename MatrixType, typename PreconditionerType>
void
SolverMinRes<VectorType>::solve (const MatrixType &A,
VectorType &x,
const VectorType &b,
const PreconditionerType &preconditioner)
{
LogStream::Prefix prefix("minres");
// Memory allocation
typename VectorMemory<VectorType>::Pointer Vu0 (this->memory);
typename VectorMemory<VectorType>::Pointer Vu1 (this->memory);
typename VectorMemory<VectorType>::Pointer Vu2 (this->memory);
typename VectorMemory<VectorType>::Pointer Vm0 (this->memory);
typename VectorMemory<VectorType>::Pointer Vm1 (this->memory);
typename VectorMemory<VectorType>::Pointer Vm2 (this->memory);
typename VectorMemory<VectorType>::Pointer Vv (this->memory);
// define some aliases for simpler access
typedef VectorType *vecptr;
vecptr u[3] = {Vu0.get(), Vu1.get(), Vu2.get()};
vecptr m[3] = {Vm0.get(), Vm1.get(), Vm2.get()};
VectorType &v = *Vv;
// resize the vectors, but do not set the values since they'd be overwritten
// soon anyway.
u[0]->reinit(b,true);
u[1]->reinit(b,true);
u[2]->reinit(b,true);
m[0]->reinit(b,true);
m[1]->reinit(b,true);
m[2]->reinit(b,true);
v.reinit(b,true);
// some values needed
double delta[3] = { 0, 0, 0 };
double f[2] = { 0, 0 };
double e[2] = { 0, 0 };
double r_l2 = 0;
double r0 = 0;
double tau = 0;
double c = 0;
double s = 0;
double d_ = 0;
// The iteration step.
unsigned int j = 1;
// Start of the solution process
A.vmult(*m[0],x);
*u[1] = b;
*u[1] -= *m[0];
// Precondition is applied.
// The preconditioner has to be
// positive definite and symmetric
// M v = u[1]
preconditioner.vmult (v,*u[1]);
delta[1] = v * (*u[1]);
// Preconditioner positive
Assert (delta[1]>=0, ExcPreconditionerNotDefinite());
r0 = std::sqrt(delta[1]);
r_l2 = r0;
u[0]->reinit(b);
delta[0] = 1.;
m[0]->reinit(b);
m[1]->reinit(b);
m[2]->reinit(b);
SolverControl::State conv = this->iteration_status(0, r_l2, x);
while (conv==SolverControl::iterate)
{
if (delta[1]!=0)
v *= 1./std::sqrt(delta[1]);
else
v.reinit(b);
A.vmult(*u[2],v);
u[2]->add (-std::sqrt(delta[1]/delta[0]), *u[0]);
const double gamma = *u[2] * v;
u[2]->add (-gamma / std::sqrt(delta[1]), *u[1]);
*m[0] = v;
// precondition: solve M v = u[2]
// Preconditioner has to be positive
// definite and symmetric.
preconditioner.vmult(v,*u[2]);
delta[2] = v * (*u[2]);
Assert (delta[2]>=0, ExcPreconditionerNotDefinite());
if (j==1)
{
d_ = gamma;
e[1] = std::sqrt(delta[2]);
}
if (j>1)
{
d_ = s * e[0] - c * gamma;
e[0] = c * e[0] + s * gamma;
f[1] = s * std::sqrt(delta[2]);
e[1] = -c * std::sqrt(delta[2]);
}
const double d = std::sqrt (d_*d_ + delta[2]);
if (j>1)
tau *= s / c;
c = d_ / d;
tau *= c;
s = std::sqrt(delta[2]) / d;
if (j==1)
tau = r0 * c;
m[0]->add (-e[0], *m[1]);
if (j>1)
m[0]->add (-f[0], *m[2]);
*m[0] *= 1./d;
x.add (tau, *m[0]);
r_l2 *= std::fabs(s);
conv = this->iteration_status(j, r_l2, x);
// next iteration step
++j;
// All vectors have to be shifted
// one iteration step.
// This should be changed one time.
//
// the previous code was like this:
// m[2] = m[1];
// m[1] = m[0];
// but it can be made more efficient,
// since the value of m[0] is no more
// needed in the next iteration
swap (*m[2], *m[1]);
swap (*m[1], *m[0]);
// likewise, but reverse direction:
// u[0] = u[1];
// u[1] = u[2];
swap (*u[0], *u[1]);
swap (*u[1], *u[2]);
// these are scalars, so need
// to bother
f[0] = f[1];
e[0] = e[1];
delta[0] = delta[1];
delta[1] = delta[2];
}
// in case of failure: throw exception
AssertThrow(conv == SolverControl::success,
SolverControl::NoConvergence (j, r_l2));
// otherwise exit as normal
}
#endif // DOXYGEN
DEAL_II_NAMESPACE_CLOSE
#endif
| lgpl-2.1 |
fredrik-johansson/flint2 | fmpq_poly/test/t-scalar_div_si.c | 4124 | /*
Copyright (C) 2009 William Hart
Copyright (C) 2010 Sebastian Pancratz
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <gmp.h>
#include "flint.h"
#include "fmpz.h"
#include "fmpq_poly.h"
#include "long_extras.h"
#include "ulong_extras.h"
int
main(void)
{
int i, result;
ulong cflags = UWORD(0);
FLINT_TEST_INIT(state);
flint_printf("scalar_div_si....");
fflush(stdout);
/* Check aliasing of a and b */
for (i = 0; i < 1000 * flint_test_multiplier(); i++)
{
fmpq_poly_t a, b;
slong n;
fmpq_poly_init(a);
fmpq_poly_init(b);
fmpq_poly_randtest(a, state, n_randint(state, 100), 200);
n = z_randtest_not_zero(state);
fmpq_poly_scalar_div_si(b, a, n);
fmpq_poly_scalar_div_si(a, a, n);
cflags |= fmpq_poly_is_canonical(a) ? 0 : 1;
cflags |= fmpq_poly_is_canonical(b) ? 0 : 2;
result = (fmpq_poly_equal(a, b) && !cflags);
if (!result)
{
flint_printf("FAIL:\n");
fmpq_poly_debug(a), flint_printf("\n\n");
fmpq_poly_debug(b), flint_printf("\n\n");
flint_printf("cflags = %wu\n\n", cflags);
fflush(stdout);
flint_abort();
}
fmpq_poly_clear(a);
fmpq_poly_clear(b);
}
/* Compare with fmpq_poly_scalar_div_ui */
for (i = 0; i < 1000 * flint_test_multiplier(); i++)
{
fmpq_poly_t a, b;
ulong n;
n = n_randtest_not_zero(state);
if (n > WORD_MAX)
n >>= 1;
fmpq_poly_init(a);
fmpq_poly_init(b);
fmpq_poly_randtest(a, state, n_randint(state, 100), 200);
fmpq_poly_scalar_div_ui(b, a, n);
fmpq_poly_scalar_div_si(a, a, n);
cflags |= fmpq_poly_is_canonical(a) ? 0 : 1;
cflags |= fmpq_poly_is_canonical(b) ? 0 : 2;
result = (fmpq_poly_equal(a, b) && !cflags);
if (!result)
{
flint_printf("FAIL:\n");
fmpq_poly_debug(a), flint_printf("\n\n");
fmpq_poly_debug(b), flint_printf("\n\n");
flint_printf("cflags = %wu\n\n", cflags);
fflush(stdout);
flint_abort();
}
fmpq_poly_clear(a);
fmpq_poly_clear(b);
}
/* Check (a / n1) / n2 == a / (n1 * n2) */
for (i = 0; i < 1000 * flint_test_multiplier(); i++)
{
fmpq_poly_t a, b, c;
slong n1, n2;
ulong m;
while ((n1 = (slong) n_randbits(state, FLINT_BITS / 2)) == 0) ;
while ((n2 = (slong) n_randbits(state, FLINT_BITS / 2 - 1)) == 0) ;
m = n_randlimb(state);
if (m & UWORD(1))
n1 = -n1;
if (m & UWORD(2))
n2 = -n2;
fmpq_poly_init(a);
fmpq_poly_init(b);
fmpq_poly_init(c);
fmpq_poly_randtest(a, state, n_randint(state, 100), 200);
fmpq_poly_scalar_div_si(b, a, n1);
fmpq_poly_scalar_div_si(c, b, n2);
fmpq_poly_scalar_div_si(b, a, n1 * n2);
cflags |= fmpq_poly_is_canonical(b) ? 0 : 1;
cflags |= fmpq_poly_is_canonical(c) ? 0 : 2;
result = (fmpq_poly_equal(b, c) && !cflags);
if (!result)
{
flint_printf("FAIL:\n\n");
flint_printf("n1 = %wu, n2 = %wu:\n\n", n1, n2);
fmpq_poly_debug(a), flint_printf("\n\n");
fmpq_poly_debug(b), flint_printf("\n\n");
fmpq_poly_debug(c), flint_printf("\n\n");
flint_printf("cflags = %wu\n\n", cflags);
fflush(stdout);
flint_abort();
}
fmpq_poly_clear(a);
fmpq_poly_clear(b);
fmpq_poly_clear(c);
}
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
| lgpl-2.1 |
cdmdotnet/CQRS | wiki/docs/4.1/html/classCqrs_1_1Ninject_1_1Akka_1_1AkkaNinjectDependencyResolver_a08c93ce2f3f66affd8753eb3d3de1211.html | 5749 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://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.16"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.Ninject.Akka.AkkaNinjectDependencyResolver.RawAkkaNinjectDependencyResolver</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="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(initResizable);
/* @license-end */</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/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></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 id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">4.1</span>
</div>
<div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.16 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('classCqrs_1_1Ninject_1_1Akka_1_1AkkaNinjectDependencyResolver_a08c93ce2f3f66affd8753eb3d3de1211.html','');});
/* @license-end */
</script>
<div id="doc-content">
<!-- 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 class="contents">
<a id="a08c93ce2f3f66affd8753eb3d3de1211"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a08c93ce2f3f66affd8753eb3d3de1211">◆ </a></span>RawAkkaNinjectDependencyResolver</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">global.Akka.DI.Ninject.NinjectDependencyResolver Cqrs.Ninject.Akka.AkkaNinjectDependencyResolver.RawAkkaNinjectDependencyResolver</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">get</span><span class="mlabel">set</span><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>The inner resolver used by Akka.NET </p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Ninject.html">Ninject</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Ninject_1_1Akka.html">Akka</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Ninject_1_1Akka_1_1AkkaNinjectDependencyResolver.html">AkkaNinjectDependencyResolver</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li>
</ul>
</div>
</body>
</html>
| lgpl-2.1 |
enthought/qt-mobility | plugins/multimedia/symbian/mmf/s60mediaserviceplugin.h | 2686 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef S60SERVICEPLUGIN_H
#define S60SERVICEPLUGIN_H
#include <qmediaservice.h>
#include <qmediaserviceproviderplugin.h>
#include "s60formatsupported.h"
QT_USE_NAMESPACE
class S60MediaServicePlugin : public QMediaServiceProviderPlugin,public QMediaServiceSupportedFormatsInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedFormatsInterface)
public:
QStringList keys() const;
QMediaService* create(QString const& key);
void release(QMediaService *service);
QtMultimediaKit::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const;
QStringList supportedMimeTypes() const;
private:
mutable QStringList m_supportedmimetypes;
};
#endif // S60SERVICEPLUGIN_H
| lgpl-2.1 |
sipXtapi/sipXtapi | sipXportLib/include/os/OsServerSocket.h | 3775 | //
// Copyright (C) 2006 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
#ifndef _OsServerSocket_h_
#define _OsServerSocket_h_
// SYSTEM INCLUDES
//#include <...>
// APPLICATION INCLUDES
#include <os/OsConnectionSocket.h>
#include <os/OsAtomics.h>
// DEFINES
// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
// FORWARD DECLARATIONS
//: Implements TCP server for accepting TCP connections
// This class provides the implementation of the UDP datagram-based
// socket class which may be instantiated.
class OsServerSocket
{
/* //////////////////////////// PUBLIC //////////////////////////////////// */
public:
/* ============================ CREATORS ================================== */
OsServerSocket(int connectionQueueSize,
int serverPort=PORT_DEFAULT,
const char* szBindAddr = NULL,
const bool bPerformBind = true);
//:Constructor to set up TCP socket server
// Sets the socket connection queue and starts listening on the
// port for requests to connect.
//
//!param: connectionQueueSize - The maximum number of outstanding
// connection requests which are allowed before subsequent requests
// are turned away.
//!param: serverPort - The port on which the server will listen to
// accept connection requests. PORT_DEFAULT means let OS pick port.
OsServerSocket& operator=(const OsServerSocket& rhs);
//:Assignment operator
virtual
~OsServerSocket();
//:Destructor
/* ============================ MANIPULATORS ============================== */
virtual OsConnectionSocket* accept();
//:Blocking accept of next connection
// Blocks and waits for the next TCP connection request.
//!returns: Returns a socket connected to the client requesting the
//!returns: connection. If an error occurs returns NULL.
virtual void close();
//: Close down the server
/* ============================ ACCESSORS ================================= */
virtual int getSocketDescriptor() const;
//:Return the socket descriptor
// Warning: Use of this method risks the creation of platform-dependent
// code.
virtual int getLocalHostPort() const;
//:Return the local port number
// Returns the port to which this socket is bound on this host.
virtual void getBindIp(UtlString& ip) const ;
//:Gets the bind ip (could be 0.0.0.0)
/* ============================ INQUIRY =================================== */
virtual UtlBoolean isOk() const;
//: Server socket is in ready to accept incoming conection requests.
int isConnectionReady();
//: Poll to see if connections are waiting
//!returns: 1 if one or call to accept() will not block <br>
//!returns: 0 if no connections are ready (i.e. accept() will block).
/* //////////////////////////// PROTECTED ///////////////////////////////// */
protected:
virtual OsConnectionSocket* createConnectionSocket(UtlString localIp, int descriptor);
OsAtomicLightInt socketDescriptor;
int localHostPort;
UtlString mLocalIp;
/* //////////////////////////// PRIVATE /////////////////////////////////// */
private:
OsServerSocket(const OsServerSocket& rOsServerSocket);
//:Disable copy constructor
OsServerSocket();
//:Disable default constructor
};
/* ============================ INLINE METHODS ============================ */
#endif // _OsServerSocket_h_
| lgpl-2.1 |
CannibalVox/DimDoors | src/main/java/StevenDimDoors/mod_pocketDim/blocks/BlockDoorGold.java | 1123 | package StevenDimDoors.mod_pocketDim.blocks;
import java.util.Random;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.IconFlipped;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockDoorGold extends BlockDoor
{
public BlockDoorGold(Material par2Material)
{
super( par2Material);
}
@SideOnly(Side.CLIENT)
protected String getTextureName()
{
return mod_pocketDim.modid + ":" + this.getUnlocalizedName();
}
@Override
public Item getItemDropped(int par1, Random par2Random, int par3)
{
return (par1 & 8) != 0 ? null : mod_pocketDim.itemGoldenDoor;
}
@Override
@SideOnly(Side.CLIENT)
public Item getItem(World world, int x, int y, int z) {
return mod_pocketDim.itemGoldenDoor;
}
}
| lgpl-2.1 |
skyvers/wildcat | skyve-ext/src/main/java/org/skyve/impl/domain/messages/SecurityException.java | 377 | package org.skyve.impl.domain.messages;
import org.skyve.domain.messages.DomainException;
public class SecurityException extends DomainException {
/**
* For Serialization
*/
private static final long serialVersionUID = 2941808458696267548L;
public SecurityException(String resource, String userName) {
super(userName + " does not have access to " + resource);
}
}
| lgpl-2.1 |
railfuture/tiki-website | img/flags/flagnames.php | 7500 | <?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: flagnames.php 39469 2012-01-12 21:13:48Z changi67 $
// -*- coding:utf-8 -*-
/*
* The listing associates country names used as filenames for flags in Tikiwiki for language translation
*/
// This script is only for language translations - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
// Here come the dynamically generated strings for img/flags/*.gif
// This file ensures that the following strings will be included in the language translation files.
tra('Afghanistan');
tra('Aland Islands');
tra('Aland_Islands');
tra('Albania');
tra('Algeria');
tra('American Samoa');
tra('American_Samoa');
tra('Andorra');
tra('Angola');
tra('Anguilla');
tra('Antigua');
tra('Argentina');
tra('Armenia');
tra('Aruba');
tra('Australia');
tra('Austria');
tra('Azerbaijan');
tra('Bahamas');
tra('Bahrain');
tra('Bangladesh');
tra('Barbados');
tra('Belarus');
tra('Belgium');
tra('Belize');
tra('Benin');
tra('Bermuda');
tra('Bhutan');
tra('Bolivia');
tra('Bosnia and Herzegovina');
tra('Bosnia_and_Herzegovina');
tra('Botswana');
tra('Bouvet Island');
tra('Bouvet_Island');
tra('Brazil');
tra('British Indian Ocean Territory');
tra('British Virgin Islands');
tra('British_Indian_Ocean_Territory');
tra('British_Virgin_Islands');
tra('Brunei');
tra('Bulgaria');
tra('Burkina Faso');
tra('Burkina_Faso');
tra('Burundi');
tra('Cambodia');
tra('Cameroon');
tra('Canada');
tra('Cape Verde');
tra('Cape_Verde');
tra('Catalan Countries');
tra('Catalan_Countries');
tra('Cayman Islands');
tra('Cayman_Islands');
tra('Central African Republic');
tra('Central_African_Republic');
tra('Chad');
tra('Chile');
tra('China');
tra('Christmas Island');
tra('Christmas_Island');
tra('Cocos Islands');
tra('Cocos_Islands');
tra('Colombia');
tra('Comoros');
tra('Congo Democratic');
tra('Congo');
tra('Congo_Democratic');
tra('Cook Islands');
tra('Cook_Islands');
tra('Costa Rica');
tra('Costa_Rica');
tra('Croatia');
tra('Cuba');
tra('Cyprus');
tra('Czech Republic');
tra('Czech_Republic');
tra('Denmark');
tra('Djibouti');
tra('Dominica');
tra('Dominican Republic');
tra('Dominican_Republic');
tra('Ecuador');
tra('Egypt');
tra('El Salvador');
tra('El_Salvador');
tra('Equatorial Guinea');
tra('Equatorial_Guinea');
tra('Eritrea');
tra('Estonia');
tra('Ethiopia');
tra('Europe');
tra('Falkland Islands');
tra('Falkland_Islands');
tra('Faroe Islands');
tra('Faroe_Islands');
tra('Federated States of Micronesia');
tra('Federated_States_of_Micronesia');
tra('Fiji');
tra('Finland');
tra('France');
tra('French Guiana');
tra('French Polynesia');
tra('French Southern Territories');
tra('French_Guiana');
tra('French_Polynesia');
tra('French_Southern_Territories');
tra('Gabon');
tra('Gambia');
tra('Georgia');
tra('Germany');
tra('Ghana');
tra('Gibraltar');
tra('Greece');
tra('Greenland');
tra('Grenada');
tra('Guadeloupe');
tra('Guam');
tra('Guatemala');
tra('Guernsey');
tra('Guinea Bissau');
tra('Guinea');
tra('Guinea_Bissau');
tra('Guyana');
tra('Haiti');
tra('Heard Island and McDonald Islands');
tra('Heard_Island_and_McDonald_Islands');
tra('Honduras');
tra('Hong Kong');
tra('Hong_Kong');
tra('Hungary');
tra('Iceland');
tra('India');
tra('Indonesia');
tra('Iran');
tra('Iraq');
tra('Ireland');
tra('Isle of Man');
tra('Israel');
tra('Italy');
tra('Ivory Coast');
tra('Ivory_Coast');
tra('Jamaica');
tra('Japan');
tra('Jersey');
tra('Jordan');
tra('Kazakstan');
tra('Kenya');
tra('Kiribati');
tra('Kuwait');
tra('Kyrgyzstan');
tra('Laos');
tra('Latvia');
tra('Lebanon');
tra('Lesotho');
tra('Liberia');
tra('Libya');
tra('Liechtenstein');
tra('Lithuania');
tra('Luxemburg');
tra('Macao');
tra('Macedonia');
tra('Madagascar');
tra('Malawi');
tra('Malaysia');
tra('Maldives');
tra('Mali');
tra('Malta');
tra('Marshall Islands');
tra('Marshall_Islands');
tra('Martinique');
tra('Mauritania');
tra('Mauritius');
tra('Mayotte');
tra('Mexico');
tra('Moldova');
tra('Monaco');
tra('Mongolia');
tra('Montenegro');
tra('Montserrat');
tra('Morocco');
tra('Mozambique');
tra('Myanmar');
tra('Namibia');
tra('Nauru');
tra('Nepal');
tra('Netherlands Antilles');
tra('Netherlands');
tra('Netherlands_Antilles');
tra('New Caledonia');
tra('New Zealand');
tra('New_Caledonia');
tra('New_Zealand');
tra('Nicaragua');
tra('Niger');
tra('Nigeria');
tra('Niue');
tra('None');
tra('Norfolk Island');
tra('Norfolk_Island');
tra('North Korea');
tra('North_Korea');
tra('Northern Mariana Islands');
tra('Northern_Mariana_Islands');
tra('Norway');
tra('Oman');
tra('Other');
tra('Pakistan');
tra('Palau');
tra('Palestine');
tra('Panama');
tra('Papua New Guinea');
tra('Papua_New_Guinea');
tra('Paraguay');
tra('Peru');
tra('Philippines');
tra('Pitcairn');
tra('Poland');
tra('Portugal');
tra('Puerto Rico');
tra('Puerto_Rico');
tra('Quatar');
tra('Republic of Macedonia');
tra('Republic_of_Macedonia');
tra('Reunion');
tra('Romania');
tra('Russia');
tra('Russian Federation');
tra('Russian_Federation');
tra('Rwanda');
tra('Saint Helena');
tra('Saint Kitts and Nevis');
tra('Saint Lucia');
tra('Saint Pierre and Miquelon');
tra('Saint_Helena');
tra('Saint_Kitts_and_Nevis');
tra('Saint_Lucia');
tra('Saint_Pierre_and_Miquelon');
tra('Samoa');
tra('San Marino');
tra('San_Marino');
tra('Sao Tome and Principe');
tra('Sao_Tome_and_Principe');
tra('Saudi Arabia');
tra('Saudi_Arabia');
tra('Senegal');
tra('Serbia');
tra('Seychelles');
tra('Sierra Leone');
tra('Sierra_Leone');
tra('Singapore');
tra('Slovakia');
tra('Slovenia');
tra('Solomon Islands');
tra('Solomon_Islands');
tra('Somalia');
tra('South Africa');
tra('South Georgia and South Sandwich Islands');
tra('South Korea');
tra('South_Africa');
tra('South_Georgia_and_South_Sandwich_Islands');
tra('South_Korea');
tra('Spain');
tra('Sri Lanka');
tra('Sri_Lanka');
tra('St Vincent Grenadines');
tra('St_Vincent_Grenadines');
tra('Sudan');
tra('Surinam');
tra('Svalbard and Jan Mayen');
tra('Svalbard_and_Jan_Mayen');
tra('Swaziland');
tra('Sweden');
tra('Switzerland');
tra('Syria');
tra('Taiwan');
tra('Tajikistan');
tra('Tanzania');
tra('Thailand');
tra('Timor-Leste');
tra('Togo');
tra('Tokelau');
tra('Tonga');
tra('Trinidad Tobago');
tra('Trinidad_Tobago');
tra('Tunisia');
tra('Turkey');
tra('Turkmenistan');
tra('Turks and Caicos Islands');
tra('Turks_and_Caicos_Islands');
tra('Tuvalu');
tra('US Virgin Islands');
tra('US_Virgin_Islands');
tra('Uganda');
tra('Ukraine');
tra('United Arab Emirates');
tra('United Kingdom');
tra('United Nations Organization');
tra('United States Minor Outlying Islands');
tra('United States');
tra('United_Arab_Emirates');
tra('United_Kingdom');
tra('United_Kingdom_-_England_and_Wales');
tra('United_Kingdom_-_Northern_Ireland');
tra('United_Kingdom_-_Scotland');
tra('United_Nations_Organization');
tra('United_States');
tra('United_States_Minor_Outlying_Islands');
tra('Uruguay');
tra('Uzbekistan');
tra('Vanuatu');
tra('Vatican');
tra('Venezuela');
tra('Viet Nam');
tra('Viet_Nam');
tra('Wales');
tra('Wallis and Futuna');
tra('Wallis_and_Futuna');
tra('Western Sahara');
tra('Western_Sahara');
tra('World');
tra('Yemen');
tra('Yugoslavia');
tra('Zambia');
tra('Zimbabwe');
tra('the former Yugoslav Republic of Macedonia');
tra('the_former_Yugoslav_Republic_of_Macedonia');
| lgpl-2.1 |
jbakosi/HYPRE | src/struct_mv/box.c | 23750 | /*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* $Revision$
***********************************************************************EHEADER*/
/******************************************************************************
*
* Member functions for hypre_Box class:
* Basic class functions.
*
*****************************************************************************/
#include "_hypre_struct_mv.h"
/*==========================================================================
* Member functions: hypre_Index
*==========================================================================*/
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SetIndex( hypre_Index index,
HYPRE_Int val )
{
HYPRE_Int d;
for (d = 0; d < HYPRE_MAXDIM; d++)
{
hypre_IndexD(index, d) = val;
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_CopyIndex( hypre_Index in_index,
hypre_Index out_index )
{
HYPRE_Int d;
for (d = 0; d < HYPRE_MAXDIM; d++)
{
hypre_IndexD(out_index, d) = hypre_IndexD(in_index, d);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_CopyToCleanIndex( hypre_Index in_index,
HYPRE_Int ndim,
hypre_Index out_index )
{
HYPRE_Int d;
for (d = 0; d < ndim; d++)
{
hypre_IndexD(out_index, d) = hypre_IndexD(in_index, d);
}
for (d = ndim; d < HYPRE_MAXDIM; d++)
{
hypre_IndexD(out_index, d) = 0;
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_IndexEqual( hypre_Index index,
HYPRE_Int val,
HYPRE_Int ndim )
{
HYPRE_Int d, equal;
equal = 1;
for (d = 0; d < ndim; d++)
{
if (hypre_IndexD(index, d) != val)
{
equal = 0;
break;
}
}
return equal;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_IndexMin( hypre_Index index,
HYPRE_Int ndim )
{
HYPRE_Int d, min;
min = hypre_IndexD(index, 0);
for (d = 1; d < ndim; d++)
{
if (hypre_IndexD(index, d) < min)
{
min = hypre_IndexD(index, d);
}
}
return min;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_IndexMax( hypre_Index index,
HYPRE_Int ndim )
{
HYPRE_Int d, max;
max = hypre_IndexD(index, 0);
for (d = 1; d < ndim; d++)
{
if (hypre_IndexD(index, d) < max)
{
max = hypre_IndexD(index, d);
}
}
return max;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_AddIndexes( hypre_Index index1,
hypre_Index index2,
HYPRE_Int ndim,
hypre_Index result )
{
HYPRE_Int d;
for (d = 0; d < ndim; d++)
{
hypre_IndexD(result, d) = hypre_IndexD(index1, d) + hypre_IndexD(index2, d);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SubtractIndexes( hypre_Index index1,
hypre_Index index2,
HYPRE_Int ndim,
hypre_Index result )
{
HYPRE_Int d;
for (d = 0; d < ndim; d++)
{
hypre_IndexD(result, d) = hypre_IndexD(index1, d) - hypre_IndexD(index2, d);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_IndexesEqual( hypre_Index index1,
hypre_Index index2,
HYPRE_Int ndim )
{
HYPRE_Int d, equal;
equal = 1;
for (d = 0; d < ndim; d++)
{
if (hypre_IndexD(index1, d) != hypre_IndexD(index2, d))
{
equal = 0;
break;
}
}
return equal;
}
/*==========================================================================
* Member functions: hypre_Box
*==========================================================================*/
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
hypre_Box *
hypre_BoxCreate( HYPRE_Int ndim )
{
hypre_Box *box;
box = hypre_TAlloc(hypre_Box, 1);
hypre_BoxNDim(box) = ndim;
return box;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxDestroy( hypre_Box *box )
{
if (box)
{
hypre_TFree(box);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* This is used to initialize ndim when the box has static storage
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxInit( hypre_Box *box,
HYPRE_Int ndim )
{
hypre_BoxNDim(box) = ndim;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxSetExtents( hypre_Box *box,
hypre_Index imin,
hypre_Index imax )
{
hypre_CopyIndex(imin, hypre_BoxIMin(box));
hypre_CopyIndex(imax, hypre_BoxIMax(box));
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_CopyBox( hypre_Box *box1,
hypre_Box *box2 )
{
hypre_CopyIndex(hypre_BoxIMin(box1), hypre_BoxIMin(box2));
hypre_CopyIndex(hypre_BoxIMax(box1), hypre_BoxIMax(box2));
hypre_BoxNDim(box2) = hypre_BoxNDim(box1);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Return a duplicate box.
*--------------------------------------------------------------------------*/
hypre_Box *
hypre_BoxDuplicate( hypre_Box *box )
{
hypre_Box *new_box;
new_box = hypre_BoxCreate(hypre_BoxNDim(box));
hypre_CopyBox(box, new_box);
return new_box;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxVolume( hypre_Box *box )
{
HYPRE_Int volume, d, ndim = hypre_BoxNDim(box);
volume = 1;
for (d = 0; d < ndim; d++)
{
volume *= hypre_BoxSizeD(box, d);
}
return volume;
}
/*--------------------------------------------------------------------------
* To prevent overflow when needed
*--------------------------------------------------------------------------*/
HYPRE_Real
hypre_doubleBoxVolume( hypre_Box *box )
{
HYPRE_Real volume;
HYPRE_Int d, ndim = hypre_BoxNDim(box);
volume = 1.0;
for (d = 0; d < ndim; d++)
{
volume *= hypre_BoxSizeD(box, d);
}
return volume;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_IndexInBox( hypre_Index index,
hypre_Box *box )
{
HYPRE_Int d, inbox, ndim = hypre_BoxNDim(box);
inbox = 1;
for (d = 0; d < ndim; d++)
{
if (!hypre_IndexDInBox(index, d, box))
{
inbox = 0;
break;
}
}
return inbox;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxGetSize( hypre_Box *box,
hypre_Index size )
{
HYPRE_Int d, ndim = hypre_BoxNDim(box);
for (d = 0; d < ndim; d++)
{
hypre_IndexD(size, d) = hypre_BoxSizeD(box, d);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxGetStrideSize( hypre_Box *box,
hypre_Index stride,
hypre_Index size )
{
HYPRE_Int d, s, ndim = hypre_BoxNDim(box);
for (d = 0; d < ndim; d++)
{
s = hypre_BoxSizeD(box, d);
if (s > 0)
{
s = (s - 1) / hypre_IndexD(stride, d) + 1;
}
hypre_IndexD(size, d) = s;
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxGetStrideVolume( hypre_Box *box,
hypre_Index stride,
HYPRE_Int *volume_ptr )
{
HYPRE_Int volume, d, s, ndim = hypre_BoxNDim(box);
volume = 1;
for (d = 0; d < ndim; d++)
{
s = hypre_BoxSizeD(box, d);
if (s > 0)
{
s = (s - 1) / hypre_IndexD(stride, d) + 1;
}
volume *= s;
}
*volume_ptr = volume;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Returns the rank of an index into a multi-D box where the assumed ordering is
* dimension 0 first, then dimension 1, etc.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxIndexRank( hypre_Box *box,
hypre_Index index )
{
HYPRE_Int rank, size, d, ndim = hypre_BoxNDim(box);
rank = 0;
size = 1;
for (d = 0; d < ndim; d++)
{
rank += (hypre_IndexD(index, d) - hypre_BoxIMinD(box, d)) * size;
size *= hypre_BoxSizeD(box, d);
}
return rank;
}
/*--------------------------------------------------------------------------
* Computes an index into a multi-D box from a rank where the assumed ordering
* is dimension 0 first, then dimension 1, etc.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxRankIndex( hypre_Box *box,
HYPRE_Int rank,
hypre_Index index )
{
HYPRE_Int d, r, s, ndim = hypre_BoxNDim(box);
r = rank;
s = hypre_BoxVolume(box);
for (d = ndim-1; d >= 0; d--)
{
s = s / hypre_BoxSizeD(box, d);
hypre_IndexD(index, d) = r / s;
hypre_IndexD(index, d) += hypre_BoxIMinD(box, d);
r = r % s;
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Returns the distance of an index offset in a multi-D box where the assumed
* ordering is dimension 0 first, then dimension 1, etc.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxOffsetDistance( hypre_Box *box,
hypre_Index index )
{
HYPRE_Int dist, size, d, ndim = hypre_BoxNDim(box);
dist = 0;
size = 1;
for (d = 0; d < ndim; d++)
{
dist += hypre_IndexD(index, d) * size;
size *= hypre_BoxSizeD(box, d);
}
return dist;
}
/*--------------------------------------------------------------------------
* Shift a box by a positive shift
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxShiftPos( hypre_Box *box,
hypre_Index shift )
{
HYPRE_Int d, ndim = hypre_BoxNDim(box);
for (d = 0; d < ndim; d++)
{
hypre_BoxIMinD(box, d) += hypre_IndexD(shift, d);
hypre_BoxIMaxD(box, d) += hypre_IndexD(shift, d);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Shift a box by a negative shift
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxShiftNeg( hypre_Box *box,
hypre_Index shift )
{
HYPRE_Int d, ndim = hypre_BoxNDim(box);
for (d = 0; d < ndim; d++)
{
hypre_BoxIMinD(box, d) -= hypre_IndexD(shift, d);
hypre_BoxIMaxD(box, d) -= hypre_IndexD(shift, d);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Grow a box outward in each dimension as specified by index
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxGrowByIndex( hypre_Box *box,
hypre_Index index )
{
hypre_IndexRef imin = hypre_BoxIMin(box);
hypre_IndexRef imax = hypre_BoxIMax(box);
HYPRE_Int ndim = hypre_BoxNDim(box);
HYPRE_Int d, i;
for (d = 0; d < ndim; d++)
{
i = hypre_IndexD(index, d);
hypre_IndexD(imin, d) -= i;
hypre_IndexD(imax, d) += i;
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Grow a box outward by val in each dimension
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxGrowByValue( hypre_Box *box,
HYPRE_Int val )
{
HYPRE_Int *imin = hypre_BoxIMin(box);
HYPRE_Int *imax = hypre_BoxIMax(box);
HYPRE_Int ndim = hypre_BoxNDim(box);
HYPRE_Int d;
for (d = 0; d < ndim; d++)
{
hypre_IndexD(imin, d) -= val;
hypre_IndexD(imax, d) += val;
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Grow a box as specified by array
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxGrowByArray( hypre_Box *box,
HYPRE_Int *array )
{
HYPRE_Int *imin = hypre_BoxIMin(box);
HYPRE_Int *imax = hypre_BoxIMax(box);
HYPRE_Int ndim = hypre_BoxNDim(box);
HYPRE_Int d;
for (d = 0; d < ndim; d++)
{
imin[d] -= array[2*d];
imax[d] += array[2*d+1];
}
return hypre_error_flag;
}
/*==========================================================================
* Member functions: hypre_BoxArray
*==========================================================================*/
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
hypre_BoxArray *
hypre_BoxArrayCreate( HYPRE_Int size,
HYPRE_Int ndim )
{
HYPRE_Int i;
hypre_Box *box;
hypre_BoxArray *box_array;
box_array = hypre_TAlloc(hypre_BoxArray, 1);
hypre_BoxArrayBoxes(box_array) = hypre_CTAlloc(hypre_Box, size);
hypre_BoxArraySize(box_array) = size;
hypre_BoxArrayAllocSize(box_array) = size;
hypre_BoxArrayNDim(box_array) = ndim;
for (i = 0; i < size; i++)
{
box = hypre_BoxArrayBox(box_array, i);
hypre_BoxNDim(box) = ndim;
}
return box_array;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxArrayDestroy( hypre_BoxArray *box_array )
{
if (box_array)
{
hypre_TFree(hypre_BoxArrayBoxes(box_array));
hypre_TFree(box_array);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxArraySetSize( hypre_BoxArray *box_array,
HYPRE_Int size )
{
HYPRE_Int alloc_size;
alloc_size = hypre_BoxArrayAllocSize(box_array);
if (size > alloc_size)
{
HYPRE_Int i, old_alloc_size, ndim = hypre_BoxArrayNDim(box_array);
hypre_Box *box;
old_alloc_size = alloc_size;
alloc_size = size + hypre_BoxArrayExcess;
hypre_BoxArrayBoxes(box_array) =
hypre_TReAlloc(hypre_BoxArrayBoxes(box_array), hypre_Box, alloc_size);
hypre_BoxArrayAllocSize(box_array) = alloc_size;
for (i = old_alloc_size; i < alloc_size; i++)
{
box = hypre_BoxArrayBox(box_array, i);
hypre_BoxNDim(box) = ndim;
}
}
hypre_BoxArraySize(box_array) = size;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Return a duplicate box_array.
*--------------------------------------------------------------------------*/
hypre_BoxArray *
hypre_BoxArrayDuplicate( hypre_BoxArray *box_array )
{
hypre_BoxArray *new_box_array;
HYPRE_Int i;
new_box_array = hypre_BoxArrayCreate(
hypre_BoxArraySize(box_array), hypre_BoxArrayNDim(box_array));
hypre_ForBoxI(i, box_array)
{
hypre_CopyBox(hypre_BoxArrayBox(box_array, i),
hypre_BoxArrayBox(new_box_array, i));
}
return new_box_array;
}
/*--------------------------------------------------------------------------
* Append box to the end of box_array.
* The box_array may be empty.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_AppendBox( hypre_Box *box,
hypre_BoxArray *box_array )
{
HYPRE_Int size;
size = hypre_BoxArraySize(box_array);
hypre_BoxArraySetSize(box_array, (size + 1));
hypre_CopyBox(box, hypre_BoxArrayBox(box_array, size));
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Delete box from box_array.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_DeleteBox( hypre_BoxArray *box_array,
HYPRE_Int index )
{
HYPRE_Int i;
for (i = index; i < hypre_BoxArraySize(box_array) - 1; i++)
{
hypre_CopyBox(hypre_BoxArrayBox(box_array, i+1),
hypre_BoxArrayBox(box_array, i));
}
hypre_BoxArraySize(box_array) --;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Deletes boxes corrsponding to indices from box_array.
* Assumes indices are in ascending order. (AB 11/04)
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_DeleteMultipleBoxes( hypre_BoxArray *box_array,
HYPRE_Int* indices,
HYPRE_Int num )
{
HYPRE_Int i, j, start, array_size;
if (num < 1)
{
return hypre_error_flag;
}
array_size = hypre_BoxArraySize(box_array);
start = indices[0];
j = 0;
for (i = start; (i + j) < array_size; i++)
{
if (j < num)
{
while ((i+j) == indices[j]) /* see if deleting consecutive items */
{
j++; /*increase the shift*/
if (j == num) break;
}
}
if ( (i+j) < array_size) /* if deleting the last item then no moving */
{
hypre_CopyBox(hypre_BoxArrayBox(box_array, i+j),
hypre_BoxArrayBox(box_array, i));
}
}
hypre_BoxArraySize(box_array) = array_size - num;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Append box_array_0 to the end of box_array_1.
* The box_array_1 may be empty.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_AppendBoxArray( hypre_BoxArray *box_array_0,
hypre_BoxArray *box_array_1 )
{
HYPRE_Int size, size_0;
HYPRE_Int i;
size = hypre_BoxArraySize(box_array_1);
size_0 = hypre_BoxArraySize(box_array_0);
hypre_BoxArraySetSize(box_array_1, (size + size_0));
/* copy box_array_0 boxes into box_array_1 */
for (i = 0; i < size_0; i++)
{
hypre_CopyBox(hypre_BoxArrayBox(box_array_0, i),
hypre_BoxArrayBox(box_array_1, size + i));
}
return hypre_error_flag;
}
/*==========================================================================
* Member functions: hypre_BoxArrayArray
*==========================================================================*/
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
hypre_BoxArrayArray *
hypre_BoxArrayArrayCreate( HYPRE_Int size,
HYPRE_Int ndim )
{
hypre_BoxArrayArray *box_array_array;
HYPRE_Int i;
box_array_array = hypre_CTAlloc(hypre_BoxArrayArray, 1);
hypre_BoxArrayArrayBoxArrays(box_array_array) =
hypre_CTAlloc(hypre_BoxArray *, size);
for (i = 0; i < size; i++)
{
hypre_BoxArrayArrayBoxArray(box_array_array, i) =
hypre_BoxArrayCreate(0, ndim);
}
hypre_BoxArrayArraySize(box_array_array) = size;
hypre_BoxArrayArrayNDim(box_array_array) = ndim;
return box_array_array;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoxArrayArrayDestroy( hypre_BoxArrayArray *box_array_array )
{
HYPRE_Int i;
if (box_array_array)
{
hypre_ForBoxArrayI(i, box_array_array)
hypre_BoxArrayDestroy(
hypre_BoxArrayArrayBoxArray(box_array_array, i));
hypre_TFree(hypre_BoxArrayArrayBoxArrays(box_array_array));
hypre_TFree(box_array_array);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* Return a duplicate box_array_array.
*--------------------------------------------------------------------------*/
hypre_BoxArrayArray *
hypre_BoxArrayArrayDuplicate( hypre_BoxArrayArray *box_array_array )
{
hypre_BoxArrayArray *new_box_array_array;
hypre_BoxArray **new_box_arrays;
HYPRE_Int new_size;
hypre_BoxArray **box_arrays;
HYPRE_Int i;
new_size = hypre_BoxArrayArraySize(box_array_array);
new_box_array_array = hypre_BoxArrayArrayCreate(
new_size, hypre_BoxArrayArrayNDim(box_array_array));
if (new_size)
{
new_box_arrays = hypre_BoxArrayArrayBoxArrays(new_box_array_array);
box_arrays = hypre_BoxArrayArrayBoxArrays(box_array_array);
for (i = 0; i < new_size; i++)
{
hypre_AppendBoxArray(box_arrays[i], new_box_arrays[i]);
}
}
return new_box_array_array;
}
| lgpl-2.1 |
jonmbake/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/checks/design/OneTopLevelClassCheckTest.java | 7614 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2018 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.design;
import static com.puppycrawl.tools.checkstyle.checks.design.OneTopLevelClassCheck.MSG_KEY;
import static org.junit.Assert.assertArrayEquals;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
public class OneTopLevelClassCheckTest extends AbstractModuleTestSupport {
@Override
protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/checks/design/onetoplevelclass";
}
@Test
public void testGetRequiredTokens() {
final OneTopLevelClassCheck checkObj = new OneTopLevelClassCheck();
assertArrayEquals("Required tokens array is not empty",
CommonUtils.EMPTY_INT_ARRAY, checkObj.getRequiredTokens());
}
@Test
public void testClearState() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String firstInputFilePath = getPath("InputOneTopLevelClassDeclarationOrder.java");
final String secondInputFilePath = getPath("InputOneTopLevelClassInterface2.java");
final File[] inputs = {
new File(firstInputFilePath),
new File(secondInputFilePath),
};
final List<String> expectedFirstInput = Collections.singletonList(
"10: " + getCheckMessage(MSG_KEY, "InputDeclarationOrderEnum"));
final List<String> expectedSecondInput = Arrays.asList(
"3: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner1"),
"11: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner2"));
verify(createChecker(checkConfig), inputs,
ImmutableMap.of(firstInputFilePath, expectedFirstInput,
secondInputFilePath, expectedSecondInput));
}
@Test
public void testAcceptableTokens() {
final OneTopLevelClassCheck check = new OneTopLevelClassCheck();
check.getAcceptableTokens();
// ZERO tokens as Check do Traverse of Tree himself, he does not need to subscribed to
// Tokens
Assert.assertEquals("Acceptable tokens array size larger than 0",
0, check.getAcceptableTokens().length);
}
@Test
public void testFileWithOneTopLevelClass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputOneTopLevelClass.java"), expected);
}
@Test
public void testFileWithOneTopLevelInterface() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputOneTopLevelClassInterface.java"), expected);
}
@Test
public void testFileWithOneTopLevelEnum() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputOneTopLevelClassEnum.java"), expected);
}
@Test
public void testFileWithNoPublicTopLevelClass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"8: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassNoPublic2"),
};
verify(checkConfig, getPath("InputOneTopLevelClassNoPublic.java"), expected);
}
@Test
public void testFileWithThreeTopLevelInterface() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"3: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner1"),
"11: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner2"),
};
verify(checkConfig, getPath("InputOneTopLevelClassInterface2.java"), expected);
}
@Test
public void testFileWithThreeTopLevelEnum() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"3: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassEnum2inner1"),
"11: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassEnum2inner2"),
};
verify(checkConfig, getPath("InputOneTopLevelClassEnum2.java"), expected);
}
@Test
public void testFileWithFewTopLevelClasses() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"25: " + getCheckMessage(MSG_KEY, "NoSuperClone"),
"29: " + getCheckMessage(MSG_KEY, "InnerClone"),
"33: " + getCheckMessage(MSG_KEY, "CloneWithTypeArguments"),
"37: " + getCheckMessage(MSG_KEY, "CloneWithTypeArgumentsAndNoSuper"),
"41: " + getCheckMessage(MSG_KEY, "MyClassWithGenericSuperMethod"),
"45: " + getCheckMessage(MSG_KEY, "AnotherClass"),
"48: " + getCheckMessage(MSG_KEY, "NativeTest"),
};
verify(checkConfig, getPath("InputOneTopLevelClassClone.java"), expected);
}
@Test
public void testFileWithSecondEnumTopLevelClass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"10: " + getCheckMessage(MSG_KEY, "InputDeclarationOrderEnum"),
};
verify(checkConfig, getPath("InputOneTopLevelClassDeclarationOrder.java"), expected);
}
@Test
public void testPackageInfoWithNoTypesDeclared() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getNonCompilablePath("package-info.java"), expected);
}
}
| lgpl-2.1 |
cdmdotnet/CQRS | wiki/docs/4.0/html/classCqrs_1_1Azure_1_1ServiceBus_1_1MessageSerialiser_a9207c867f358e352eee5d3727fe620e4.html | 6442 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://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.16"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.Azure.ServiceBus.MessageSerialiser.DeserialiseEvent</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="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(initResizable);
/* @license-end */</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/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></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 id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">4.0</span>
</div>
<div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.16 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('classCqrs_1_1Azure_1_1ServiceBus_1_1MessageSerialiser_a9207c867f358e352eee5d3727fe620e4.html','');});
/* @license-end */
</script>
<div id="doc-content">
<!-- 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 class="contents">
<a id="a9207c867f358e352eee5d3727fe620e4"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a9207c867f358e352eee5d3727fe620e4">◆ </a></span>DeserialiseEvent()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="interfaceCqrs_1_1Events_1_1IEvent.html">IEvent</a><TAuthenticationToken> <a class="el" href="classCqrs_1_1Azure_1_1ServiceBus_1_1MessageSerialiser.html">Cqrs.Azure.ServiceBus.MessageSerialiser</a>< TAuthenticationToken >.DeserialiseEvent </td>
<td>(</td>
<td class="paramtype">string @ </td>
<td class="paramname"><em>event</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Deserialise the provided <em>event</em> from its string representation. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">event</td><td>A string representation of an IEvent<TAuthenticationToken> to deserialise.</td></tr>
</table>
</dd>
</dl>
<p>Implements <a class="el" href="interfaceCqrs_1_1Azure_1_1ServiceBus_1_1IMessageSerialiser_ab65c6e4a8c2a660ceb2236ee11fd33f6.html#ab65c6e4a8c2a660ceb2236ee11fd33f6">Cqrs.Azure.ServiceBus.IMessageSerialiser< TAuthenticationToken ></a>.</p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure.html">Azure</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure_1_1ServiceBus.html">ServiceBus</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Azure_1_1ServiceBus_1_1MessageSerialiser.html">MessageSerialiser</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li>
</ul>
</div>
</body>
</html>
| lgpl-2.1 |
MichelRottleuthner/RIOT | sys/rtt_stdio/rtt_stdio.c | 14455 | /*
* Copyright (C) 2016 Michael Andersen <[email protected]>
*
* This file was based on SEGGER's reference implementation
* which can be found here: https://www.segger.com/jlink-rtt.html
* (c) 2014-2016 SEGGER Microcontroller GmbH & Co. KG
* This implementation bore the following license notes:
**********************************************************************
* SEGGER MICROCONTROLLER GmbH & Co. KG *
* Solutions for real time microcontroller applications *
**********************************************************************
* *
* (c) 2014 - 2016 SEGGER Microcontroller GmbH & Co. KG *
* *
* www.segger.com Support: [email protected] *
* *
**********************************************************************
* *
* SEGGER RTT * Real Time Transfer for embedded targets *
* *
**********************************************************************
* *
* All rights reserved. *
* *
* SEGGER strongly recommends to not make any changes *
* to or modify the source code of this software in order to stay *
* compatible with the RTT protocol and J-Link. *
* *
* Redistribution and use in source and binary forms, with or *
* without modification, are permitted provided that the following *
* conditions are met: *
* *
* o Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* *
* o Redistributions in binary form must reproduce the above *
* copyright notice, this list of conditions and the following *
* disclaimer in the documentation and/or other materials provided *
* with the distribution. *
* *
* o Neither the name of SEGGER Microcontroller GmbH & Co. KG *
* nor the names of its contributors may be used to endorse or *
* promote products derived from this software without specific *
* prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND *
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT *
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; *
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE *
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH *
* DAMAGE. *
* *
**********************************************************************/
/**
* @ingroup sys
* @{
*
* @file
* @brief SEGGER RTT stdio implementation
*
* This file implements UART read/write functions, but it
* is actually a virtual UART backed by a ringbuffer that
* complies with SEGGER RTT. It is designed to shadow
* uart_stdio that is used by newlib.
*
* @author Michael Andersen <[email protected]>
*
* @}
*/
#include <stdio.h>
#if MODULE_VFS
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#endif
#include <string.h>
#include <rtt_stdio.h>
#include "thread.h"
#include "mutex.h"
#include "xtimer.h"
#if MODULE_VFS
#include "vfs.h"
#endif
/* This parameter affects the bandwidth of both input and output. Decreasing
it will significantly improve bandwidth at the cost of CPU time. */
#ifndef STDIO_POLL_INTERVAL
#define STDIO_POLL_INTERVAL 50000U
#endif
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#ifndef STDIO_TX_BUFSIZE
#define STDIO_TX_BUFSIZE (512)
#endif
#ifndef STDIO_RX_BUFSIZE
#define STDIO_RX_BUFSIZE (32)
#endif
/**
* @brief use mutex for waiting on stdin being enabled
*/
static mutex_t _rx_mutex = MUTEX_INIT;
/**
* @brief buffer holding stdout
*/
static char up_buffer [STDIO_TX_BUFSIZE];
/**
* @brief buffer holding stdin
*/
static char down_buffer [STDIO_RX_BUFSIZE];
/**
* @brief flag that enables stdin polling
*/
static char stdin_enabled = 0;
/**
* @brief flag that enables stdout blocking/polling
*/
static char blocking_stdout = 0;
/**
* @brief SEGGER's ring buffer implementation
*/
typedef struct {
const char* channel_name; /* Optional name. Standard names so far are:
"Terminal", "VCom" */
char* buf_ptr; /* Pointer to start of buffer */
int32_t buf_size; /* Buffer size in bytes. Note that one byte is
lost, as this implementation does not fill up
the buffer in order to avoid the problem of
being unable to distinguish between full and
empty. */
volatile int32_t wr_off; /* Position of next item to be written by either
host (down-buffer) or target (up-buffer). Must
be volatile since it may be modified by host
(down-buffer) */
volatile int32_t rd_off; /* Position of next item to be read by target
(down-buffer) or host (up-buffer). Must be
volatile since it may be modified by host
(up-buffer) */
int32_t flags; /* Contains configuration flags */
} rtt_ringbuf_t;
/**
* @brief RTT control block which describes the number of buffers available
* as well as the configuration for each buffer. The struct definition
* is fixed, as it is expected by SEGGER's software
*/
typedef struct {
char sentinel[16]; /* Initialized to "SEGGER RTT" */
int32_t max_up_buffers; /* Initialized to 1 */
int32_t max_down_buffers; /* Initialized to 1 */
rtt_ringbuf_t up[1]; /* Up buffers, transferring information up
from target via debug probe to host */
rtt_ringbuf_t down[1]; /* Down buffers, transferring information
down from host via debug probe to target */
} segger_rtt_cb_t;
/**
* @brief The SEGGER Real-Time-Terminal control block (CB)
*/
static segger_rtt_cb_t rtt_cb = {
"SEGGER RTT",
1,
1,
{{ "Terminal", &up_buffer[0], sizeof(up_buffer), 0, 0, 0 }},
{{ "Terminal", &down_buffer[0], sizeof(down_buffer), 0, 0, 0 }},
};
/**
* @brief read bytes from the down buffer. This function does not block.
* The logic here is unmodified from SEGGER's reference, it is just
* refactored to match code style. The string is not null terminated.
*
* @return the number of bytes read
*/
static int rtt_read(char* buf_ptr, uint16_t buf_size) {
int16_t num_bytes_rem;
uint16_t num_bytes_read;
int16_t rd_off;
int16_t wr_off;
rd_off = rtt_cb.down[0].rd_off;
wr_off = rtt_cb.down[0].wr_off;
num_bytes_read = 0;
/* Read from current read position to wrap-around of buffer, first */
if (rd_off > wr_off) {
num_bytes_rem = rtt_cb.down[0].buf_size - rd_off;
num_bytes_rem = MIN(num_bytes_rem, (int)buf_size);
memcpy(buf_ptr, rtt_cb.down[0].buf_ptr + rd_off, num_bytes_rem);
num_bytes_read += num_bytes_rem;
buf_ptr += num_bytes_rem;
buf_size -= num_bytes_rem;
rd_off += num_bytes_rem;
/* Handle wrap-around of buffer */
if (rd_off == rtt_cb.down[0].buf_size) {
rd_off = 0;
}
}
/* Read remaining items of buffer */
num_bytes_rem = wr_off - rd_off;
num_bytes_rem = MIN(num_bytes_rem, (int)buf_size);
if (num_bytes_rem > 0) {
memcpy(buf_ptr, rtt_cb.down[0].buf_ptr + rd_off, num_bytes_rem);
num_bytes_read += num_bytes_rem;
rd_off += num_bytes_rem;
}
if (num_bytes_read) {
rtt_cb.down[0].rd_off = rd_off;
}
return num_bytes_read;
}
/**
* @brief write bytes to the up buffer. This function does not block.
* The logic here is unmodified from SEGGER's reference, it is just
* refactored to match code style. The string does not need to be null
* terminated.
*
* @return the number of bytes read
*/
int rtt_write(const char* buf_ptr, unsigned num_bytes) {
int num_bytes_to_write;
unsigned num_bytes_written;
int rd_off;
rd_off = rtt_cb.up[0].rd_off;
num_bytes_to_write = rd_off - rtt_cb.up[0].wr_off - 1;
if (num_bytes_to_write < 0) {
num_bytes_to_write += rtt_cb.up[0].buf_size;
}
/* If the complete data does not fit in the buffer, trim the data */
if ((int)num_bytes > num_bytes_to_write) {
num_bytes = num_bytes_to_write;
}
/* Early out if there is nothing to do */
if (num_bytes == 0) {
return 0;
}
/* Write data to buffer and handle wrap-around if necessary */
num_bytes_written = 0;
do {
/* May be changed by host (debug probe) in the meantime */
rd_off = rtt_cb.up[0].rd_off;
num_bytes_to_write = rd_off - rtt_cb.up[0].wr_off - 1;
if (num_bytes_to_write < 0) {
num_bytes_to_write += rtt_cb.up[0].buf_size;
}
/* Number of bytes that can be written until buffer wrap-around */
num_bytes_to_write = MIN(num_bytes_to_write, (rtt_cb.up[0].buf_size -
rtt_cb.up[0].wr_off));
num_bytes_to_write = MIN(num_bytes_to_write, (int)num_bytes);
memcpy(rtt_cb.up[0].buf_ptr + rtt_cb.up[0].wr_off, buf_ptr, num_bytes_to_write);
num_bytes_written += num_bytes_to_write;
buf_ptr += num_bytes_to_write;
num_bytes -= num_bytes_to_write;
rtt_cb.up[0].wr_off += num_bytes_to_write;
if (rtt_cb.up[0].wr_off == rtt_cb.up[0].buf_size) {
rtt_cb.up[0].wr_off = 0;
}
} while (num_bytes);
return num_bytes_written;
}
#if MODULE_VFS
static ssize_t rtt_stdio_vfs_read(vfs_file_t *filp, void *dest, size_t nbytes);
static ssize_t rtt_stdio_vfs_write(vfs_file_t *filp, const void *src, size_t nbytes);
/**
* @brief VFS file operation table for stdin/stdout/stderr
*/
static vfs_file_ops_t rtt_stdio_vfs_ops = {
.read = rtt_stdio_vfs_read,
.write = rtt_stdio_vfs_write,
};
static ssize_t rtt_stdio_vfs_read(vfs_file_t *filp, void *dest, size_t nbytes)
{
int fd = filp->private_data.value;
if (fd != STDIN_FILENO) {
return -EBADF;
}
return rtt_read(dest, nbytes);
}
static ssize_t rtt_stdio_vfs_write(vfs_file_t *filp, const void *src, size_t nbytes)
{
int fd = filp->private_data.value;
if (fd == STDIN_FILENO) {
return -EBADF;
}
return rtt_write(src, nbytes);
}
#endif
void uart_stdio_init(void) {
#ifndef RTT_STDIO_DISABLE_STDIN
stdin_enabled = 1;
#endif
#ifdef RTT_STDIO_ENABLE_BLOCKING_STDOUT
blocking_stdout = 1;
#endif
#if MODULE_VFS
int fd;
fd = vfs_bind(STDIN_FILENO, O_RDONLY, &rtt_stdio_vfs_ops, (void *)STDIN_FILENO);
if (fd < 0) {
/* How to handle errors on init? */
}
fd = vfs_bind(STDOUT_FILENO, O_WRONLY, &rtt_stdio_vfs_ops, (void *)STDOUT_FILENO);
if (fd < 0) {
/* How to handle errors on init? */
}
fd = vfs_bind(STDERR_FILENO, O_WRONLY, &rtt_stdio_vfs_ops, (void *)STDERR_FILENO);
if (fd < 0) {
/* How to handle errors on init? */
}
#endif
/* the mutex should start locked */
mutex_lock(&_rx_mutex);
}
void rtt_stdio_enable_stdin(void) {
stdin_enabled = 1;
mutex_unlock(&_rx_mutex);
}
void rtt_stdio_enable_blocking_stdout(void) {
blocking_stdout = 1;
}
/* The reason we have this strange logic is as follows:
If we have an RTT console, we are powered, and so don't care
that polling uses a lot of power. If however, we do not
actually have an RTT console (because we are deployed on
a battery somewhere) then we REALLY don't want to poll
especially since we are not expecting to EVER get input. */
int uart_stdio_read(char* buffer, int count) {
int res = rtt_read(buffer, count);
if (res == 0) {
if (!stdin_enabled) {
mutex_lock(&_rx_mutex);
/* We only unlock when rtt_stdio_enable_stdin is called
Note that we assume only one caller invoked this function */
}
xtimer_ticks32_t last_wakeup = xtimer_now();
while(1) {
xtimer_periodic_wakeup(&last_wakeup, STDIO_POLL_INTERVAL);
res = rtt_read(buffer, count);
if (res > 0)
return res;
}
}
return res;
}
int uart_stdio_write(const char* buffer, int len) {
int written = rtt_write(buffer, len);
xtimer_ticks32_t last_wakeup = xtimer_now();
while (blocking_stdout && written < len) {
xtimer_periodic_wakeup(&last_wakeup, STDIO_POLL_INTERVAL);
written += rtt_write(&buffer[written], len-written);
}
return written;
}
| lgpl-2.1 |
ld3300/ola | python/examples/ola_artnet_params.py | 1591 | #!/usr/bin/env python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# ola_artnet_params.py
# Copyright (C) 2005 Simon Newton
"""Fetch some ArtNet parameters."""
__author__ = '[email protected] (Simon Newton)'
from ola.ClientWrapper import ClientWrapper
from ola import ArtNetConfigMessages_pb2
def ArtNetConfigureReply(state, response):
reply = ArtNetConfigMessages_pb2.Reply()
reply.ParseFromString(response)
print('Short Name: %s' % reply.options.short_name)
print('Long Name: %s' % reply.options.long_name)
print('Subnet: %d' % reply.options.subnet)
wrapper.Stop()
#Set this appropriately
device_alias = 1
wrapper = ClientWrapper()
client = wrapper.Client()
artnet_request = ArtNetConfigMessages_pb2.Request()
artnet_request.type = artnet_request.ARTNET_OPTIONS_REQUEST
client.ConfigureDevice(device_alias, artnet_request.SerializeToString(),
ArtNetConfigureReply)
wrapper.Run()
| lgpl-2.1 |
dcuartielles/SmartWatch | build/linux/work/hardware/tools/arm/share/doc/gcc-arm-none-eabi/html/as.html/H8_002f300_002dAddressing.html | 4108 | <html lang="en">
<head>
<title>H8/300-Addressing - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="H8_002f300-Syntax.html#H8_002f300-Syntax" title="H8/300 Syntax">
<link rel="prev" href="H8_002f300_002dRegs.html#H8_002f300_002dRegs" title="H8/300-Regs">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2000, 2001, 2002, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation,
Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="H8%2f300-Addressing"></a>
<a name="H8_002f300_002dAddressing"></a>
Previous: <a rel="previous" accesskey="p" href="H8_002f300_002dRegs.html#H8_002f300_002dRegs">H8/300-Regs</a>,
Up: <a rel="up" accesskey="u" href="H8_002f300-Syntax.html#H8_002f300-Syntax">H8/300 Syntax</a>
<hr>
</div>
<h5 class="subsubsection">9.10.2.3 Addressing Modes</h5>
<p><a name="index-addressing-modes_002c-H8_002f300-821"></a><a name="index-H8_002f300-addressing-modes-822"></a>as understands the following addressing modes for the H8/300:
<dl>
<dt><code>r</code><var>n</var><dd>Register direct
<br><dt><code>@r</code><var>n</var><dd>Register indirect
<br><dt><code>@(</code><var>d</var><code>, r</code><var>n</var><code>)</code><dt><code>@(</code><var>d</var><code>:16, r</code><var>n</var><code>)</code><dt><code>@(</code><var>d</var><code>:24, r</code><var>n</var><code>)</code><dd>Register indirect: 16-bit or 24-bit displacement <var>d</var> from register
<var>n</var>. (24-bit displacements are only meaningful on the H8/300H.)
<br><dt><code>@r</code><var>n</var><code>+</code><dd>Register indirect with post-increment
<br><dt><code>@-r</code><var>n</var><dd>Register indirect with pre-decrement
<br><dt><code>@</code><var>aa</var><dt><code>@</code><var>aa</var><code>:8</code><dt><code>@</code><var>aa</var><code>:16</code><dt><code>@</code><var>aa</var><code>:24</code><dd>Absolute address <code>aa</code>. (The address size ‘<samp><span class="samp">:24</span></samp>’ only makes
sense on the H8/300H.)
<br><dt><code>#</code><var>xx</var><dt><code>#</code><var>xx</var><code>:8</code><dt><code>#</code><var>xx</var><code>:16</code><dt><code>#</code><var>xx</var><code>:32</code><dd>Immediate data <var>xx</var>. You may specify the ‘<samp><span class="samp">:8</span></samp>’, ‘<samp><span class="samp">:16</span></samp>’, or
‘<samp><span class="samp">:32</span></samp>’ for clarity, if you wish; but <code>as</code> neither
requires this nor uses it—the data size required is taken from
context.
<br><dt><code>@@</code><var>aa</var><dt><code>@@</code><var>aa</var><code>:8</code><dd>Memory indirect. You may specify the ‘<samp><span class="samp">:8</span></samp>’ for clarity, if you
wish; but <code>as</code> neither requires this nor uses it.
</dl>
</body></html>
| lgpl-2.1 |
risesecurity/unixasm | osx-x86-cntsockcode.c | 3185 | /*
* osx-x86-cntsockcode.c
* Copyright 2006 Ramon de Carvalho Valle <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define CNTSOCKADDR 1
#define CNTSOCKPORT 8
char cntsockcode[]= /* 65 bytes */
"\x68\x7f\x00\x00\x01" /* pushl $0x0100007f */
"\x68\xff\x02\x04\xd2" /* pushl $0xd20402ff */
"\x89\xe7" /* movl %esp,%edi */
"\x31\xc0" /* xorl %eax,%eax */
"\x50" /* pushl %eax */
"\x6a\x01" /* pushl $0x01 */
"\x6a\x02" /* pushl $0x02 */
"\x6a\x10" /* pushl $0x10 */
"\xb0\x61" /* movb $0x61,%al */
"\xcd\x80" /* int $0x80 */
"\x57" /* pushl %edi */
"\x50" /* pushl %eax */
"\x50" /* pushl %eax */
"\x6a\x62" /* pushl $0x62 */
"\x58" /* popl %eax */
"\xcd\x80" /* int $0x80 */
"\x50" /* pushl %eax */
"\x6a\x5a" /* pushl $0x5a */
"\x58" /* popl %eax */
"\xcd\x80" /* int $0x80 */
"\xff\x4f\xe8" /* decl -0x18(%edi) */
"\x79\xf6" /* jns <cntsockcode+34> */
"\x68\x2f\x2f\x73\x68" /* pushl $0x68732f2f */
"\x68\x2f\x62\x69\x6e" /* pushl $0x6e69622f */
"\x89\xe3" /* movl %esp,%ebx */
"\x50" /* pushl %eax */
"\x54" /* pushl %esp */
"\x54" /* pushl %esp */
"\x53" /* pushl %ebx */
"\x50" /* pushl %eax */
"\xb0\x3b" /* movb $0x3b,%al */
"\xcd\x80" /* int $0x80 */
;
| lgpl-2.1 |
RLovelett/qt | tools/linguist/shared/qscript.cpp | 84936 | // This file was generated by qlalr - DO NOT EDIT!
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
class QScriptGrammar
{
public:
enum {
EOF_SYMBOL = 0,
T_AND = 1,
T_AND_AND = 2,
T_AND_EQ = 3,
T_AUTOMATIC_SEMICOLON = 62,
T_BREAK = 4,
T_CASE = 5,
T_CATCH = 6,
T_COLON = 7,
T_COMMA = 8,
T_CONST = 81,
T_CONTINUE = 9,
T_DEBUGGER = 82,
T_DEFAULT = 10,
T_DELETE = 11,
T_DIVIDE_ = 12,
T_DIVIDE_EQ = 13,
T_DO = 14,
T_DOT = 15,
T_ELSE = 16,
T_EQ = 17,
T_EQ_EQ = 18,
T_EQ_EQ_EQ = 19,
T_FALSE = 80,
T_FINALLY = 20,
T_FOR = 21,
T_FUNCTION = 22,
T_GE = 23,
T_GT = 24,
T_GT_GT = 25,
T_GT_GT_EQ = 26,
T_GT_GT_GT = 27,
T_GT_GT_GT_EQ = 28,
T_IDENTIFIER = 29,
T_IF = 30,
T_IN = 31,
T_INSTANCEOF = 32,
T_LBRACE = 33,
T_LBRACKET = 34,
T_LE = 35,
T_LPAREN = 36,
T_LT = 37,
T_LT_LT = 38,
T_LT_LT_EQ = 39,
T_MINUS = 40,
T_MINUS_EQ = 41,
T_MINUS_MINUS = 42,
T_NEW = 43,
T_NOT = 44,
T_NOT_EQ = 45,
T_NOT_EQ_EQ = 46,
T_NULL = 78,
T_NUMERIC_LITERAL = 47,
T_OR = 48,
T_OR_EQ = 49,
T_OR_OR = 50,
T_PLUS = 51,
T_PLUS_EQ = 52,
T_PLUS_PLUS = 53,
T_QUESTION = 54,
T_RBRACE = 55,
T_RBRACKET = 56,
T_REMAINDER = 57,
T_REMAINDER_EQ = 58,
T_RESERVED_WORD = 83,
T_RETURN = 59,
T_RPAREN = 60,
T_SEMICOLON = 61,
T_STAR = 63,
T_STAR_EQ = 64,
T_STRING_LITERAL = 65,
T_SWITCH = 66,
T_THIS = 67,
T_THROW = 68,
T_TILDE = 69,
T_TRUE = 79,
T_TRY = 70,
T_TYPEOF = 71,
T_VAR = 72,
T_VOID = 73,
T_WHILE = 74,
T_WITH = 75,
T_XOR = 76,
T_XOR_EQ = 77,
ACCEPT_STATE = 236,
RULE_COUNT = 267,
STATE_COUNT = 465,
TERMINAL_COUNT = 84,
NON_TERMINAL_COUNT = 88,
GOTO_INDEX_OFFSET = 465,
GOTO_INFO_OFFSET = 1374,
GOTO_CHECK_OFFSET = 1374
};
static const char *const spell [];
static const int lhs [];
static const int rhs [];
static const int goto_default [];
static const int action_default [];
static const int action_index [];
static const int action_info [];
static const int action_check [];
static inline int nt_action (int state, int nt)
{
const int *const goto_index = &action_index [GOTO_INDEX_OFFSET];
const int *const goto_check = &action_check [GOTO_CHECK_OFFSET];
const int yyn = goto_index [state] + nt;
if (yyn < 0 || goto_check [yyn] != nt)
return goto_default [nt];
const int *const goto_info = &action_info [GOTO_INFO_OFFSET];
return goto_info [yyn];
}
static inline int t_action (int state, int token)
{
const int yyn = action_index [state] + token;
if (yyn < 0 || action_check [yyn] != token)
return - action_default [state];
return action_info [yyn];
}
};
const char *const QScriptGrammar::spell [] = {
"end of file", "&", "&&", "&=", "break", "case", "catch", ":", ";", "continue",
"default", "delete", "/", "/=", "do", ".", "else", "=", "==", "===",
"finally", "for", "function", ">=", ">", ">>", ">>=", ">>>", ">>>=", "identifier",
"if", "in", "instanceof", "{", "[", "<=", "(", "<", "<<", "<<=",
"-", "-=", "--", "new", "!", "!=", "!==", "numeric literal", "|", "|=",
"||", "+", "+=", "++", "?", "}", "]", "%", "%=", "return",
")", ";", 0, "*", "*=", "string literal", "switch", "this", "throw", "~",
"try", "typeof", "var", "void", "while", "with", "^", "^=", "null", "true",
"false", "const", "debugger", "reserved word"};
const int QScriptGrammar::lhs [] = {
85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
85, 85, 85, 85, 87, 87, 91, 91, 86, 86,
92, 92, 93, 93, 93, 93, 94, 94, 94, 94,
94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
94, 94, 94, 94, 94, 94, 94, 95, 95, 96,
96, 96, 96, 96, 99, 99, 100, 100, 100, 100,
98, 98, 101, 101, 102, 102, 103, 103, 103, 104,
104, 104, 104, 104, 104, 104, 104, 104, 104, 105,
105, 105, 105, 106, 106, 106, 107, 107, 107, 107,
108, 108, 108, 108, 108, 108, 108, 109, 109, 109,
109, 109, 109, 110, 110, 110, 110, 110, 111, 111,
111, 111, 111, 112, 112, 113, 113, 114, 114, 115,
115, 116, 116, 117, 117, 118, 118, 119, 119, 120,
120, 121, 121, 122, 122, 123, 123, 90, 90, 124,
124, 125, 125, 125, 125, 125, 125, 125, 125, 125,
125, 125, 125, 89, 89, 126, 126, 127, 127, 128,
128, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 130, 146, 146, 145,
145, 131, 131, 147, 147, 148, 148, 150, 150, 149,
151, 154, 152, 152, 155, 153, 153, 132, 133, 133,
134, 134, 135, 135, 135, 135, 135, 135, 135, 136,
136, 136, 136, 137, 137, 137, 137, 138, 138, 139,
141, 156, 156, 159, 159, 157, 157, 160, 158, 140,
142, 142, 143, 143, 143, 161, 162, 144, 163, 97,
167, 167, 164, 164, 165, 165, 168, 84, 169, 169,
170, 170, 166, 166, 88, 88, 171};
const int QScriptGrammar:: rhs[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 3,
3, 5, 3, 3, 2, 4, 1, 2, 0, 1,
3, 5, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 4, 3, 3, 1, 2, 2, 2, 4, 3,
2, 3, 1, 3, 1, 1, 1, 2, 2, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
3, 3, 3, 1, 3, 3, 1, 3, 3, 3,
1, 3, 3, 3, 3, 3, 3, 1, 3, 3,
3, 3, 3, 1, 3, 3, 3, 3, 1, 3,
3, 3, 3, 1, 3, 1, 3, 1, 3, 1,
3, 1, 3, 1, 3, 1, 3, 1, 3, 1,
3, 1, 3, 1, 5, 1, 5, 1, 3, 1,
3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 0, 1, 1, 3, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 3, 1, 2, 0,
1, 3, 3, 1, 1, 1, 3, 1, 3, 2,
2, 2, 0, 1, 2, 0, 1, 1, 2, 2,
7, 5, 7, 7, 5, 9, 10, 7, 8, 2,
2, 3, 3, 2, 2, 3, 3, 3, 3, 5,
5, 3, 5, 1, 2, 0, 1, 4, 3, 3,
3, 3, 3, 3, 4, 5, 2, 1, 8, 8,
1, 3, 0, 1, 0, 1, 1, 1, 1, 2,
1, 1, 0, 1, 0, 1, 2};
const int QScriptGrammar::action_default [] = {
0, 97, 164, 128, 136, 132, 172, 179, 76, 148,
178, 186, 174, 124, 0, 175, 262, 61, 176, 177,
182, 77, 140, 144, 65, 94, 75, 80, 60, 0,
114, 180, 101, 259, 258, 261, 183, 0, 194, 0,
248, 0, 8, 9, 0, 5, 0, 263, 2, 0,
265, 19, 0, 0, 0, 0, 0, 3, 6, 0,
0, 166, 208, 7, 0, 1, 0, 0, 4, 0,
0, 195, 0, 0, 0, 184, 185, 90, 0, 173,
181, 0, 0, 77, 96, 263, 2, 265, 79, 78,
0, 0, 0, 92, 93, 91, 0, 264, 253, 254,
0, 251, 0, 252, 0, 255, 256, 0, 257, 250,
260, 0, 266, 0, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 23,
41, 42, 43, 44, 45, 25, 46, 47, 24, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 0,
21, 0, 0, 0, 22, 13, 95, 0, 125, 0,
0, 0, 0, 115, 0, 0, 0, 0, 0, 0,
105, 0, 0, 0, 99, 100, 98, 103, 107, 106,
104, 102, 117, 116, 118, 0, 133, 0, 129, 68,
0, 0, 0, 70, 59, 58, 0, 0, 69, 165,
0, 73, 71, 0, 72, 74, 209, 210, 0, 161,
154, 152, 159, 160, 158, 157, 163, 156, 155, 153,
162, 149, 0, 137, 0, 0, 141, 0, 0, 145,
67, 0, 0, 63, 0, 62, 267, 224, 0, 225,
226, 227, 220, 0, 221, 222, 223, 81, 0, 0,
0, 0, 0, 213, 214, 170, 168, 130, 138, 134,
150, 126, 171, 0, 77, 142, 146, 119, 108, 0,
0, 127, 0, 0, 0, 0, 120, 0, 0, 0,
0, 0, 112, 110, 113, 111, 109, 122, 121, 123,
0, 135, 0, 131, 0, 169, 77, 0, 151, 166,
167, 0, 166, 0, 0, 216, 0, 0, 0, 218,
0, 139, 0, 0, 143, 0, 0, 147, 206, 0,
198, 207, 201, 0, 205, 0, 166, 199, 0, 166,
0, 0, 217, 0, 0, 0, 219, 264, 253, 0,
0, 255, 0, 249, 0, 240, 0, 0, 0, 212,
0, 211, 188, 191, 0, 27, 30, 31, 248, 34,
35, 5, 39, 40, 2, 41, 44, 3, 6, 166,
7, 48, 1, 50, 4, 52, 53, 54, 55, 56,
57, 189, 187, 65, 66, 64, 0, 228, 229, 0,
0, 0, 231, 236, 234, 237, 0, 0, 235, 236,
0, 232, 0, 233, 190, 239, 0, 190, 238, 0,
241, 242, 0, 190, 243, 244, 0, 0, 245, 0,
0, 0, 246, 247, 83, 82, 0, 0, 0, 215,
0, 0, 0, 230, 0, 20, 0, 17, 19, 11,
0, 16, 12, 18, 15, 10, 0, 14, 87, 85,
89, 86, 84, 88, 203, 196, 0, 204, 200, 0,
202, 192, 0, 193, 197};
const int QScriptGrammar::goto_default [] = {
29, 28, 436, 434, 113, 14, 2, 435, 112, 111,
114, 193, 24, 17, 189, 26, 8, 200, 21, 27,
77, 25, 1, 32, 30, 267, 13, 261, 3, 257,
5, 259, 4, 258, 22, 265, 23, 266, 9, 260,
256, 297, 386, 262, 263, 35, 6, 79, 12, 15,
18, 19, 10, 7, 31, 80, 20, 36, 75, 76,
11, 354, 353, 78, 456, 455, 319, 320, 458, 322,
457, 321, 392, 396, 399, 395, 394, 414, 415, 16,
100, 107, 96, 99, 106, 108, 33, 0};
const int QScriptGrammar::action_index [] = {
1210, 59, -84, 71, 41, -1, -84, -84, 148, -84,
-84, -84, -84, 201, 130, -84, -84, -84, -84, -84,
-84, 343, 67, 62, 122, 109, -84, -84, -84, 85,
273, -84, 184, -84, 1210, -84, -84, 119, -84, 112,
-84, 521, -84, -84, 1130, -84, 45, 54, 58, 38,
1290, 50, 521, 521, 521, 376, 521, -84, -84, 521,
521, 521, -84, -84, 25, -84, 521, 521, -84, 43,
521, -84, 521, 18, 15, -84, -84, -84, 24, -84,
-84, 521, 521, 64, 153, 27, -84, 1050, -84, -84,
521, 521, 521, -84, -84, -84, 28, -84, 37, 55,
19, -84, 33, -84, 34, 1210, -84, 16, 1210, -84,
-84, 39, 52, -3, -84, -84, -84, -84, -84, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, 521,
-84, 1050, 125, 521, -84, -84, 155, 521, 189, 521,
521, 521, 521, 248, 521, 521, 521, 521, 521, 521,
243, 521, 521, 521, 75, 82, 94, 177, 184, 184,
184, 184, 263, 283, 298, 521, 44, 521, 77, -84,
970, 521, 817, -84, -84, -84, 95, 521, -84, -84,
93, -84, -84, 521, -84, -84, -84, -84, 521, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, -84,
-84, -84, 521, 41, 521, 521, 68, 66, 521, -84,
-84, 970, 521, -84, 103, -84, -84, -84, 63, -84,
-84, -84, -84, 69, -84, -84, -84, -84, -27, 12,
521, 92, 100, -84, -84, 890, -84, 31, -13, -45,
-84, 210, 32, -28, 387, 20, 73, 304, 117, -5,
521, 212, 521, 521, 521, 521, 213, 521, 521, 521,
521, 521, 151, 150, 176, 158, 168, 304, 304, 228,
521, -72, 521, 4, 521, -84, 306, 521, -84, 521,
8, -50, 521, -48, 1130, -84, 521, 80, 1130, -84,
521, -33, 521, 521, 5, 48, 521, -84, 17, 88,
11, -84, -84, 521, -84, -29, 521, -84, -41, 521,
-39, 1130, -84, 521, 87, 1130, -84, -8, -2, -35,
10, 1210, -16, -84, 1130, -84, 521, 86, 1130, -14,
1130, -84, -84, 1130, -36, 107, -21, 165, 3, 521,
1130, 6, 14, 61, 7, -19, 448, -4, -6, 671,
29, 13, 23, 521, 30, -10, 521, 9, 521, -30,
-18, -84, -84, 164, -84, -84, 46, -84, -84, 521,
111, -24, -84, 36, -84, 40, 99, 521, -84, 21,
22, -84, -11, -84, 1130, -84, 106, 1130, -84, 178,
-84, -84, 98, 1130, 57, -84, 56, 60, -84, 51,
26, 35, -84, -84, -84, -84, 521, 97, 1130, -84,
521, 90, 1130, -84, 79, 76, 744, -84, 49, -84,
594, -84, -84, -84, -84, -84, 83, -84, -84, -84,
-84, -84, -84, -84, 42, -84, 162, -84, -84, 521,
-84, -84, 53, -84, -84,
-61, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -4, -88, -88, 22, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -51, -88, -88, -88, -88, -88,
-88, 105, -88, -88, -12, -88, -88, -88, -88, -88,
-7, -88, 35, 132, 62, 154, 79, -88, -88, 100,
75, 36, -88, -88, -88, -88, 37, 70, -88, -1,
86, -88, 92, -88, -88, -88, -88, -88, -88, -88,
-88, 90, 95, -88, -88, -88, -88, -88, -88, -88,
87, 82, 74, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -47, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, 28,
-88, 20, -88, 19, -88, -88, -88, 39, -88, 42,
43, 106, 61, -88, 63, 55, 52, 53, 91, 125,
-88, 120, 123, 118, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, 116, -88, 59, -88, -88,
16, 18, 15, -88, -88, -88, -88, 21, -88, -88,
-88, -88, -88, 24, -88, -88, -88, -88, 38, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, 97, -88, 115, 25, -88, -88, 26, -88,
-88, 111, 14, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
23, -88, -88, -88, -88, 108, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
160, -88, 171, 163, 145, 179, -88, 135, 45, 41,
66, 80, -88, -88, -88, -88, -88, -88, -88, -88,
172, -88, 156, -88, 142, -88, -88, 144, -88, 122,
-88, -88, 114, -88, -23, -88, 48, -88, 29, -88,
224, -88, 157, 175, -88, -88, 182, -88, -88, -88,
-88, -88, -88, 183, -88, -21, 134, -88, -88, 49,
-88, 3, -88, 44, -88, 2, -88, -88, -37, -88,
-88, -31, -88, -88, 10, -88, 47, -88, 17, -88,
27, -88, -88, 13, -88, -88, -88, -88, -88, 117,
6, -88, -88, -88, -88, -88, 154, -88, -88, 1,
-88, -88, -88, 7, -88, -35, 137, -88, 141, -88,
-88, -88, -88, -6, -88, -88, -88, -88, -88, 78,
-88, -88, -88, -88, -88, -69, -88, 11, -88, -59,
-88, -88, -88, -88, 83, -88, -88, 56, -88, -88,
-88, -88, -88, -40, -58, -88, -88, -29, -88, -88,
-88, -45, -88, -88, -88, -88, -3, -88, -42, -88,
-5, -88, -32, -88, -88, -88, 9, -88, 8, -88,
-2, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, 12,
-88, -88, -56, -88, -88};
const int QScriptGrammar::action_info [] = {
318, -25, 350, -45, 292, 270, 426, 310, -194, 393,
-32, 302, 304, -37, 344, 290, 197, 346, 430, 382,
329, 331, 310, 413, 318, 340, 397, 101, 338, 404,
-49, 292, 270, 299, 323, 290, -24, -51, -195, 343,
294, 397, 333, 341, 403, 397, 149, 249, 250, 389,
255, 430, 155, 454, 426, 316, 97, 437, 437, 459,
151, 389, 103, 102, 98, 344, 101, 105, 413, 222,
222, 109, 157, 228, 346, 187, 413, 417, 157, 104,
420, 255, 454, 337, 443, 236, 421, 438, 197, 185,
97, 197, 419, 413, 197, 197, 325, -263, 197, 81,
197, 203, 0, 197, 416, 197, 88, 388, 387, 400,
82, 197, 224, 407, 197, 81, 225, 89, 417, 197,
187, 90, 81, 312, 241, 240, 82, 313, 0, 0,
246, 245, 153, 82, 81, 439, 238, 231, 197, 0,
308, 243, 171, 447, 172, 82, 348, 335, 238, 326,
432, 198, 252, 204, 401, 173, 232, 428, 192, 235,
0, 254, 253, 190, 0, 90, 91, 90, 239, 237,
462, 391, 92, 244, 242, 171, 171, 172, 172, 231,
239, 237, 191, 171, 192, 172, 197, 0, 173, 173,
0, 207, 206, 171, 243, 172, 173, 0, 232, 0,
192, 171, 171, 172, 172, 0, 173, 159, 160, 171,
91, 172, 91, 0, 173, 173, 92, 0, 92, 159,
160, 0, 173, 463, 461, 0, 244, 242, 272, 273,
272, 273, 0, 0, 161, 162, 277, 278, 0, 411,
410, 0, 0, 0, 0, 279, 161, 162, 280, 0,
281, 277, 278, 0, 0, 274, 275, 274, 275, 0,
279, 0, 0, 280, 0, 281, 0, 0, 171, 0,
172, 164, 165, 0, 0, 0, 0, 0, 0, 166,
167, 173, 0, 168, 0, 169, 164, 165, 0, 0,
0, 0, 0, 0, 166, 167, 164, 165, 168, 0,
169, 0, 0, 0, 166, 167, 164, 165, 168, 209,
169, 0, 0, 0, 166, 167, 0, 0, 168, 210,
169, 164, 165, 211, 0, 0, 0, 277, 278, 166,
167, 0, 212, 168, 213, 169, 279, 0, 0, 280,
0, 281, 0, 0, 0, 214, 209, 215, 88, 0,
0, 0, 0, 0, 0, 216, 210, 0, 217, 89,
211, 0, 0, 0, 218, 0, 0, 0, 0, 212,
219, 213, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 214, 220, 215, 88, 0, 0, 42, 43,
209, 0, 216, 0, 0, 217, 89, 0, 85, 0,
210, 218, 0, 0, 211, 86, 0, 219, 0, 87,
51, 0, 52, 212, 0, 213, 0, 0, 306, 55,
220, 0, 0, 58, 0, 0, 214, 0, 215, 88,
0, 0, 0, 0, 0, 0, 216, 0, 0, 217,
89, 63, 0, 65, 0, 218, 0, 0, 0, 0,
0, 219, 0, 0, 57, 68, 45, 0, 0, 0,
42, 43, 0, 0, 220, 0, 0, 0, 0, 0,
85, 0, 0, 0, 0, 0, 0, 86, 0, 0,
0, 87, 51, 0, 52, 0, 0, 0, 0, 0,
0, 55, 0, 0, 0, 58, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 63, 0, 65, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 57, 68, 45, 0,
0, 0, 41, 42, 43, 0, 0, 0, 0, 0,
0, 0, 0, 85, 0, 0, 0, 0, 0, 0,
86, 0, 0, 0, 87, 51, 0, 52, 0, 0,
0, 53, 0, 54, 55, 56, 0, 0, 58, 0,
0, 0, 59, 0, 60, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 63, 0, 65, 0,
67, 0, 70, 0, 72, 0, 0, 0, 0, 57,
68, 45, 0, 0, 0, 41, 42, 43, 0, 0,
0, 0, 0, 0, 0, 0, 85, 0, 0, 0,
0, 0, 0, 86, 0, 0, 0, 87, 51, 0,
52, 0, 0, 0, 53, 0, 54, 55, 56, 0,
0, 58, 0, 0, 0, 59, 0, 60, 0, 0,
442, 0, 0, 0, 0, 0, 0, 0, 0, 63,
0, 65, 0, 67, 0, 70, 0, 72, 0, 0,
0, 0, 57, 68, 45, 0, 0, 0, -47, 0,
0, 0, 41, 42, 43, 0, 0, 0, 0, 0,
0, 0, 0, 85, 0, 0, 0, 0, 0, 0,
86, 0, 0, 0, 87, 51, 0, 52, 0, 0,
0, 53, 0, 54, 55, 56, 0, 0, 58, 0,
0, 0, 59, 0, 60, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 63, 0, 65, 0,
67, 0, 70, 0, 72, 0, 0, 0, 0, 57,
68, 45, 0, 0, 0, 41, 42, 43, 0, 0,
0, 0, 0, 0, 0, 0, 85, 0, 0, 0,
0, 0, 0, 86, 0, 0, 0, 87, 51, 0,
52, 0, 0, 0, 53, 0, 54, 55, 56, 0,
0, 58, 0, 0, 0, 59, 0, 60, 0, 0,
445, 0, 0, 0, 0, 0, 0, 0, 0, 63,
0, 65, 0, 67, 0, 70, 0, 72, 0, 0,
0, 0, 57, 68, 45, 0, 0, 0, 41, 42,
43, 0, 0, 0, 0, 0, 0, 0, 0, 85,
0, 0, 0, 0, 0, 0, 86, 0, 0, 0,
87, 51, 0, 52, 0, 0, 0, 53, 0, 54,
55, 56, 0, 0, 58, 0, 0, 0, 59, 0,
60, 0, 0, 0, 0, 0, 0, 202, 0, 0,
0, 0, 63, 0, 65, 0, 67, 0, 70, 0,
72, 0, 0, 0, 0, 57, 68, 45, 0, 0,
0, 41, 42, 43, 0, 0, 0, 0, 0, 0,
0, 0, 85, 0, 0, 0, 0, 0, 0, 86,
0, 0, 0, 87, 51, 0, 52, 0, 0, 0,
53, 0, 54, 55, 56, 0, 0, 58, 0, 0,
0, 59, 0, 60, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 63, 0, 65, 0, 67,
0, 70, 269, 72, 0, 0, 0, 0, 57, 68,
45, 0, 0, 0, 115, 116, 117, 0, 0, 119,
121, 122, 0, 0, 123, 0, 124, 0, 0, 0,
126, 127, 128, 0, 0, 0, 0, 0, 0, 195,
130, 131, 132, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 133, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 137,
0, 0, 0, 0, 0, 0, 139, 140, 141, 0,
143, 144, 145, 146, 147, 148, 0, 0, 134, 142,
125, 118, 120, 136, 115, 116, 117, 0, 0, 119,
121, 122, 0, 0, 123, 0, 124, 0, 0, 0,
126, 127, 128, 0, 0, 0, 0, 0, 0, 129,
130, 131, 132, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 133, 0, 0, 0, 135, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 137,
0, 0, 0, 0, 0, 138, 139, 140, 141, 0,
143, 144, 145, 146, 147, 148, 0, 0, 134, 142,
125, 118, 120, 136, 37, 0, 0, 0, 0, 39,
0, 41, 42, 43, 44, 0, 0, 0, 0, 0,
0, 46, 85, 0, 0, 0, 0, 0, 0, 48,
49, 0, 0, 50, 51, 0, 52, 0, 0, 0,
53, 0, 54, 55, 56, 0, 0, 58, 0, 0,
0, 59, 0, 60, 0, 0, 0, 0, 0, 61,
0, 62, 0, 0, 0, 63, 64, 65, 66, 67,
69, 70, 71, 72, 73, 74, 0, 0, 57, 68,
45, 38, 40, 0, 37, 0, 0, 0, 0, 39,
0, 41, 42, 43, 44, 0, 0, 0, 0, 0,
0, 46, 47, 0, 0, 0, 0, 0, 0, 48,
49, 0, 0, 50, 51, 0, 52, 0, 0, 0,
53, 0, 54, 55, 56, 0, 0, 58, 0, 0,
0, 59, 0, 60, 0, 0, 0, 0, 0, 61,
0, 62, 0, 0, 0, 63, 64, 65, 66, 67,
69, 70, 71, 72, 73, 74, 0, 0, 57, 68,
45, 38, 40, 0, 355, 116, 117, 0, 0, 357,
121, 359, 42, 43, 360, 0, 124, 0, 0, 0,
126, 362, 363, 0, 0, 0, 0, 0, 0, 364,
365, 131, 132, 50, 51, 0, 52, 0, 0, 0,
53, 0, 54, 366, 56, 0, 0, 368, 0, 0,
0, 59, 0, 60, 0, -190, 0, 0, 0, 369,
0, 62, 0, 0, 0, 370, 371, 372, 373, 67,
375, 376, 377, 378, 379, 380, 0, 0, 367, 374,
361, 356, 358, 136,
431, 422, 427, 429, 441, 352, 300, 398, 385, 464,
440, 412, 409, 433, 402, 444, 406, 423, 460, 234,
418, 201, 305, 196, 34, 154, 194, 199, 251, 152,
205, 227, 229, 248, 150, 110, 230, 208, 352, 110,
446, 300, 409, 339, 221, 412, 327, 336, 332, 334,
342, 248, 347, 307, 300, 345, 0, 83, 381, 83,
83, 83, 349, 83, 284, 158, 163, 182, 283, 0,
83, 83, 351, 83, 309, 178, 179, 83, 177, 83,
83, 83, 449, 390, 83, 184, 170, 188, 83, 285,
453, 330, 83, 83, 95, 452, 0, 83, 83, 450,
83, 352, 94, 286, 83, 83, 424, 93, 83, 83,
83, 84, 425, 83, 180, 83, 156, 408, 83, 300,
451, 194, 233, 83, 83, 247, 264, 300, 352, 223,
183, 268, 0, 83, 83, 83, 83, 247, 83, 300,
176, 83, 174, 83, 405, 175, 186, 0, 181, 226,
83, 0, 448, 83, 0, 83, 303, 424, 282, 83,
296, 425, 296, 83, 301, 268, 383, 268, 268, 384,
288, 0, 0, 0, 83, 83, 328, 0, 83, 268,
268, 83, 295, 268, 298, 293, 268, 271, 287, 83,
83, 0, 314, 296, 268, 268, 276, 83, 268, 0,
296, 296, 268, 291, 289, 268, 268, 0, 0, 0,
0, 0, 0, 0, 0, 315, 0, 0, 0, 0,
0, 0, 317, 324, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 83, 0, 0, 0, 0, 268, 0, 0,
0, 0, 0, 0, 0, 0, 0, 311, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0};
const int QScriptGrammar::action_check [] = {
29, 7, 16, 7, 76, 1, 36, 2, 29, 33,
7, 61, 60, 7, 7, 48, 8, 36, 36, 55,
61, 60, 2, 33, 29, 60, 5, 29, 36, 7,
7, 76, 1, 61, 17, 48, 7, 7, 29, 55,
8, 5, 31, 33, 55, 5, 7, 74, 36, 36,
36, 36, 55, 29, 36, 7, 29, 8, 8, 17,
8, 36, 29, 8, 36, 7, 29, 33, 33, 2,
2, 55, 1, 7, 36, 76, 33, 20, 1, 60,
29, 36, 29, 29, 8, 0, 60, 8, 8, 48,
29, 8, 36, 33, 8, 8, 8, 36, 8, 40,
8, 8, -1, 8, 6, 8, 42, 61, 62, 10,
51, 8, 50, 7, 8, 40, 54, 53, 20, 8,
76, 12, 40, 50, 61, 62, 51, 54, -1, -1,
61, 62, 7, 51, 40, 56, 29, 15, 8, -1,
60, 29, 25, 60, 27, 51, 60, 60, 29, 61,
60, 56, 60, 60, 55, 38, 34, 60, 36, 56,
-1, 61, 62, 15, -1, 12, 57, 12, 61, 62,
8, 60, 63, 61, 62, 25, 25, 27, 27, 15,
61, 62, 34, 25, 36, 27, 8, -1, 38, 38,
-1, 61, 62, 25, 29, 27, 38, -1, 34, -1,
36, 25, 25, 27, 27, -1, 38, 18, 19, 25,
57, 27, 57, -1, 38, 38, 63, -1, 63, 18,
19, -1, 38, 61, 62, -1, 61, 62, 18, 19,
18, 19, -1, -1, 45, 46, 23, 24, -1, 61,
62, -1, -1, -1, -1, 32, 45, 46, 35, -1,
37, 23, 24, -1, -1, 45, 46, 45, 46, -1,
32, -1, -1, 35, -1, 37, -1, -1, 25, -1,
27, 23, 24, -1, -1, -1, -1, -1, -1, 31,
32, 38, -1, 35, -1, 37, 23, 24, -1, -1,
-1, -1, -1, -1, 31, 32, 23, 24, 35, -1,
37, -1, -1, -1, 31, 32, 23, 24, 35, 3,
37, -1, -1, -1, 31, 32, -1, -1, 35, 13,
37, 23, 24, 17, -1, -1, -1, 23, 24, 31,
32, -1, 26, 35, 28, 37, 32, -1, -1, 35,
-1, 37, -1, -1, -1, 39, 3, 41, 42, -1,
-1, -1, -1, -1, -1, 49, 13, -1, 52, 53,
17, -1, -1, -1, 58, -1, -1, -1, -1, 26,
64, 28, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 39, 77, 41, 42, -1, -1, 12, 13,
3, -1, 49, -1, -1, 52, 53, -1, 22, -1,
13, 58, -1, -1, 17, 29, -1, 64, -1, 33,
34, -1, 36, 26, -1, 28, -1, -1, 31, 43,
77, -1, -1, 47, -1, -1, 39, -1, 41, 42,
-1, -1, -1, -1, -1, -1, 49, -1, -1, 52,
53, 65, -1, 67, -1, 58, -1, -1, -1, -1,
-1, 64, -1, -1, 78, 79, 80, -1, -1, -1,
12, 13, -1, -1, 77, -1, -1, -1, -1, -1,
22, -1, -1, -1, -1, -1, -1, 29, -1, -1,
-1, 33, 34, -1, 36, -1, -1, -1, -1, -1,
-1, 43, -1, -1, -1, 47, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 65, -1, 67, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 78, 79, 80, -1,
-1, -1, 11, 12, 13, -1, -1, -1, -1, -1,
-1, -1, -1, 22, -1, -1, -1, -1, -1, -1,
29, -1, -1, -1, 33, 34, -1, 36, -1, -1,
-1, 40, -1, 42, 43, 44, -1, -1, 47, -1,
-1, -1, 51, -1, 53, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 65, -1, 67, -1,
69, -1, 71, -1, 73, -1, -1, -1, -1, 78,
79, 80, -1, -1, -1, 11, 12, 13, -1, -1,
-1, -1, -1, -1, -1, -1, 22, -1, -1, -1,
-1, -1, -1, 29, -1, -1, -1, 33, 34, -1,
36, -1, -1, -1, 40, -1, 42, 43, 44, -1,
-1, 47, -1, -1, -1, 51, -1, 53, -1, -1,
56, -1, -1, -1, -1, -1, -1, -1, -1, 65,
-1, 67, -1, 69, -1, 71, -1, 73, -1, -1,
-1, -1, 78, 79, 80, -1, -1, -1, 7, -1,
-1, -1, 11, 12, 13, -1, -1, -1, -1, -1,
-1, -1, -1, 22, -1, -1, -1, -1, -1, -1,
29, -1, -1, -1, 33, 34, -1, 36, -1, -1,
-1, 40, -1, 42, 43, 44, -1, -1, 47, -1,
-1, -1, 51, -1, 53, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 65, -1, 67, -1,
69, -1, 71, -1, 73, -1, -1, -1, -1, 78,
79, 80, -1, -1, -1, 11, 12, 13, -1, -1,
-1, -1, -1, -1, -1, -1, 22, -1, -1, -1,
-1, -1, -1, 29, -1, -1, -1, 33, 34, -1,
36, -1, -1, -1, 40, -1, 42, 43, 44, -1,
-1, 47, -1, -1, -1, 51, -1, 53, -1, -1,
56, -1, -1, -1, -1, -1, -1, -1, -1, 65,
-1, 67, -1, 69, -1, 71, -1, 73, -1, -1,
-1, -1, 78, 79, 80, -1, -1, -1, 11, 12,
13, -1, -1, -1, -1, -1, -1, -1, -1, 22,
-1, -1, -1, -1, -1, -1, 29, -1, -1, -1,
33, 34, -1, 36, -1, -1, -1, 40, -1, 42,
43, 44, -1, -1, 47, -1, -1, -1, 51, -1,
53, -1, -1, -1, -1, -1, -1, 60, -1, -1,
-1, -1, 65, -1, 67, -1, 69, -1, 71, -1,
73, -1, -1, -1, -1, 78, 79, 80, -1, -1,
-1, 11, 12, 13, -1, -1, -1, -1, -1, -1,
-1, -1, 22, -1, -1, -1, -1, -1, -1, 29,
-1, -1, -1, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 65, -1, 67, -1, 69,
-1, 71, 72, 73, -1, -1, -1, -1, 78, 79,
80, -1, -1, -1, 4, 5, 6, -1, -1, 9,
10, 11, -1, -1, 14, -1, 16, -1, -1, -1,
20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, 31, 32, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 43, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 59,
-1, -1, -1, -1, -1, -1, 66, 67, 68, -1,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, 83, 4, 5, 6, -1, -1, 9,
10, 11, -1, -1, 14, -1, 16, -1, -1, -1,
20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, 31, 32, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 43, -1, -1, -1, 47, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 59,
-1, -1, -1, -1, -1, 65, 66, 67, 68, -1,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, 83, 4, -1, -1, -1, -1, 9,
-1, 11, 12, 13, 14, -1, -1, -1, -1, -1,
-1, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, -1, -1, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, -1, -1, -1, -1, 59,
-1, 61, -1, -1, -1, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, -1, 4, -1, -1, -1, -1, 9,
-1, 11, 12, 13, 14, -1, -1, -1, -1, -1,
-1, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, -1, -1, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, -1, -1, -1, -1, 59,
-1, 61, -1, -1, -1, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, -1, 4, 5, 6, -1, -1, 9,
10, 11, 12, 13, 14, -1, 16, -1, -1, -1,
20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, 31, 32, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, 55, -1, -1, -1, 59,
-1, 61, -1, -1, -1, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, 83,
5, 46, 5, 45, 6, 45, 5, 76, 14, 65,
2, 46, 5, 45, 73, 6, 5, 46, 6, 5,
78, 6, 45, 5, 85, 6, 10, 6, 5, 9,
6, 6, 6, 45, 6, 86, 14, 41, 45, 86,
5, 5, 5, 80, 6, 46, 67, 45, 45, 5,
81, 45, 5, 5, 5, 45, -1, 18, 45, 18,
18, 18, 45, 18, 23, 26, 24, 24, 23, -1,
18, 18, 45, 18, 45, 23, 23, 18, 23, 18,
18, 18, 20, 5, 18, 24, 23, 28, 18, 23,
20, 42, 18, 18, 20, 20, -1, 18, 18, 20,
18, 45, 20, 23, 18, 18, 20, 20, 18, 18,
18, 21, 20, 18, 23, 18, 21, 61, 18, 5,
20, 10, 11, 18, 18, 20, 18, 5, 45, 32,
24, 23, -1, 18, 18, 18, 18, 20, 18, 5,
22, 18, 22, 18, 61, 22, 30, -1, 23, 34,
18, -1, 20, 18, -1, 18, 42, 20, 23, 18,
18, 20, 18, 18, 42, 23, 12, 23, 23, 15,
25, -1, -1, -1, 18, 18, 42, -1, 18, 23,
23, 18, 40, 23, 40, 29, 23, 27, 25, 18,
18, -1, 35, 18, 23, 23, 25, 18, 23, -1,
18, 18, 23, 31, 25, 23, 23, -1, -1, -1,
-1, -1, -1, -1, -1, 40, -1, -1, -1, -1,
-1, -1, 40, 40, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 18, -1, -1, -1, -1, 23, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 33, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1};
#define Q_SCRIPT_REGEXPLITERAL_RULE1 7
#define Q_SCRIPT_REGEXPLITERAL_RULE2 8
#include "translator.h"
#include <QtCore/qdebug.h>
#include <QtCore/qnumeric.h>
#include <QtCore/qstring.h>
#include <QtCore/qtextcodec.h>
#include <QtCore/qvariant.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
QT_BEGIN_NAMESPACE
static void recordMessage(
Translator *tor, const QString &context, const QString &text, const QString &comment,
const QString &extracomment, bool plural, const QString &fileName, int lineNo)
{
TranslatorMessage msg(
context, text, comment, QString(),
fileName, lineNo, QStringList(),
TranslatorMessage::Unfinished, plural);
msg.setExtraComment(extracomment.simplified());
tor->replace(msg);
}
namespace QScript
{
class Lexer
{
public:
Lexer();
~Lexer();
void setCode(const QString &c, int lineno);
int lex();
int currentLineNo() const { return yylineno; }
int currentColumnNo() const { return yycolumn; }
int startLineNo() const { return startlineno; }
int startColumnNo() const { return startcolumn; }
int endLineNo() const { return currentLineNo(); }
int endColumnNo() const
{ int col = currentColumnNo(); return (col > 0) ? col - 1 : col; }
bool prevTerminator() const { return terminator; }
enum State { Start,
Identifier,
InIdentifier,
InSingleLineComment,
InMultiLineComment,
InNum,
InNum0,
InHex,
InOctal,
InDecimal,
InExponentIndicator,
InExponent,
Hex,
Octal,
Number,
String,
Eof,
InString,
InEscapeSequence,
InHexEscape,
InUnicodeEscape,
Other,
Bad };
enum Error {
NoError,
IllegalCharacter,
UnclosedStringLiteral,
IllegalEscapeSequence,
IllegalUnicodeEscapeSequence,
UnclosedComment,
IllegalExponentIndicator,
IllegalIdentifier
};
enum ParenthesesState {
IgnoreParentheses,
CountParentheses,
BalancedParentheses
};
enum RegExpBodyPrefix {
NoPrefix,
EqualPrefix
};
bool scanRegExp(RegExpBodyPrefix prefix = NoPrefix);
QString pattern;
int flags;
State lexerState() const
{ return state; }
QString errorMessage() const
{ return errmsg; }
void setErrorMessage(const QString &err)
{ errmsg = err; }
void setErrorMessage(const char *err)
{ setErrorMessage(QString::fromLatin1(err)); }
Error error() const
{ return err; }
void clearError()
{ err = NoError; }
private:
int yylineno;
bool done;
char *buffer8;
QChar *buffer16;
uint size8, size16;
uint pos8, pos16;
bool terminator;
bool restrKeyword;
// encountered delimiter like "'" and "}" on last run
bool delimited;
int stackToken;
State state;
void setDone(State s);
uint pos;
void shift(uint p);
int lookupKeyword(const char *);
bool isWhiteSpace() const;
bool isLineTerminator() const;
bool isHexDigit(ushort c) const;
bool isOctalDigit(ushort c) const;
int matchPunctuator(ushort c1, ushort c2,
ushort c3, ushort c4);
ushort singleEscape(ushort c) const;
ushort convertOctal(ushort c1, ushort c2,
ushort c3) const;
public:
static unsigned char convertHex(ushort c1);
static unsigned char convertHex(ushort c1, ushort c2);
static QChar convertUnicode(ushort c1, ushort c2,
ushort c3, ushort c4);
static bool isIdentLetter(ushort c);
static bool isDecimalDigit(ushort c);
inline int ival() const { return qsyylval.toInt(); }
inline double dval() const { return qsyylval.toDouble(); }
inline QString ustr() const { return qsyylval.toString(); }
inline QVariant val() const { return qsyylval; }
const QChar *characterBuffer() const { return buffer16; }
int characterCount() const { return pos16; }
private:
void record8(ushort c);
void record16(QChar c);
void recordStartPos();
int findReservedWord(const QChar *buffer, int size) const;
void syncProhibitAutomaticSemicolon();
const QChar *code;
uint length;
int yycolumn;
int startlineno;
int startcolumn;
int bol; // begin of line
QVariant qsyylval;
// current and following unicode characters
ushort current, next1, next2, next3;
struct keyword {
const char *name;
int token;
};
QString errmsg;
Error err;
bool wantRx;
bool check_reserved;
ParenthesesState parenthesesState;
int parenthesesCount;
bool prohibitAutomaticSemicolon;
};
} // namespace QScript
extern double qstrtod(const char *s00, char const **se, bool *ok);
#define shiftWindowsLineBreak() if(current == '\r' && next1 == '\n') shift(1);
namespace QScript {
static int toDigit(char c)
{
if ((c >= '0') && (c <= '9'))
return c - '0';
else if ((c >= 'a') && (c <= 'z'))
return 10 + c - 'a';
else if ((c >= 'A') && (c <= 'Z'))
return 10 + c - 'A';
return -1;
}
double integerFromString(const char *buf, int size, int radix)
{
if (size == 0)
return qSNaN();
double sign = 1.0;
int i = 0;
if (buf[0] == '+') {
++i;
} else if (buf[0] == '-') {
sign = -1.0;
++i;
}
if (((size-i) >= 2) && (buf[i] == '0')) {
if (((buf[i+1] == 'x') || (buf[i+1] == 'X'))
&& (radix < 34)) {
if ((radix != 0) && (radix != 16))
return 0;
radix = 16;
i += 2;
} else {
if (radix == 0) {
radix = 8;
++i;
}
}
} else if (radix == 0) {
radix = 10;
}
int j = i;
for ( ; i < size; ++i) {
int d = toDigit(buf[i]);
if ((d == -1) || (d >= radix))
break;
}
double result;
if (j == i) {
if (!qstrcmp(buf, "Infinity"))
result = qInf();
else
result = qSNaN();
} else {
result = 0;
double multiplier = 1;
for (--i ; i >= j; --i, multiplier *= radix)
result += toDigit(buf[i]) * multiplier;
}
result *= sign;
return result;
}
} // namespace QScript
QScript::Lexer::Lexer()
:
yylineno(0),
size8(128), size16(128), restrKeyword(false),
stackToken(-1), pos(0),
code(0), length(0),
bol(true),
current(0), next1(0), next2(0), next3(0),
err(NoError),
check_reserved(true),
parenthesesState(IgnoreParentheses),
prohibitAutomaticSemicolon(false)
{
// allocate space for read buffers
buffer8 = new char[size8];
buffer16 = new QChar[size16];
flags = 0;
}
QScript::Lexer::~Lexer()
{
delete [] buffer8;
delete [] buffer16;
}
void QScript::Lexer::setCode(const QString &c, int lineno)
{
errmsg = QString();
yylineno = lineno;
yycolumn = 1;
restrKeyword = false;
delimited = false;
stackToken = -1;
pos = 0;
code = c.unicode();
length = c.length();
bol = true;
// read first characters
current = (length > 0) ? code[0].unicode() : 0;
next1 = (length > 1) ? code[1].unicode() : 0;
next2 = (length > 2) ? code[2].unicode() : 0;
next3 = (length > 3) ? code[3].unicode() : 0;
}
void QScript::Lexer::shift(uint p)
{
while (p--) {
++pos;
++yycolumn;
current = next1;
next1 = next2;
next2 = next3;
next3 = (pos + 3 < length) ? code[pos+3].unicode() : 0;
}
}
void QScript::Lexer::setDone(State s)
{
state = s;
done = true;
}
int QScript::Lexer::findReservedWord(const QChar *c, int size) const
{
switch (size) {
case 2: {
if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o'))
return QScriptGrammar::T_DO;
else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('f'))
return QScriptGrammar::T_IF;
else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n'))
return QScriptGrammar::T_IN;
} break;
case 3: {
if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('o') && c[2] == QLatin1Char('r'))
return QScriptGrammar::T_FOR;
else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('e') && c[2] == QLatin1Char('w'))
return QScriptGrammar::T_NEW;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') && c[2] == QLatin1Char('y'))
return QScriptGrammar::T_TRY;
else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('a') && c[2] == QLatin1Char('r'))
return QScriptGrammar::T_VAR;
else if (check_reserved) {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') && c[2] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 4: {
if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_CASE;
else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('l')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_ELSE;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('s'))
return QScriptGrammar::T_THIS;
else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('d'))
return QScriptGrammar::T_VOID;
else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('i')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('h'))
return QScriptGrammar::T_WITH;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('u') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_TRUE;
else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('l'))
return QScriptGrammar::T_NULL;
else if (check_reserved) {
if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('n')
&& c[2] == QLatin1Char('u') && c[3] == QLatin1Char('m'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('y')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('l') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('g'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('r'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('g') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('o'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 5: {
if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('e') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('k'))
return QScriptGrammar::T_BREAK;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('c')
&& c[4] == QLatin1Char('h'))
return QScriptGrammar::T_CATCH;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('w'))
return QScriptGrammar::T_THROW;
else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('e'))
return QScriptGrammar::T_WHILE;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('s')
&& c[4] == QLatin1Char('t'))
return QScriptGrammar::T_CONST;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('s')
&& c[4] == QLatin1Char('e'))
return QScriptGrammar::T_FALSE;
else if (check_reserved) {
if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('r')
&& c[4] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('r'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('l'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('l')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('s')
&& c[4] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('l')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 6: {
if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('t') && c[5] == QLatin1Char('e'))
return QScriptGrammar::T_DELETE;
else if (c[0] == QLatin1Char('r') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('u')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('n'))
return QScriptGrammar::T_RETURN;
else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('w')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('c') && c[5] == QLatin1Char('h'))
return QScriptGrammar::T_SWITCH;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('y')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('o') && c[5] == QLatin1Char('f'))
return QScriptGrammar::T_TYPEOF;
else if (check_reserved) {
if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('t')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('u') && c[3] == QLatin1Char('b')
&& c[4] == QLatin1Char('l') && c[5] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('b') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('i')
&& c[4] == QLatin1Char('v') && c[5] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('w') && c[5] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 7: {
if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('f') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('u') && c[5] == QLatin1Char('l')
&& c[6] == QLatin1Char('t'))
return QScriptGrammar::T_DEFAULT;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('l') && c[5] == QLatin1Char('l')
&& c[6] == QLatin1Char('y'))
return QScriptGrammar::T_FINALLY;
else if (check_reserved) {
if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('e') && c[5] == QLatin1Char('a')
&& c[6] == QLatin1Char('n'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('n') && c[5] == QLatin1Char('d')
&& c[6] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('c') && c[3] == QLatin1Char('k')
&& c[4] == QLatin1Char('a') && c[5] == QLatin1Char('g')
&& c[6] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('v')
&& c[4] == QLatin1Char('a') && c[5] == QLatin1Char('t')
&& c[6] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 8: {
if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('i') && c[5] == QLatin1Char('n')
&& c[6] == QLatin1Char('u') && c[7] == QLatin1Char('e'))
return QScriptGrammar::T_CONTINUE;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c')
&& c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i')
&& c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n'))
return QScriptGrammar::T_FUNCTION;
else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('b') && c[3] == QLatin1Char('u')
&& c[4] == QLatin1Char('g') && c[5] == QLatin1Char('g')
&& c[6] == QLatin1Char('e') && c[7] == QLatin1Char('r'))
return QScriptGrammar::T_DEBUGGER;
else if (check_reserved) {
if (c[0] == QLatin1Char('a') && c[1] == QLatin1Char('b')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('a')
&& c[6] == QLatin1Char('c') && c[7] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i')
&& c[6] == QLatin1Char('l') && c[7] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 9: {
if (check_reserved) {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('f')
&& c[6] == QLatin1Char('a') && c[7] == QLatin1Char('c')
&& c[8] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('n')
&& c[4] == QLatin1Char('s') && c[5] == QLatin1Char('i')
&& c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n')
&& c[8] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('e') && c[5] == QLatin1Char('c')
&& c[6] == QLatin1Char('t') && c[7] == QLatin1Char('e')
&& c[8] == QLatin1Char('d'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 10: {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('a') && c[5] == QLatin1Char('n')
&& c[6] == QLatin1Char('c') && c[7] == QLatin1Char('e')
&& c[8] == QLatin1Char('o') && c[9] == QLatin1Char('f'))
return QScriptGrammar::T_INSTANCEOF;
else if (check_reserved) {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('e') && c[5] == QLatin1Char('m')
&& c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n')
&& c[8] == QLatin1Char('t') && c[9] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 12: {
if (check_reserved) {
if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('y')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c')
&& c[4] == QLatin1Char('h') && c[5] == QLatin1Char('r')
&& c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n')
&& c[8] == QLatin1Char('i') && c[9] == QLatin1Char('z')
&& c[10] == QLatin1Char('e') && c[11] == QLatin1Char('d'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
} // switch
return -1;
}
int QScript::Lexer::lex()
{
int token = 0;
state = Start;
ushort stringType = 0; // either single or double quotes
pos8 = pos16 = 0;
done = false;
terminator = false;
// did we push a token on the stack previously ?
// (after an automatic semicolon insertion)
if (stackToken >= 0) {
setDone(Other);
token = stackToken;
stackToken = -1;
}
while (!done) {
switch (state) {
case Start:
if (isWhiteSpace()) {
// do nothing
} else if (current == '/' && next1 == '/') {
recordStartPos();
shift(1);
state = InSingleLineComment;
} else if (current == '/' && next1 == '*') {
recordStartPos();
shift(1);
state = InMultiLineComment;
} else if (current == 0) {
syncProhibitAutomaticSemicolon();
if (!terminator && !delimited && !prohibitAutomaticSemicolon) {
// automatic semicolon insertion if program incomplete
token = QScriptGrammar::T_SEMICOLON;
stackToken = 0;
setDone(Other);
} else {
setDone(Eof);
}
} else if (isLineTerminator()) {
shiftWindowsLineBreak();
yylineno++;
yycolumn = 0;
bol = true;
terminator = true;
syncProhibitAutomaticSemicolon();
if (restrKeyword) {
token = QScriptGrammar::T_SEMICOLON;
setDone(Other);
}
} else if (current == '"' || current == '\'') {
recordStartPos();
state = InString;
stringType = current;
} else if (isIdentLetter(current)) {
recordStartPos();
record16(current);
state = InIdentifier;
} else if (current == '0') {
recordStartPos();
record8(current);
state = InNum0;
} else if (isDecimalDigit(current)) {
recordStartPos();
record8(current);
state = InNum;
} else if (current == '.' && isDecimalDigit(next1)) {
recordStartPos();
record8(current);
state = InDecimal;
} else {
recordStartPos();
token = matchPunctuator(current, next1, next2, next3);
if (token != -1) {
if (terminator && !delimited && !prohibitAutomaticSemicolon
&& (token == QScriptGrammar::T_PLUS_PLUS
|| token == QScriptGrammar::T_MINUS_MINUS)) {
// automatic semicolon insertion
stackToken = token;
token = QScriptGrammar::T_SEMICOLON;
}
setDone(Other);
}
else {
setDone(Bad);
err = IllegalCharacter;
errmsg = QLatin1String("Illegal character");
}
}
break;
case InString:
if (current == stringType) {
shift(1);
setDone(String);
} else if (current == 0 || isLineTerminator()) {
setDone(Bad);
err = UnclosedStringLiteral;
errmsg = QLatin1String("Unclosed string at end of line");
} else if (current == '\\') {
state = InEscapeSequence;
} else {
record16(current);
}
break;
// Escape Sequences inside of strings
case InEscapeSequence:
if (isOctalDigit(current)) {
if (current >= '0' && current <= '3' &&
isOctalDigit(next1) && isOctalDigit(next2)) {
record16(convertOctal(current, next1, next2));
shift(2);
state = InString;
} else if (isOctalDigit(current) &&
isOctalDigit(next1)) {
record16(convertOctal('0', current, next1));
shift(1);
state = InString;
} else if (isOctalDigit(current)) {
record16(convertOctal('0', '0', current));
state = InString;
} else {
setDone(Bad);
err = IllegalEscapeSequence;
errmsg = QLatin1String("Illegal escape squence");
}
} else if (current == 'x')
state = InHexEscape;
else if (current == 'u')
state = InUnicodeEscape;
else {
record16(singleEscape(current));
state = InString;
}
break;
case InHexEscape:
if (isHexDigit(current) && isHexDigit(next1)) {
state = InString;
record16(QLatin1Char(convertHex(current, next1)));
shift(1);
} else if (current == stringType) {
record16(QLatin1Char('x'));
shift(1);
setDone(String);
} else {
record16(QLatin1Char('x'));
record16(current);
state = InString;
}
break;
case InUnicodeEscape:
if (isHexDigit(current) && isHexDigit(next1) &&
isHexDigit(next2) && isHexDigit(next3)) {
record16(convertUnicode(current, next1, next2, next3));
shift(3);
state = InString;
} else if (current == stringType) {
record16(QLatin1Char('u'));
shift(1);
setDone(String);
} else {
setDone(Bad);
err = IllegalUnicodeEscapeSequence;
errmsg = QLatin1String("Illegal unicode escape sequence");
}
break;
case InSingleLineComment:
if (isLineTerminator()) {
shiftWindowsLineBreak();
yylineno++;
yycolumn = 0;
terminator = true;
bol = true;
if (restrKeyword) {
token = QScriptGrammar::T_SEMICOLON;
setDone(Other);
} else
state = Start;
} else if (current == 0) {
setDone(Eof);
}
break;
case InMultiLineComment:
if (current == 0) {
setDone(Bad);
err = UnclosedComment;
errmsg = QLatin1String("Unclosed comment at end of file");
} else if (isLineTerminator()) {
shiftWindowsLineBreak();
yylineno++;
} else if (current == '*' && next1 == '/') {
state = Start;
shift(1);
}
break;
case InIdentifier:
if (isIdentLetter(current) || isDecimalDigit(current)) {
record16(current);
break;
}
setDone(Identifier);
break;
case InNum0:
if (current == 'x' || current == 'X') {
record8(current);
state = InHex;
} else if (current == '.') {
record8(current);
state = InDecimal;
} else if (current == 'e' || current == 'E') {
record8(current);
state = InExponentIndicator;
} else if (isOctalDigit(current)) {
record8(current);
state = InOctal;
} else if (isDecimalDigit(current)) {
record8(current);
state = InDecimal;
} else {
setDone(Number);
}
break;
case InHex:
if (isHexDigit(current))
record8(current);
else
setDone(Hex);
break;
case InOctal:
if (isOctalDigit(current)) {
record8(current);
} else if (isDecimalDigit(current)) {
record8(current);
state = InDecimal;
} else {
setDone(Octal);
}
break;
case InNum:
if (isDecimalDigit(current)) {
record8(current);
} else if (current == '.') {
record8(current);
state = InDecimal;
} else if (current == 'e' || current == 'E') {
record8(current);
state = InExponentIndicator;
} else {
setDone(Number);
}
break;
case InDecimal:
if (isDecimalDigit(current)) {
record8(current);
} else if (current == 'e' || current == 'E') {
record8(current);
state = InExponentIndicator;
} else {
setDone(Number);
}
break;
case InExponentIndicator:
if (current == '+' || current == '-') {
record8(current);
} else if (isDecimalDigit(current)) {
record8(current);
state = InExponent;
} else {
setDone(Bad);
err = IllegalExponentIndicator;
errmsg = QLatin1String("Illegal syntax for exponential number");
}
break;
case InExponent:
if (isDecimalDigit(current)) {
record8(current);
} else {
setDone(Number);
}
break;
default:
Q_ASSERT_X(0, "Lexer::lex", "Unhandled state in switch statement");
}
// move on to the next character
if (!done)
shift(1);
if (state != Start && state != InSingleLineComment)
bol = false;
}
// no identifiers allowed directly after numeric literal, e.g. "3in" is bad
if ((state == Number || state == Octal || state == Hex)
&& isIdentLetter(current)) {
state = Bad;
err = IllegalIdentifier;
errmsg = QLatin1String("Identifier cannot start with numeric literal");
}
// terminate string
buffer8[pos8] = '\0';
double dval = 0;
if (state == Number) {
dval = qstrtod(buffer8, 0, 0);
} else if (state == Hex) { // scan hex numbers
dval = QScript::integerFromString(buffer8, pos8, 16);
state = Number;
} else if (state == Octal) { // scan octal number
dval = QScript::integerFromString(buffer8, pos8, 8);
state = Number;
}
restrKeyword = false;
delimited = false;
switch (parenthesesState) {
case IgnoreParentheses:
break;
case CountParentheses:
if (token == QScriptGrammar::T_RPAREN) {
--parenthesesCount;
if (parenthesesCount == 0)
parenthesesState = BalancedParentheses;
} else if (token == QScriptGrammar::T_LPAREN) {
++parenthesesCount;
}
break;
case BalancedParentheses:
parenthesesState = IgnoreParentheses;
break;
}
switch (state) {
case Eof:
return 0;
case Other:
if(token == QScriptGrammar::T_RBRACE || token == QScriptGrammar::T_SEMICOLON)
delimited = true;
return token;
case Identifier:
if ((token = findReservedWord(buffer16, pos16)) < 0) {
/* TODO: close leak on parse error. same holds true for String */
qsyylval = QString(buffer16, pos16);
return QScriptGrammar::T_IDENTIFIER;
}
if (token == QScriptGrammar::T_CONTINUE || token == QScriptGrammar::T_BREAK
|| token == QScriptGrammar::T_RETURN || token == QScriptGrammar::T_THROW) {
restrKeyword = true;
} else if (token == QScriptGrammar::T_IF || token == QScriptGrammar::T_FOR
|| token == QScriptGrammar::T_WHILE || token == QScriptGrammar::T_WITH) {
parenthesesState = CountParentheses;
parenthesesCount = 0;
} else if (token == QScriptGrammar::T_DO) {
parenthesesState = BalancedParentheses;
}
return token;
case String:
qsyylval = QString(buffer16, pos16);
return QScriptGrammar::T_STRING_LITERAL;
case Number:
qsyylval = dval;
return QScriptGrammar::T_NUMERIC_LITERAL;
case Bad:
return -1;
default:
Q_ASSERT(!"unhandled numeration value in switch");
return -1;
}
}
bool QScript::Lexer::isWhiteSpace() const
{
return (current == ' ' || current == '\t' ||
current == 0x0b || current == 0x0c);
}
bool QScript::Lexer::isLineTerminator() const
{
return (current == '\n' || current == '\r');
}
bool QScript::Lexer::isIdentLetter(ushort c)
{
/* TODO: allow other legitimate unicode chars */
return ((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| c == '$'
|| c == '_');
}
bool QScript::Lexer::isDecimalDigit(ushort c)
{
return (c >= '0' && c <= '9');
}
bool QScript::Lexer::isHexDigit(ushort c) const
{
return ((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F'));
}
bool QScript::Lexer::isOctalDigit(ushort c) const
{
return (c >= '0' && c <= '7');
}
int QScript::Lexer::matchPunctuator(ushort c1, ushort c2,
ushort c3, ushort c4)
{
if (c1 == '>' && c2 == '>' && c3 == '>' && c4 == '=') {
shift(4);
return QScriptGrammar::T_GT_GT_GT_EQ;
} else if (c1 == '=' && c2 == '=' && c3 == '=') {
shift(3);
return QScriptGrammar::T_EQ_EQ_EQ;
} else if (c1 == '!' && c2 == '=' && c3 == '=') {
shift(3);
return QScriptGrammar::T_NOT_EQ_EQ;
} else if (c1 == '>' && c2 == '>' && c3 == '>') {
shift(3);
return QScriptGrammar::T_GT_GT_GT;
} else if (c1 == '<' && c2 == '<' && c3 == '=') {
shift(3);
return QScriptGrammar::T_LT_LT_EQ;
} else if (c1 == '>' && c2 == '>' && c3 == '=') {
shift(3);
return QScriptGrammar::T_GT_GT_EQ;
} else if (c1 == '<' && c2 == '=') {
shift(2);
return QScriptGrammar::T_LE;
} else if (c1 == '>' && c2 == '=') {
shift(2);
return QScriptGrammar::T_GE;
} else if (c1 == '!' && c2 == '=') {
shift(2);
return QScriptGrammar::T_NOT_EQ;
} else if (c1 == '+' && c2 == '+') {
shift(2);
return QScriptGrammar::T_PLUS_PLUS;
} else if (c1 == '-' && c2 == '-') {
shift(2);
return QScriptGrammar::T_MINUS_MINUS;
} else if (c1 == '=' && c2 == '=') {
shift(2);
return QScriptGrammar::T_EQ_EQ;
} else if (c1 == '+' && c2 == '=') {
shift(2);
return QScriptGrammar::T_PLUS_EQ;
} else if (c1 == '-' && c2 == '=') {
shift(2);
return QScriptGrammar::T_MINUS_EQ;
} else if (c1 == '*' && c2 == '=') {
shift(2);
return QScriptGrammar::T_STAR_EQ;
} else if (c1 == '/' && c2 == '=') {
shift(2);
return QScriptGrammar::T_DIVIDE_EQ;
} else if (c1 == '&' && c2 == '=') {
shift(2);
return QScriptGrammar::T_AND_EQ;
} else if (c1 == '^' && c2 == '=') {
shift(2);
return QScriptGrammar::T_XOR_EQ;
} else if (c1 == '%' && c2 == '=') {
shift(2);
return QScriptGrammar::T_REMAINDER_EQ;
} else if (c1 == '|' && c2 == '=') {
shift(2);
return QScriptGrammar::T_OR_EQ;
} else if (c1 == '<' && c2 == '<') {
shift(2);
return QScriptGrammar::T_LT_LT;
} else if (c1 == '>' && c2 == '>') {
shift(2);
return QScriptGrammar::T_GT_GT;
} else if (c1 == '&' && c2 == '&') {
shift(2);
return QScriptGrammar::T_AND_AND;
} else if (c1 == '|' && c2 == '|') {
shift(2);
return QScriptGrammar::T_OR_OR;
}
switch(c1) {
case '=': shift(1); return QScriptGrammar::T_EQ;
case '>': shift(1); return QScriptGrammar::T_GT;
case '<': shift(1); return QScriptGrammar::T_LT;
case ',': shift(1); return QScriptGrammar::T_COMMA;
case '!': shift(1); return QScriptGrammar::T_NOT;
case '~': shift(1); return QScriptGrammar::T_TILDE;
case '?': shift(1); return QScriptGrammar::T_QUESTION;
case ':': shift(1); return QScriptGrammar::T_COLON;
case '.': shift(1); return QScriptGrammar::T_DOT;
case '+': shift(1); return QScriptGrammar::T_PLUS;
case '-': shift(1); return QScriptGrammar::T_MINUS;
case '*': shift(1); return QScriptGrammar::T_STAR;
case '/': shift(1); return QScriptGrammar::T_DIVIDE_;
case '&': shift(1); return QScriptGrammar::T_AND;
case '|': shift(1); return QScriptGrammar::T_OR;
case '^': shift(1); return QScriptGrammar::T_XOR;
case '%': shift(1); return QScriptGrammar::T_REMAINDER;
case '(': shift(1); return QScriptGrammar::T_LPAREN;
case ')': shift(1); return QScriptGrammar::T_RPAREN;
case '{': shift(1); return QScriptGrammar::T_LBRACE;
case '}': shift(1); return QScriptGrammar::T_RBRACE;
case '[': shift(1); return QScriptGrammar::T_LBRACKET;
case ']': shift(1); return QScriptGrammar::T_RBRACKET;
case ';': shift(1); return QScriptGrammar::T_SEMICOLON;
default: return -1;
}
}
ushort QScript::Lexer::singleEscape(ushort c) const
{
switch(c) {
case 'b':
return 0x08;
case 't':
return 0x09;
case 'n':
return 0x0A;
case 'v':
return 0x0B;
case 'f':
return 0x0C;
case 'r':
return 0x0D;
case '"':
return 0x22;
case '\'':
return 0x27;
case '\\':
return 0x5C;
default:
return c;
}
}
ushort QScript::Lexer::convertOctal(ushort c1, ushort c2,
ushort c3) const
{
return ((c1 - '0') * 64 + (c2 - '0') * 8 + c3 - '0');
}
unsigned char QScript::Lexer::convertHex(ushort c)
{
if (c >= '0' && c <= '9')
return (c - '0');
else if (c >= 'a' && c <= 'f')
return (c - 'a' + 10);
else
return (c - 'A' + 10);
}
unsigned char QScript::Lexer::convertHex(ushort c1, ushort c2)
{
return ((convertHex(c1) << 4) + convertHex(c2));
}
QChar QScript::Lexer::convertUnicode(ushort c1, ushort c2,
ushort c3, ushort c4)
{
return QChar((convertHex(c3) << 4) + convertHex(c4),
(convertHex(c1) << 4) + convertHex(c2));
}
void QScript::Lexer::record8(ushort c)
{
Q_ASSERT(c <= 0xff);
// enlarge buffer if full
if (pos8 >= size8 - 1) {
char *tmp = new char[2 * size8];
memcpy(tmp, buffer8, size8 * sizeof(char));
delete [] buffer8;
buffer8 = tmp;
size8 *= 2;
}
buffer8[pos8++] = (char) c;
}
void QScript::Lexer::record16(QChar c)
{
// enlarge buffer if full
if (pos16 >= size16 - 1) {
QChar *tmp = new QChar[2 * size16];
memcpy(tmp, buffer16, size16 * sizeof(QChar));
delete [] buffer16;
buffer16 = tmp;
size16 *= 2;
}
buffer16[pos16++] = c;
}
void QScript::Lexer::recordStartPos()
{
startlineno = yylineno;
startcolumn = yycolumn;
}
bool QScript::Lexer::scanRegExp(RegExpBodyPrefix prefix)
{
pos16 = 0;
bool lastWasEscape = false;
if (prefix == EqualPrefix)
record16(QLatin1Char('='));
while (1) {
if (isLineTerminator() || current == 0) {
errmsg = QLatin1String("Unterminated regular expression literal");
return false;
}
else if (current != '/' || lastWasEscape == true)
{
record16(current);
lastWasEscape = !lastWasEscape && (current == '\\');
}
else {
pattern = QString(buffer16, pos16);
pos16 = 0;
shift(1);
break;
}
shift(1);
}
flags = 0;
while (isIdentLetter(current)) {
record16(current);
shift(1);
}
return true;
}
void QScript::Lexer::syncProhibitAutomaticSemicolon()
{
if (parenthesesState == BalancedParentheses) {
// we have seen something like "if (foo)", which means we should
// never insert an automatic semicolon at this point, since it would
// then be expanded into an empty statement (ECMA-262 7.9.1)
prohibitAutomaticSemicolon = true;
parenthesesState = IgnoreParentheses;
} else {
prohibitAutomaticSemicolon = false;
}
}
class Translator;
class QScriptParser: protected QScriptGrammar
{
public:
QVariant val;
struct Location {
int startLine;
int startColumn;
int endLine;
int endColumn;
};
public:
QScriptParser();
~QScriptParser();
bool parse(QScript::Lexer *lexer,
const QString &fileName,
Translator *translator);
inline QString errorMessage() const
{ return error_message; }
inline int errorLineNumber() const
{ return error_lineno; }
inline int errorColumnNumber() const
{ return error_column; }
protected:
inline void reallocateStack();
inline QVariant &sym(int index)
{ return sym_stack [tos + index - 1]; }
inline Location &loc(int index)
{ return location_stack [tos + index - 2]; }
protected:
int tos;
int stack_size;
QVector<QVariant> sym_stack;
int *state_stack;
Location *location_stack;
QString error_message;
int error_lineno;
int error_column;
};
inline void QScriptParser::reallocateStack()
{
if (! stack_size)
stack_size = 128;
else
stack_size <<= 1;
sym_stack.resize(stack_size);
state_stack = reinterpret_cast<int*> (qRealloc(state_stack, stack_size * sizeof(int)));
location_stack = reinterpret_cast<Location*> (qRealloc(location_stack, stack_size * sizeof(Location)));
}
inline static bool automatic(QScript::Lexer *lexer, int token)
{
return (token == QScriptGrammar::T_RBRACE)
|| (token == 0)
|| lexer->prevTerminator();
}
QScriptParser::QScriptParser():
tos(0),
stack_size(0),
sym_stack(0),
state_stack(0),
location_stack(0)
{
}
QScriptParser::~QScriptParser()
{
if (stack_size) {
qFree(state_stack);
qFree(location_stack);
}
}
static inline QScriptParser::Location location(QScript::Lexer *lexer)
{
QScriptParser::Location loc;
loc.startLine = lexer->startLineNo();
loc.startColumn = lexer->startColumnNo();
loc.endLine = lexer->endLineNo();
loc.endColumn = lexer->endColumnNo();
return loc;
}
bool QScriptParser::parse(QScript::Lexer *lexer,
const QString &fileName,
Translator *translator)
{
const int INITIAL_STATE = 0;
int yytoken = -1;
int saved_yytoken = -1;
int identLineNo = -1;
reallocateStack();
tos = 0;
state_stack[++tos] = INITIAL_STATE;
while (true)
{
const int state = state_stack [tos];
if (yytoken == -1 && - TERMINAL_COUNT != action_index [state])
{
if (saved_yytoken == -1)
{
yytoken = lexer->lex();
location_stack [tos] = location(lexer);
}
else
{
yytoken = saved_yytoken;
saved_yytoken = -1;
}
}
int act = t_action (state, yytoken);
if (act == ACCEPT_STATE)
return true;
else if (act > 0)
{
if (++tos == stack_size)
reallocateStack();
sym_stack [tos] = lexer->val ();
state_stack [tos] = act;
location_stack [tos] = location(lexer);
yytoken = -1;
}
else if (act < 0)
{
int r = - act - 1;
tos -= rhs [r];
act = state_stack [tos++];
switch (r) {
case 1: {
sym(1) = sym(1).toByteArray();
identLineNo = lexer->startLineNo();
} break;
case 7: {
bool rx = lexer->scanRegExp(QScript::Lexer::NoPrefix);
if (!rx) {
error_message = lexer->errorMessage();
error_lineno = lexer->startLineNo();
error_column = lexer->startColumnNo();
return false;
}
} break;
case 8: {
bool rx = lexer->scanRegExp(QScript::Lexer::EqualPrefix);
if (!rx) {
error_message = lexer->errorMessage();
error_lineno = lexer->startLineNo();
error_column = lexer->startColumnNo();
return false;
}
} break;
case 66: {
QString name = sym(1).toString();
if ((name == QLatin1String("qsTranslate")) || (name == QLatin1String("QT_TRANSLATE_NOOP"))) {
QVariantList args = sym(2).toList();
if (args.size() < 2) {
qWarning("%s:%d: %s() requires at least two arguments",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
if ((args.at(0).type() != QVariant::String)
|| (args.at(1).type() != QVariant::String)) {
qWarning("%s:%d: %s(): both arguments must be literal strings",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
QString context = args.at(0).toString();
QString text = args.at(1).toString();
QString comment = args.value(2).toString();
QString extracomment;
bool plural = (args.size() > 4);
recordMessage(translator, context, text, comment, extracomment,
plural, fileName, identLineNo);
}
}
} else if ((name == QLatin1String("qsTr")) || (name == QLatin1String("QT_TR_NOOP"))) {
QVariantList args = sym(2).toList();
if (args.size() < 1) {
qWarning("%s:%d: %s() requires at least one argument",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
if (args.at(0).type() != QVariant::String) {
qWarning("%s:%d: %s(): text to translate must be a literal string",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
QString context = QFileInfo(fileName).baseName();
QString text = args.at(0).toString();
QString comment = args.value(1).toString();
QString extracomment;
bool plural = (args.size() > 2);
recordMessage(translator, context, text, comment, extracomment,
plural, fileName, identLineNo);
}
}
}
} break;
case 70: {
sym(1) = QVariantList();
} break;
case 71: {
sym(1) = sym(2);
} break;
case 72: {
sym(1) = QVariantList() << sym(1);
} break;
case 73: {
sym(1) = sym(1).toList() << sym(3);
} break;
case 94: {
if ((sym(1).type() == QVariant::String) || (sym(3).type() == QVariant::String))
sym(1) = sym(1).toString() + sym(3).toString();
else
sym(1) = QVariant();
} break;
} // switch
state_stack [tos] = nt_action (act, lhs [r] - TERMINAL_COUNT);
if (rhs[r] > 1) {
location_stack[tos - 1].endLine = location_stack[tos + rhs[r] - 2].endLine;
location_stack[tos - 1].endColumn = location_stack[tos + rhs[r] - 2].endColumn;
location_stack[tos] = location_stack[tos + rhs[r] - 1];
}
}
else
{
if (saved_yytoken == -1 && automatic (lexer, yytoken) && t_action (state, T_AUTOMATIC_SEMICOLON) > 0)
{
saved_yytoken = yytoken;
yytoken = T_SEMICOLON;
continue;
}
else if ((state == INITIAL_STATE) && (yytoken == 0)) {
// accept empty input
yytoken = T_SEMICOLON;
continue;
}
int ers = state;
int shifts = 0;
int reduces = 0;
int expected_tokens [3];
for (int tk = 0; tk < TERMINAL_COUNT; ++tk)
{
int k = t_action (ers, tk);
if (! k)
continue;
else if (k < 0)
++reduces;
else if (spell [tk])
{
if (shifts < 3)
expected_tokens [shifts] = tk;
++shifts;
}
}
error_message.clear ();
if (shifts && shifts < 3)
{
bool first = true;
for (int s = 0; s < shifts; ++s)
{
if (first)
error_message += QLatin1String ("Expected ");
else
error_message += QLatin1String (", ");
first = false;
error_message += QLatin1String("`");
error_message += QLatin1String (spell [expected_tokens [s]]);
error_message += QLatin1String("'");
}
}
if (error_message.isEmpty())
error_message = lexer->errorMessage();
error_lineno = lexer->startLineNo();
error_column = lexer->startColumnNo();
return false;
}
}
return false;
}
bool loadQScript(Translator &translator, QIODevice &dev, ConversionData &cd)
{
QTextStream ts(&dev);
QByteArray codecName;
if (!cd.m_codecForSource.isEmpty())
codecName = cd.m_codecForSource;
else
codecName = translator.codecName(); // Just because it should be latin1 already
ts.setCodec(QTextCodec::codecForName(codecName));
ts.setAutoDetectUnicode(true);
QString code = ts.readAll();
QScript::Lexer lexer;
lexer.setCode(code, /*lineNumber=*/1);
QScriptParser parser;
if (!parser.parse(&lexer, cd.m_sourceFileName, &translator)) {
qWarning("%s:%d: %s", qPrintable(cd.m_sourceFileName), parser.errorLineNumber(),
qPrintable(parser.errorMessage()));
return false;
}
// Java uses UTF-16 internally and Jambi makes UTF-8 for tr() purposes of it.
translator.setCodecName("UTF-8");
return true;
}
bool saveQScript(const Translator &translator, QIODevice &dev, ConversionData &cd)
{
Q_UNUSED(dev);
Q_UNUSED(translator);
cd.appendError(QLatin1String("Cannot save .js files"));
return false;
}
int initQScript()
{
Translator::FileFormat format;
format.extension = QLatin1String("js");
format.fileType = Translator::FileFormat::SourceCode;
format.priority = 0;
format.description = QObject::tr("Qt Script source files");
format.loader = &loadQScript;
format.saver = &saveQScript;
Translator::registerFileFormat(format);
return 1;
}
Q_CONSTRUCTOR_FUNCTION(initQScript)
QT_END_NAMESPACE
| lgpl-2.1 |
desura/desura-cef3-full | libcef/common/scheme_registrar_impl.cc | 1711 | // Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/common/scheme_registrar_impl.h"
#include <string>
#include "libcef/common/content_client.h"
#include "base/bind.h"
#include "base/logging.h"
CefSchemeRegistrarImpl::CefSchemeRegistrarImpl()
: supported_thread_id_(base::PlatformThread::CurrentId()) {
}
bool CefSchemeRegistrarImpl::AddCustomScheme(
const CefString& scheme_name,
bool is_standard,
bool is_local,
bool is_display_isolated) {
if (!VerifyContext())
return false;
const std::string& scheme = scheme_name;
if (is_standard)
standard_schemes_.push_back(scheme);
CefContentClient::SchemeInfo scheme_info = {
scheme, is_standard, is_local, is_display_isolated};
CefContentClient::Get()->AddCustomScheme(scheme_info);
return true;
}
void CefSchemeRegistrarImpl::GetStandardSchemes(
std::vector<std::string>* standard_schemes) {
if (!VerifyContext())
return;
if (standard_schemes_.empty())
return;
standard_schemes->insert(standard_schemes->end(), standard_schemes_.begin(),
standard_schemes_.end());
}
bool CefSchemeRegistrarImpl::VerifyRefCount() {
return (GetRefCt() == 1);
}
void CefSchemeRegistrarImpl::Detach() {
if (VerifyContext())
supported_thread_id_ = base::kInvalidThreadId;
}
bool CefSchemeRegistrarImpl::VerifyContext() {
if (base::PlatformThread::CurrentId() != supported_thread_id_) {
// This object should only be accessed from the thread that created it.
NOTREACHED();
return false;
}
return true;
}
| lgpl-2.1 |
Chinchilla-Software-Com/CQRS | wiki/docs/2.1/html/classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub.html | 18233 | <!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.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CQRS.NET: Cqrs.WebApi.SignalR.Hubs.NotificationHub Class 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="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</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/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></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 id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CQRS.NET
 <span id="projectnumber">2.1</span>
</div>
<div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub.html','');});
</script>
<div id="doc-content">
<!-- 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 class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pro-methods">Protected Member Functions</a> |
<a href="#properties">Properties</a> |
<a href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">Cqrs.WebApi.SignalR.Hubs.NotificationHub Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<div id="dynsection-0" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="dynsection-0-trigger" src="closed.png" alt="+"/> Inheritance diagram for Cqrs.WebApi.SignalR.Hubs.NotificationHub:</div>
<div id="dynsection-0-summary" class="dynsummary" style="display:block;">
</div>
<div id="dynsection-0-content" class="dyncontent" style="display:none;">
<div class="center">
<img src="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub.png" usemap="#Cqrs.WebApi.SignalR.Hubs.NotificationHub_map" alt=""/>
<map id="Cqrs.WebApi.SignalR.Hubs.NotificationHub_map" name="Cqrs.WebApi.SignalR.Hubs.NotificationHub_map">
<area href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub.html" alt="Cqrs.WebApi.SignalR.Hubs.INotificationHub" shape="rect" coords="380,0,750,24"/>
<area href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1ISingleSignOnTokenNotificationHub.html" alt="Cqrs.WebApi.SignalR.Hubs.ISingleSignOnTokenNotificationHub" shape="rect" coords="760,0,1130,24"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:aeb3d9f4d90baeb103231c5c47a13e00d"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_aeb3d9f4d90baeb103231c5c47a13e00d.html#aeb3d9f4d90baeb103231c5c47a13e00d">NotificationHub</a> (ILogger logger, ICorrelationIdHelper correlationIdHelper)</td></tr>
<tr class="separator:aeb3d9f4d90baeb103231c5c47a13e00d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a83b123b045c22ce5bcaee79168cca10a"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a83b123b045c22ce5bcaee79168cca10a.html#a83b123b045c22ce5bcaee79168cca10a">NotificationHub</a> ()</td></tr>
<tr class="separator:a83b123b045c22ce5bcaee79168cca10a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0188fd4fea68476ffc3b375482c7b56c"><td class="memItemLeft" align="right" valign="top">override Task </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a0188fd4fea68476ffc3b375482c7b56c.html#a0188fd4fea68476ffc3b375482c7b56c">OnConnected</a> ()</td></tr>
<tr class="memdesc:a0188fd4fea68476ffc3b375482c7b56c"><td class="mdescLeft"> </td><td class="mdescRight">When the connection connects to this hub instance we register the connection so we can respond back to it. <a href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a0188fd4fea68476ffc3b375482c7b56c.html#a0188fd4fea68476ffc3b375482c7b56c">More...</a><br /></td></tr>
<tr class="separator:a0188fd4fea68476ffc3b375482c7b56c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:acaadcc7cc9f00c184e12b6bb725a2167"><td class="memItemLeft" align="right" valign="top">override Task </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_acaadcc7cc9f00c184e12b6bb725a2167.html#acaadcc7cc9f00c184e12b6bb725a2167">OnReconnected</a> ()</td></tr>
<tr class="memdesc:acaadcc7cc9f00c184e12b6bb725a2167"><td class="mdescLeft"> </td><td class="mdescRight">When the connection reconnects to this hub instance we register the connection so we can respond back to it. <a href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_acaadcc7cc9f00c184e12b6bb725a2167.html#acaadcc7cc9f00c184e12b6bb725a2167">More...</a><br /></td></tr>
<tr class="separator:acaadcc7cc9f00c184e12b6bb725a2167"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub.html">Cqrs.WebApi.SignalR.Hubs.INotificationHub</a></td></tr>
<tr class="memitem:a85bd03a0bf9c2083822c4b67691f4297 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_a85bd03a0bf9c2083822c4b67691f4297.html#a85bd03a0bf9c2083822c4b67691f4297">SendUsersEvent< TAuthenticationToken ></a> (<a class="el" href="interfaceCqrs_1_1Events_1_1IEvent.html">IEvent</a>< TAuthenticationToken > eventData, params Guid[] userRsnCollection)</td></tr>
<tr class="memdesc:a85bd03a0bf9c2083822c4b67691f4297 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="mdescLeft"> </td><td class="mdescRight">Send out an event to specific user RSNs <a href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_a85bd03a0bf9c2083822c4b67691f4297.html#a85bd03a0bf9c2083822c4b67691f4297">More...</a><br /></td></tr>
<tr class="separator:a85bd03a0bf9c2083822c4b67691f4297 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a88cb05c6807058bfe2bff48427a45ad2 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_a88cb05c6807058bfe2bff48427a45ad2.html#a88cb05c6807058bfe2bff48427a45ad2">SendUserEvent< TAuthenticationToken ></a> (<a class="el" href="interfaceCqrs_1_1Events_1_1IEvent.html">IEvent</a>< TAuthenticationToken > eventData, string userToken)</td></tr>
<tr class="memdesc:a88cb05c6807058bfe2bff48427a45ad2 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="mdescLeft"> </td><td class="mdescRight">Send out an event to specific user token <a href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_a88cb05c6807058bfe2bff48427a45ad2.html#a88cb05c6807058bfe2bff48427a45ad2">More...</a><br /></td></tr>
<tr class="separator:a88cb05c6807058bfe2bff48427a45ad2 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ada48332e18931747c81997f8350f4066 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_ada48332e18931747c81997f8350f4066.html#ada48332e18931747c81997f8350f4066">SendAllUsersEvent< TAuthenticationToken ></a> (<a class="el" href="interfaceCqrs_1_1Events_1_1IEvent.html">IEvent</a>< TAuthenticationToken > eventData)</td></tr>
<tr class="memdesc:ada48332e18931747c81997f8350f4066 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="mdescLeft"> </td><td class="mdescRight">Send out an event to all users <a href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_ada48332e18931747c81997f8350f4066.html#ada48332e18931747c81997f8350f4066">More...</a><br /></td></tr>
<tr class="separator:ada48332e18931747c81997f8350f4066 inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6a50d35b8df69bb6d5fa9d31902c8ace inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_a6a50d35b8df69bb6d5fa9d31902c8ace.html#a6a50d35b8df69bb6d5fa9d31902c8ace">SendExceptThisUserEvent< TAuthenticationToken ></a> (<a class="el" href="interfaceCqrs_1_1Events_1_1IEvent.html">IEvent</a>< TAuthenticationToken > eventData, string userToken)</td></tr>
<tr class="memdesc:a6a50d35b8df69bb6d5fa9d31902c8ace inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="mdescLeft"> </td><td class="mdescRight">Send out an event to all users except the specific user token <a href="interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub_a6a50d35b8df69bb6d5fa9d31902c8ace.html#a6a50d35b8df69bb6d5fa9d31902c8ace">More...</a><br /></td></tr>
<tr class="separator:a6a50d35b8df69bb6d5fa9d31902c8ace inherit pub_methods_interfaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1INotificationHub"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a>
Protected Member Functions</h2></td></tr>
<tr class="memitem:a649436109e0060be9224aff8e75986b4"><td class="memItemLeft" align="right" valign="top">virtual string </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a649436109e0060be9224aff8e75986b4.html#a649436109e0060be9224aff8e75986b4">UserToken</a> ()</td></tr>
<tr class="separator:a649436109e0060be9224aff8e75986b4"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae5915026e53a6d7b9929f703688ce90c"><td class="memItemLeft" align="right" valign="top">virtual Task </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_ae5915026e53a6d7b9929f703688ce90c.html#ae5915026e53a6d7b9929f703688ce90c">Join</a> ()</td></tr>
<tr class="separator:ae5915026e53a6d7b9929f703688ce90c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a4b662758eb3732be37b9702c8d4e1791"><td class="memItemLeft" align="right" valign="top">virtual IDictionary< string, object > </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a4b662758eb3732be37b9702c8d4e1791.html#a4b662758eb3732be37b9702c8d4e1791">GetAdditionalDataForLogging</a> (Guid userRsn)</td></tr>
<tr class="separator:a4b662758eb3732be37b9702c8d4e1791"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a4c2512231d4ad5975fa584b14c2974c3"><td class="memItemLeft" align="right" valign="top">virtual IDictionary< string, object > </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a4c2512231d4ad5975fa584b14c2974c3.html#a4c2512231d4ad5975fa584b14c2974c3">GetAdditionalDataForLogging</a> (string userToken)</td></tr>
<tr class="separator:a4c2512231d4ad5975fa584b14c2974c3"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a>
Properties</h2></td></tr>
<tr class="memitem:a94a46d2beddc12c3920b33b53e579d36"><td class="memItemLeft" align="right" valign="top">ILogger </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a94a46d2beddc12c3920b33b53e579d36.html#a94a46d2beddc12c3920b33b53e579d36">Logger</a><code> [get, set]</code></td></tr>
<tr class="separator:a94a46d2beddc12c3920b33b53e579d36"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa65bf9c3c24588f4c36522fe7f911949"><td class="memItemLeft" align="right" valign="top">ICorrelationIdHelper </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_aa65bf9c3c24588f4c36522fe7f911949.html#aa65bf9c3c24588f4c36522fe7f911949">CorrelationIdHelper</a><code> [get, set]</code></td></tr>
<tr class="separator:aa65bf9c3c24588f4c36522fe7f911949"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a255a9ddc4f274cab0eae62e827f3726a"><td class="memItemLeft" align="right" valign="top">Func< string, Guid > </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a255a9ddc4f274cab0eae62e827f3726a.html#a255a9ddc4f274cab0eae62e827f3726a">ConvertUserTokenToUserRsn</a><code> [get, set]</code></td></tr>
<tr class="separator:a255a9ddc4f274cab0eae62e827f3726a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a27c6b1d7673af05bab0305e00aef9be7"><td class="memItemLeft" align="right" valign="top">virtual IHubContext </td><td class="memItemRight" valign="bottom"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub_a27c6b1d7673af05bab0305e00aef9be7.html#a27c6b1d7673af05bab0305e00aef9be7">CurrentHub</a><code> [get]</code></td></tr>
<tr class="separator:a27c6b1d7673af05bab0305e00aef9be7"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1WebApi.html">WebApi</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1WebApi_1_1SignalR.html">SignalR</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1WebApi_1_1SignalR_1_1Hubs.html">Hubs</a></li><li class="navelem"><a class="el" href="classCqrs_1_1WebApi_1_1SignalR_1_1Hubs_1_1NotificationHub.html">NotificationHub</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
| lgpl-2.1 |
ehmry/nix | src/libstore/binary-cache-store.cc | 13452 | #include "archive.hh"
#include "binary-cache-store.hh"
#include "compression.hh"
#include "derivations.hh"
#include "fs-accessor.hh"
#include "globals.hh"
#include "nar-info.hh"
#include "sync.hh"
#include "remote-fs-accessor.hh"
#include "nar-info-disk-cache.hh"
#include "nar-accessor.hh"
#include "json.hh"
#include "thread-pool.hh"
#include <chrono>
#include <future>
#include <regex>
#include <nlohmann/json.hpp>
namespace nix {
BinaryCacheStore::BinaryCacheStore(const Params & params)
: Store(params)
{
if (secretKeyFile != "")
secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));
StringSink sink;
sink << narVersionMagic1;
narMagic = *sink.s;
}
void BinaryCacheStore::init()
{
std::string cacheInfoFile = "nix-cache-info";
auto cacheInfo = getFile(cacheInfoFile);
if (!cacheInfo) {
upsertFile(cacheInfoFile, "StoreDir: " + storeDir + "\n", "text/x-nix-cache-info");
} else {
for (auto & line : tokenizeString<Strings>(*cacheInfo, "\n")) {
size_t colon = line.find(':');
if (colon == std::string::npos) continue;
auto name = line.substr(0, colon);
auto value = trim(line.substr(colon + 1, std::string::npos));
if (name == "StoreDir") {
if (value != storeDir)
throw Error(format("binary cache '%s' is for Nix stores with prefix '%s', not '%s'")
% getUri() % value % storeDir);
} else if (name == "WantMassQuery") {
wantMassQuery.setDefault(value == "1" ? "true" : "false");
} else if (name == "Priority") {
priority.setDefault(fmt("%d", std::stoi(value)));
}
}
}
}
void BinaryCacheStore::getFile(const std::string & path,
Callback<std::shared_ptr<std::string>> callback) noexcept
{
try {
callback(getFile(path));
} catch (...) { callback.rethrow(); }
}
void BinaryCacheStore::getFile(const std::string & path, Sink & sink)
{
std::promise<std::shared_ptr<std::string>> promise;
getFile(path,
{[&](std::future<std::shared_ptr<std::string>> result) {
try {
promise.set_value(result.get());
} catch (...) {
promise.set_exception(std::current_exception());
}
}});
auto data = promise.get_future().get();
sink((unsigned char *) data->data(), data->size());
}
std::shared_ptr<std::string> BinaryCacheStore::getFile(const std::string & path)
{
StringSink sink;
try {
getFile(path, sink);
} catch (NoSuchBinaryCacheFile &) {
return nullptr;
}
return sink.s;
}
std::string BinaryCacheStore::narInfoFileFor(const StorePath & storePath)
{
return storePathToHash(printStorePath(storePath)) + ".narinfo";
}
void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo)
{
auto narInfoFile = narInfoFileFor(narInfo->path);
upsertFile(narInfoFile, narInfo->to_string(*this), "text/x-nix-narinfo");
auto hashPart = storePathToHash(printStorePath(narInfo->path));
{
auto state_(state.lock());
state_->pathInfoCache.upsert(hashPart, PathInfoCacheValue { .value = std::shared_ptr<NarInfo>(narInfo) });
}
if (diskCache)
diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));
}
void BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref<std::string> & nar,
RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr<FSAccessor> accessor)
{
if (!repair && isValidPath(info.path)) return;
/* Verify that all references are valid. This may do some .narinfo
reads, but typically they'll already be cached. */
for (auto & ref : info.references)
try {
if (ref != info.path)
queryPathInfo(ref);
} catch (InvalidPath &) {
throw Error("cannot add '%s' to the binary cache because the reference '%s' is not valid",
printStorePath(info.path), printStorePath(ref));
}
assert(nar->compare(0, narMagic.size(), narMagic) == 0);
auto narInfo = make_ref<NarInfo>(info);
narInfo->narSize = nar->size();
narInfo->narHash = hashString(htSHA256, *nar);
if (info.narHash && info.narHash != narInfo->narHash)
throw Error("refusing to copy corrupted path '%1%' to binary cache", printStorePath(info.path));
auto accessor_ = std::dynamic_pointer_cast<RemoteFSAccessor>(accessor);
auto narAccessor = makeNarAccessor(nar);
if (accessor_)
accessor_->addToCache(printStorePath(info.path), *nar, narAccessor);
/* Optionally write a JSON file containing a listing of the
contents of the NAR. */
if (writeNARListing) {
std::ostringstream jsonOut;
{
JSONObject jsonRoot(jsonOut);
jsonRoot.attr("version", 1);
{
auto res = jsonRoot.placeholder("root");
listNar(res, narAccessor, "", true);
}
}
upsertFile(storePathToHash(printStorePath(info.path)) + ".ls", jsonOut.str(), "application/json");
}
/* Compress the NAR. */
narInfo->compression = compression;
auto now1 = std::chrono::steady_clock::now();
auto narCompressed = compress(compression, *nar, parallelCompression);
auto now2 = std::chrono::steady_clock::now();
narInfo->fileHash = hashString(htSHA256, *narCompressed);
narInfo->fileSize = narCompressed->size();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();
printMsg(lvlTalkative, "copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache",
printStorePath(narInfo->path), narInfo->narSize,
((1.0 - (double) narCompressed->size() / nar->size()) * 100.0),
duration);
narInfo->url = "nar/" + narInfo->fileHash.to_string(Base32, false) + ".nar"
+ (compression == "xz" ? ".xz" :
compression == "bzip2" ? ".bz2" :
compression == "br" ? ".br" :
"");
/* Optionally maintain an index of DWARF debug info files
consisting of JSON files named 'debuginfo/<build-id>' that
specify the NAR file and member containing the debug info. */
if (writeDebugInfo) {
std::string buildIdDir = "/lib/debug/.build-id";
if (narAccessor->stat(buildIdDir).type == FSAccessor::tDirectory) {
ThreadPool threadPool(25);
auto doFile = [&](std::string member, std::string key, std::string target) {
checkInterrupt();
nlohmann::json json;
json["archive"] = target;
json["member"] = member;
// FIXME: or should we overwrite? The previous link may point
// to a GC'ed file, so overwriting might be useful...
if (fileExists(key)) return;
printMsg(lvlTalkative, "creating debuginfo link from '%s' to '%s'", key, target);
upsertFile(key, json.dump(), "application/json");
};
std::regex regex1("^[0-9a-f]{2}$");
std::regex regex2("^[0-9a-f]{38}\\.debug$");
for (auto & s1 : narAccessor->readDirectory(buildIdDir)) {
auto dir = buildIdDir + "/" + s1;
if (narAccessor->stat(dir).type != FSAccessor::tDirectory
|| !std::regex_match(s1, regex1))
continue;
for (auto & s2 : narAccessor->readDirectory(dir)) {
auto debugPath = dir + "/" + s2;
if (narAccessor->stat(debugPath).type != FSAccessor::tRegular
|| !std::regex_match(s2, regex2))
continue;
auto buildId = s1 + s2;
std::string key = "debuginfo/" + buildId;
std::string target = "../" + narInfo->url;
threadPool.enqueue(std::bind(doFile, std::string(debugPath, 1), key, target));
}
}
threadPool.process();
}
}
/* Atomically write the NAR file. */
if (repair || !fileExists(narInfo->url)) {
stats.narWrite++;
upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
} else
stats.narWriteAverted++;
stats.narWriteBytes += nar->size();
stats.narWriteCompressedBytes += narCompressed->size();
stats.narWriteCompressionTimeMs += duration;
/* Atomically write the NAR info file.*/
if (secretKey) narInfo->sign(*this, *secretKey);
writeNarInfo(narInfo);
stats.narInfoWrite++;
}
bool BinaryCacheStore::isValidPathUncached(const StorePath & storePath)
{
// FIXME: this only checks whether a .narinfo with a matching hash
// part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even
// though they shouldn't. Not easily fixed.
return fileExists(narInfoFileFor(storePath));
}
void BinaryCacheStore::narFromPath(const StorePath & storePath, Sink & sink)
{
auto info = queryPathInfo(storePath).cast<const NarInfo>();
uint64_t narSize = 0;
LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {
sink(data, len);
narSize += len;
});
auto decompressor = makeDecompressionSink(info->compression, wrapperSink);
try {
getFile(info->url, *decompressor);
} catch (NoSuchBinaryCacheFile & e) {
throw SubstituteGone(e.what());
}
decompressor->finish();
stats.narRead++;
//stats.narReadCompressedBytes += nar->size(); // FIXME
stats.narReadBytes += narSize;
}
void BinaryCacheStore::queryPathInfoUncached(const StorePath & storePath,
Callback<std::shared_ptr<const ValidPathInfo>> callback) noexcept
{
auto uri = getUri();
auto storePathS = printStorePath(storePath);
auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo,
fmt("querying info about '%s' on '%s'", storePathS, uri), Logger::Fields{storePathS, uri});
PushActivity pact(act->id);
auto narInfoFile = narInfoFileFor(storePath);
auto callbackPtr = std::make_shared<decltype(callback)>(std::move(callback));
getFile(narInfoFile,
{[=](std::future<std::shared_ptr<std::string>> fut) {
try {
auto data = fut.get();
if (!data) return (*callbackPtr)(nullptr);
stats.narInfoRead++;
(*callbackPtr)((std::shared_ptr<ValidPathInfo>)
std::make_shared<NarInfo>(*this, *data, narInfoFile));
(void) act; // force Activity into this lambda to ensure it stays alive
} catch (...) {
callbackPtr->rethrow();
}
}});
}
StorePath BinaryCacheStore::addToStore(const string & name, const Path & srcPath,
bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)
{
// FIXME: some cut&paste from LocalStore::addToStore().
/* Read the whole path into memory. This is not a very scalable
method for very large paths, but `copyPath' is mainly used for
small files. */
StringSink sink;
Hash h;
if (recursive) {
dumpPath(srcPath, sink, filter);
h = hashString(hashAlgo, *sink.s);
} else {
auto s = readFile(srcPath);
dumpString(s, sink);
h = hashString(hashAlgo, s);
}
ValidPathInfo info(makeFixedOutputPath(recursive, h, name));
addToStore(info, sink.s, repair, CheckSigs, nullptr);
return std::move(info.path);
}
StorePath BinaryCacheStore::addTextToStore(const string & name, const string & s,
const StorePathSet & references, RepairFlag repair)
{
ValidPathInfo info(computeStorePathForText(name, s, references));
info.references = cloneStorePathSet(references);
if (repair || !isValidPath(info.path)) {
StringSink sink;
dumpString(s, sink);
addToStore(info, sink.s, repair, CheckSigs, nullptr);
}
return std::move(info.path);
}
ref<FSAccessor> BinaryCacheStore::getFSAccessor()
{
return make_ref<RemoteFSAccessor>(ref<Store>(shared_from_this()), localNarCache);
}
void BinaryCacheStore::addSignatures(const StorePath & storePath, const StringSet & sigs)
{
/* Note: this is inherently racy since there is no locking on
binary caches. In particular, with S3 this unreliable, even
when addSignatures() is called sequentially on a path, because
S3 might return an outdated cached version. */
auto narInfo = make_ref<NarInfo>((NarInfo &) *queryPathInfo(storePath));
narInfo->sigs.insert(sigs.begin(), sigs.end());
auto narInfoFile = narInfoFileFor(narInfo->path);
writeNarInfo(narInfo);
}
std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const StorePath & path)
{
auto drvPath = path.clone();
if (!path.isDerivation()) {
try {
auto info = queryPathInfo(path);
// FIXME: add a "Log" field to .narinfo
if (!info->deriver) return nullptr;
drvPath = info->deriver->clone();
} catch (InvalidPath &) {
return nullptr;
}
}
auto logPath = "log/" + std::string(baseNameOf(printStorePath(drvPath)));
debug("fetching build log from binary cache '%s/%s'", getUri(), logPath);
return getFile(logPath);
}
}
| lgpl-2.1 |
dsroche/flint2 | fq_nmod_poly/scalar_mul_fq.c | 538 | /*
Copyright (C) 2013 Mike Hansen
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>.
*/
#include "fq_nmod_poly.h"
#ifdef T
#undef T
#endif
#define T fq_nmod
#define CAP_T FQ_NMOD
#include "fq_poly_templates/scalar_mul_fq.c"
#undef CAP_T
#undef T
| lgpl-2.1 |
RLovelett/qt | src/gui/graphicsview/qgraphicslayout_p.h | 3523 | /****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QGRAPHICSLAYOUT_P_H
#define QGRAPHICSLAYOUT_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of qapplication_*.cpp, qwidget*.cpp and qfiledialog.cpp. This header
// file may change from version to version without notice, or even be removed.
//
// We mean it.
//
#include <QtCore/qglobal.h>
#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
#include "qgraphicslayout.h"
#include "qgraphicslayoutitem_p.h"
#include <QtGui/qstyle.h>
QT_BEGIN_NAMESPACE
class QGraphicsLayoutItem;
class QGraphicsWidget;
#ifdef QT_DEBUG
inline bool qt_graphicsLayoutDebug()
{
static int checked_env = -1;
if(checked_env == -1)
checked_env = !!qgetenv("QT_GRAPHICSLAYOUT_DEBUG").toInt();
return checked_env;
}
#endif
class Q_AUTOTEST_EXPORT QGraphicsLayoutPrivate : public QGraphicsLayoutItemPrivate
{
Q_DECLARE_PUBLIC(QGraphicsLayout)
public:
QGraphicsLayoutPrivate() : QGraphicsLayoutItemPrivate(0, true), left(-1.0), top(-1.0), right(-1.0), bottom(-1.0),
activated(true) { }
void reparentChildItems(QGraphicsItem *newParent);
void getMargin(qreal *result, qreal userMargin, QStyle::PixelMetric pm) const;
Qt::LayoutDirection visualDirection() const;
void addChildLayoutItem(QGraphicsLayoutItem *item);
void activateRecursive(QGraphicsLayoutItem *item);
qreal left, top, right, bottom;
bool activated;
};
QT_END_NAMESPACE
#endif //QT_NO_GRAPHICSVIEW
#endif
| lgpl-2.1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.