repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
WaveHack/OpenDominion
app/database/migrations/2020_10_22_200935_create_user_achievements_table.php
948
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUserAchievementsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('user_achievements', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->integer('achievement_id')->unsigned(); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users'); $table->foreign('achievement_id')->references('id')->on('achievements'); $table->unique(['user_id', 'achievement_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('user_achievements'); } }
agpl-3.0
tenders-exposed/elvis-ember
app/adapters/elvis.js
19496
import Adapter from 'ember-data/adapter'; import { AdapterError, InvalidError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServerError, TimeoutError, AbortError } from 'ember-data/adapters/errors'; import { BuildURLMixin, isEnabled, // runInDebug, // warn, deprecate, parseResponseHeaders } from 'ember-data/-private'; import MapWithDefault from '@ember/map/with-default'; import { get } from '@ember/object'; import RSVP from 'rsvp'; import { run } from '@ember/runloop'; import $ from 'jquery'; const { Promise } = RSVP; let ElvisAdapter = Adapter.extend(BuildURLMixin, { defaultSerializer: '-rest', sortQueryParams(obj) { let keys = Object.keys(obj); let len = keys.length; if (len < 2) { return obj; } let newQueryParams = {}; let sortedKeys = keys.sort(); for (let i = 0; i < len; i++) { newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; } return newQueryParams; }, coalesceFindRequests: false, // // shouldReloadAll(store, snapshotArray) { // return true; // }, findRecord(store, type, id, snapshot) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, id, snapshot, requestType: 'findRecord' }); return this._makeRequest(request); } else { let url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); let query = this.buildQuery(snapshot); return this.ajax(url, 'GET', { data: query }); } }, findAll(store, type, sinceToken, snapshotRecordArray) { let query = this.buildQuery(snapshotRecordArray); if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, sinceToken, query, snapshots: snapshotRecordArray, requestType: 'findAll' }); return this._makeRequest(request); } else { let url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll'); if (sinceToken) { query.since = sinceToken; } return this.ajax(url, 'GET', { data: query }); } }, query(store, type, query) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, query, requestType: 'query' }); return this._makeRequest(request); } else { let url = this.buildURL(type.modelName, null, null, 'query', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, queryRecord(store, type, query) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, query, requestType: 'queryRecord' }); return this._makeRequest(request); } else { let url = this.buildURL(type.modelName, null, null, 'queryRecord', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, findMany(store, type, ids, snapshots) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, ids, snapshots, requestType: 'findMany' }); return this._makeRequest(request); } else { let url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { ids } }); } }, findHasMany(store, snapshot, url, relationship) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, snapshot, url, relationship, requestType: 'findHasMany' }); return this._makeRequest(request); } else { let { id } = snapshot; let type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany')); return this.ajax(url, 'GET'); } }, findBelongsTo(store, snapshot, url, relationship) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, snapshot, url, relationship, requestType: 'findBelongsTo' }); return this._makeRequest(request); } else { let { id } = snapshot; let type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo')); return this.ajax(url, 'GET'); } }, createRecord(store, type, snapshot) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, snapshot, requestType: 'createRecord' }); return this._makeRequest(request); } else { let data = {}; let serializer = store.serializerFor(type.modelName); let url = this.buildURL(type.modelName, null, snapshot, 'createRecord'); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(url, 'POST', { data }); } }, updateRecord(store, type, snapshot) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, snapshot, requestType: 'updateRecord' }); return this._makeRequest(request); } else { let data = {}; let serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot); let { id } = snapshot; let url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, 'PATCH', { data }); } }, deleteRecord(store, type, snapshot) { if (isEnabled('ds-improved-ajax') && !this._hasCustomizedAjax()) { let request = this._requestFor({ store, type, snapshot, requestType: 'deleteRecord' }); return this._makeRequest(request); } else { let { id } = snapshot; return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), 'DELETE'); } }, _stripIDFromURL(store, snapshot) { let url = this.buildURL(snapshot.modelName, snapshot.id, snapshot); let expandedURL = url.split('/'); // Case when the url is of the format ...something/:id // We are decodeURIComponent-ing the lastSegment because if it represents // the id, it has been encodeURIComponent-ified within `buildURL`. If we // don't do this, then records with id having special characters are not // coalesced correctly (see GH #4190 for the reported bug) let lastSegment = expandedURL[expandedURL.length - 1]; let { id } = snapshot; if (decodeURIComponent(lastSegment) === id) { expandedURL[expandedURL.length - 1] = ''; } else if (endsWith(lastSegment, `?id=${id}`)) { // Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers maxURLLength: 2048, groupRecordsForFindMany(store, snapshots) { let groups = MapWithDefault.create({ defaultValue() { return []; } }); let adapter = this; let { maxURLLength } = this; snapshots.forEach((snapshot) => { let baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { let baseUrl = adapter._stripIDFromURL(store, group[0]); let idsSize = 0; let splitGroups = [[]]; group.forEach((snapshot) => { let additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; if (baseUrl.length + idsSize + additionalLength >= maxURLLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; let lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(snapshot); }); return splitGroups; } let groupsArray = []; groups.forEach((group) => { let paramNameLength = '&ids%5B%5D='.length; let splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength); splitGroups.forEach((splitGroup) => groupsArray.push(splitGroup)); }); return groupsArray; }, handleResponse(status, headers, payload, requestData) { if (this.isSuccess(status, headers, payload)) { return payload; } else if (this.isInvalid(status, headers, payload)) { return new InvalidError(payload.errors); } let errors = this.normalizeErrorResponse(status, headers, payload); let detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData); if (isEnabled('ds-extended-errors')) { switch (status) { case 401: return new UnauthorizedError(errors, detailedMessage); case 403: return new ForbiddenError(errors, detailedMessage); case 404: return new NotFoundError(errors, detailedMessage); case 409: return new ConflictError(errors, detailedMessage); default: if (status >= 500) { return new ServerError(errors, detailedMessage); } } } return new AdapterError(errors, detailedMessage); }, isSuccess(status/*, headers, payload*/) { return status >= 200 && status < 300 || status === 304; }, isInvalid(status/*, headers, payload*/) { return status === 422; }, ajax(url, type, options) { let adapter = this; let requestData = { url, method: type }; return new Promise(function(resolve, reject) { let hash = adapter.ajaxOptions(url, type, options); hash.success = function(payload, textStatus, jqXHR) { let response = ajaxSuccess(adapter, jqXHR, payload, requestData); run.join(null, resolve, response); }; hash.error = function(jqXHR, textStatus, errorThrown) { let responseData = { textStatus, errorThrown }; let error = ajaxError(adapter, jqXHR, requestData, responseData); run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, `DS: ElvisAdapter#ajax ${type} to ${url}`); }, _ajaxRequest(options) { $.ajax(options); }, ajaxOptions(url, type, options) { let hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } let headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function(xhr) { Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key])); }; } return hash; }, parseErrorResponse(responseText) { let json = responseText; try { json = $.parseJSON(responseText); } catch (e) { // ignored } return json; }, normalizeErrorResponse(status, headers, payload) { if (payload && typeof payload === 'object' && payload.errors) { return payload.errors; } else { return [ { status: `${status}`, title: 'The backend responded with an error', detail: `${payload}` } ]; } }, generatedDetailedMessage(status, headers, payload, requestData) { let shortenedPayload; let payloadContentType = headers['Content-Type'] || 'Empty Content-Type'; if (payloadContentType === 'text/html' && payload.length > 250) { shortenedPayload = '[Omitted Lengthy HTML]'; } else { shortenedPayload = payload; } let requestDescription = `${requestData.method} ${requestData.url}`; let payloadDescription = `Payload (${payloadContentType})`; return [`Ember Data Request ${requestDescription} returned a ${status}`, payloadDescription, shortenedPayload].join('\n'); }, // @since 2.5.0 buildQuery(snapshot) { let query = {}; if (snapshot) { let { include } = snapshot; if (include) { query.include = include; } } return query; }, _hasCustomizedAjax() { if (this.ajax !== ElvisAdapter.prototype.ajax) { deprecate('ElvisAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax', until: '3.0.0' }); return true; } if (this.ajaxOptions !== ElvisAdapter.prototype.ajaxOptions) { deprecate('ElvisAdapter#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax-options', until: '3.0.0' }); return true; } return false; } }); if (isEnabled('ds-improved-ajax')) { ElvisAdapter.reopen({ dataForRequest(params) { let { store, type, snapshot, requestType, query } = params; // type is not passed to findBelongsTo and findHasMany type = type || (snapshot && snapshot.type); let serializer = store.serializerFor(type.modelName); let data = {}; switch (requestType) { case 'createRecord': serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); break; case 'updateRecord': serializer.serializeIntoHash(data, type, snapshot); break; case 'findRecord': data = this.buildQuery(snapshot); break; case 'findAll': if (params.sinceToken) { query = query || {}; query.since = params.sinceToken; } data = query; break; case 'query': case 'queryRecord': if (this.sortQueryParams) { query = this.sortQueryParams(query); } data = query; break; case 'findMany': data = { ids: params.ids }; break; default: data = undefined; break; } return data; }, methodForRequest(params) { let { requestType } = params; switch (requestType) { case 'createRecord': return 'POST'; case 'updateRecord': return 'PATCH'; case 'deleteRecord': return 'DELETE'; } return 'GET'; }, urlForRequest(params) { let { type, id, ids, snapshot, snapshots, requestType, query } = params; // type and id are not passed from updateRecord and deleteRecord, hence they // are defined if not set type = type || (snapshot && snapshot.type); id = id || (snapshot && snapshot.id); switch (requestType) { case 'findAll': return this.buildURL(type.modelName, null, snapshots, requestType); case 'query': case 'queryRecord': return this.buildURL(type.modelName, null, null, requestType, query); case 'findMany': return this.buildURL(type.modelName, ids, snapshots, requestType); case 'findHasMany': case 'findBelongsTo': { let url = this.buildURL(type.modelName, id, snapshot, requestType); return this.urlPrefix(params.url, url); } } return this.buildURL(type.modelName, id, snapshot, requestType, query); }, headersForRequest() { return this.get('headers'); }, _requestFor(params) { let method = this.methodForRequest(params); let url = this.urlForRequest(params); let headers = this.headersForRequest(params); let data = this.dataForRequest(params); return { method, url, headers, data }; }, _requestToJQueryAjaxHash(request) { let hash = {}; hash.type = request.method; hash.url = request.url; hash.dataType = 'json'; hash.context = this; if (request.data) { if (request.method !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(request.data); } else { hash.data = request.data; } } let { headers } = request; if (headers !== undefined) { hash.beforeSend = function(xhr) { Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key])); }; } return hash; }, _makeRequest(request) { let adapter = this; let hash = this._requestToJQueryAjaxHash(request); let { method, url } = request; let requestData = { method, url }; return new RSVP.Promise((resolve, reject) => { hash.success = function(payload, textStatus, jqXHR) { let response = ajaxSuccess(adapter, jqXHR, payload, requestData); run.join(null, resolve, response); }; hash.error = function(jqXHR, textStatus, errorThrown) { let responseData = { textStatus, errorThrown }; let error = ajaxError(adapter, jqXHR, requestData, responseData); run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, `DS: ElvisAdapter#makeRequest: ${method} ${url}`); } }); } function ajaxSuccess(adapter, jqXHR, payload, requestData) { let response; try { response = adapter.handleResponse( jqXHR.status, parseResponseHeaders(jqXHR.getAllResponseHeaders()), payload, requestData ); } catch (error) { return Promise.reject(error); } if (response && response.isAdapterError) { return Promise.reject(response); } else { return response; } } function ajaxError(adapter, jqXHR, requestData, responseData) { /*runInDebug(function() { let message = `The server returned an empty string for ${requestData.method} ${requestData.url}, which cannot be parsed into a valid JSON. Return either null or {}.`; let validJSONString = !(responseData.textStatus === 'parsererror' && jqXHR.responseText === ''); warn(message, validJSONString, { id: 'ds.adapter.returned-empty-string-as-JSON' }); });*/ let error; if (responseData.errorThrown instanceof Error) { error = responseData.errorThrown; } else if (responseData.textStatus === 'timeout') { error = new TimeoutError(); } else if (responseData.textStatus === 'abort' || jqXHR.status === 0) { error = new AbortError(); } else { try { error = adapter.handleResponse( jqXHR.status, parseResponseHeaders(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || responseData.errorThrown, requestData ); } catch (e) { error = $.parseJSON(jqXHR.responseText); } } return error; } // From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix) { if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } export default ElvisAdapter;
agpl-3.0
tommycli/mathim
src/main/scala/mathim/snippet/Snippets.scala
3041
package mathim.snippet import _root_.scala.xml.{NodeSeq, Text} import _root_.net.liftweb.util._ import _root_.net.liftweb.common._ import _root_.java.util.Date import _root_.net.liftweb.http import http._ import http.SHtml._ import http.js.JE._ import http.js.jquery.JqJsCmds._ import http.js.JsCmds._ import Helpers._ import net.liftweb.util.Mailer class Snippets { def chatRoom(in: NodeSeq) : NodeSeq = S.param("channelName") match { case Full(channelName) => { val id = Helpers.nextFuncName // unique comet actor per page load <lift:comet type="ChatClientComet" name={ id }> <comet:message></comet:message> </lift:comet> } case _ => S.redirectTo("/") // must have accessed "/chatRoom/" } val EmailRE = """(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b""".r def mail(in: NodeSeq) : NodeSeq = { var from = ""; var to = ""; var subject = ""; var htmlBody = ""; def isEmailValid(email: String) = EmailRE.pattern.matcher(email).matches def processForm() = { var allOkay = true; if(!isEmailValid(from)) { val fromFormatted = if(from.isEmpty) "(blank)" else from S.error("From e-mail address invalid: %s".format(fromFormatted)) allOkay = false } if(!isEmailValid(to)) { val toFormatted = if(to.isEmpty) "(blank)" else to S.error("To e-mail address invalid: %s".format(toFormatted)) allOkay = false } if(subject.isEmpty && htmlBody.isEmpty) { S.error("Both the subject and email body are empty") allOkay = false } import Mailer._ val totalBody = htmlBody + "<hr/>" + "Sent with <a href='http://mathim.com/'>MathIM</a>" val restArgs = List(XHTMLMailBodyType(scala.xml.Unparsed(totalBody)), To(to)) ++ (if(from==to) None else Some(BCC(from))).toList sendMail(From(from), Subject(subject), restArgs : _*) // expand arg list if(allOkay) { S.notice("Mail sent to: %s.".format(to)) S.notice("Check the \"From\" mailbox for a copy to verify.") Run("clearMailTo();") } else Noop } // We have two textareas assuming the mailTextBody will be transformed // and copied to mailHtmlBody by the javascript pre submission ajaxForm( <div class="mailForm"> <p><b>From:</b><br/> {text("", from = _, "class"->"mailFrom")} </p> <p><b>To:</b><br/> {text("", to = _, "class"->"mailTo")} </p> <p><b>Subject:</b><br/> {text("", subject = _, "class"->"mailSubject")} </p> <p><b>Body:</b> <lift:embed what="texbar"></lift:embed> {textarea("", ignore=>() , "class"->"mailTextBody", "rows"->"16")} {textarea("", htmlBody = _, "class"->"mailHtmlBody")} </p> <p>{ajaxSubmit("Send", processForm)}</p> </div> ) } }
agpl-3.0
CircleCode/dynacase-core
Action/Freedom/revcomment.php
1278
<?php /* * @author Anakeen * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License * @package FDL */ /** * Generated Header (not documented yet) * * @author Anakeen * @version $Id: revcomment.php,v 1.5 2005/06/28 08:37:46 eric Exp $ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License * @package FDL * @subpackage GED */ /** */ // --------------------------------------------------------------- // $Id: revcomment.php,v 1.5 2005/06/28 08:37:46 eric Exp $ // $Source: /home/cvsroot/anakeen/freedom/freedom/Action/Freedom/revcomment.php,v $ // --------------------------------------------------------------- include_once ("FDL/Class.Doc.php"); include_once ("FDL/Class.DocAttr.php"); function revcomment(&$action) { $dbaccess = $action->GetParam("FREEDOM_DB"); $docid = GetHttpVars("id", 0); $doc = new_Doc($dbaccess, $docid); $err = $doc->lock(true); // auto lock if ($err != "") $action->ExitError($err); $err = $doc->canEdit(); if ($err != "") $action->ExitError($err); $action->lay->Set("APP_TITLE", _($action->parent->description)); $action->lay->Set("title", $doc->title); $action->lay->Set("docid", $doc->id); } ?>
agpl-3.0
dcbh/kelsier
Kelsier.Common/ModuleList.cs
311
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kelsier.Common { public class ModuleList { static public ModuleList() { modules = new Dictionary<string, IModule>(); hooks = new Dictionary<string, Hook>(); } } }
agpl-3.0
tocco/tocco-client
packages/sso-login/src/components/ProviderButton/ProviderButton.js
1068
import PropTypes from 'prop-types' import React from 'react' import {Icon} from 'tocco-ui' import {openLoginWindow} from '../../utils/loginWindow' import StyledProviderButton from './StyledProviderButton' const ProviderButton = ({provider, loginCompleted, loginEndpoint}) => { const clickHandler = () => { openLoginWindow(loginEndpoint, loginCompleted, provider) } return ( <StyledProviderButton primaryColor={provider.button_primary_color} secondaryColor={provider.button_secondary_color} onClick={clickHandler} > {provider.button_icon && <Icon position="prepend" icon={provider.button_icon} />} <span>{provider.button_label}</span> </StyledProviderButton> ) } ProviderButton.propTypes = { provider: PropTypes.shape({ button_primary_color: PropTypes.string, button_secondary_color: PropTypes.string, button_icon: PropTypes.string, button_label: PropTypes.string }), loginEndpoint: PropTypes.string.isRequired, loginCompleted: PropTypes.func.isRequired } export default ProviderButton
agpl-3.0
loristissino/delt
protected/models/Account.php
23708
<?php /** * Account class file. * * @license http://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License * @author Loris Tissino <loris.tissino@gmail.com> * @copyright Copyright &copy; 2013-2017 Loris Tissino * @since 1.0 */ /** * Account represents a single account belonging to the chart of accounts of a {@link Firm}. * * @property integer $id * @property integer $account_parent_id the id of the parent account * @property integer $firm_id * @property integer $type 0=normal account, 1=main position (pancake format), 2=main position (two separate columns), 3=main position (analystic format), * @property integer $level * @property string $code * @property string $rcode * @property integer $is_selectable * @property integer $subchoices * @property string $position * @property string $outstanding_balance * @property string $l10n_names * @property string $textnames * @property string $currentname * @property integer $number_of_children * @property string $comment * @property string $classes * * The followings are the available model relations: * @property Firm $firm * @property Language[] $tblLanguages * @property Posting[] $postings * * * @package application.models * */ class Account extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return Account the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return '{{account}}'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('firm_id, code', 'required'), array('account_parent_id, firm_id, level, is_selectable, subchoices', 'numerical', 'integerOnly'=>true), array('code', 'length', 'max'=>16), array('comment', 'length', 'max'=>500), array('code', 'checkCode'), array('position', 'checkPosition'), array('comment', 'checkComment'), array('position,outstanding_balance', 'length', 'max'=>1), array('textnames', 'checkNames'), array('currentname', 'safe'), array('classes', 'safe'), array('type', 'safe'), array('subchoices', 'safe'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, account_parent_id, firm_id, level, code, is_selectable, position, outstanding_balance', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'firm' => array(self::BELONGS_TO, 'Firm', 'firm_id'), 'postings' => array(self::HAS_MANY, 'Posting', 'account_id'), 'journalentries' => array(self::MANY_MANY, 'Journalentry', '{{posting}}(account_id, journalentry_id)'), 'debitgrandtotal' => array(self::STAT, 'Posting', 'account_id', 'select'=>'SUM(amount)', 'join'=> 'INNER JOIN {{journalentry}} ON t.journalentry_id = {{journalentry}}.id', 'condition'=>'{{journalentry}}.is_included = 1 and {{journalentry}}.is_visible = 1 and amount > 0', ), 'creditgrandtotal' => array(self::STAT, 'Posting', 'account_id', 'select'=>'SUM(amount)', 'join'=> 'INNER JOIN {{journalentry}} ON t.journalentry_id = {{journalentry}}.id', 'condition'=>'{{journalentry}}.is_included = 1 and {{journalentry}}.is_visible = 1 and amount < 0', ), ); } public function getBalance() { return $this->debitgrandtotal + $this->creditgrandtotal; } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'account_parent_id' => 'Account Parent', 'firm_id' => 'Firm', 'level' => 'Level', 'code' => Yii::t('delt', 'Code'), 'is_selectable' => 'Is Selectable', 'subchoices' => Yii::t('delt', 'Subchoices'), 'type' => Yii::t('delt', 'Format'), 'position' => Yii::t('delt', 'Position'), 'outstanding_balance' => Yii::t('delt', 'Ordinary outstanding balance'), 'textnames' => Yii::t('delt', 'Localized names'), 'number_of_children' => Yii::t('delt', 'Number of children'), 'comment'=> Yii::t('delt', 'Comment'), ); } /** * @return array valid account positions (key=>label) */ public function validpositions($withUnpositioned=true) { $positions=$this->firm->getValidPositions(); if($withUnpositioned) { $positions['?'] = Yii::t('delt', 'Unknown'); } return $positions; } /** * @return array valid account positions */ public function getValidpositionByCode($code) { $positions=$this->validpositions(); return isset($positions[$code]) ? $positions[$code] : null; } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('account_parent_id',$this->account_parent_id); // $criteria->compare('name', $this->name); $criteria->compare('firm_id',$this->firm_id); $criteria->compare('level',$this->level); $criteria->compare('code',$this->code,true); $criteria->compare('is_selectable',$this->is_selectable); $criteria->compare('subchoices',$this->subchoices); $criteria->compare('type',$this->type); $criteria->compare('position',$this->position); $criteria->compare('outstanding_balance',$this->outstanding_balance,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * Retrieves the name of the account in the language of the firm (if available) * @return string the name of the account */ public function getName() { return $this->currentname; } public function getClosingDescription() { return Yii::t('delt', 'Closing entry for «{item}» accounts', array('{item}'=>$this->currentname)); } public function getParent() { return Account::model()->findByPk($this->account_parent_id); } public function __toString() { return sprintf('%s - %s', $this->code, $this->name); } public function getCodeAndName(Firm $firm=null, $for_comparisons=false) { if(!$firm) { $firm = $this->firm; } return $firm->renderAccountCodeAndName($firm->renderAccountCode($this->code), $this->name); } public function getCodeAndNameForComparison(Firm $firm) { return $firm->renderAccountCodeAndName($firm->renderAccountCode($this->code), strtolower($this->name), '/[^a-z0-9]/'); } public function getAnalysis($amount, $currency='EUR') { $parent = $this->getParent(); $balance = $amount>0?'D':'C'; $lookup=$parent? $parent: $this; // if we have a parent we look for information there, otherwise here // first, we try to find a description considering the outstanding balance $mpa = Account::model()->belongingTo($this->firm_id)->ofLevel(2, '>=')->hidden(1)->withPosition($this->position)->withOutstandingBalance($lookup->outstanding_balance)->find(); if(!$mpa) { // if we don't find it, we look for something without $mpa = Account::model()->belongingTo($this->firm_id)->ofLevel(2, '>=')->hidden(1)->withPosition($this->position)->withOutstandingBalance(null)->find(); } $m = $mpa? $mpa->currentname : 'unexplained entry'; $result=array(); $result['account']=$this->currentname; $result['classification']=$mpa? $mpa->currentname : Yii::t('delt', 'Unknown'); $result['type']= $this->hasOutstandingBalance() ? ($this->outstanding_balance == $lookup->outstanding_balance ? 'N': 'C') : 'n'; // normal vs contra account $result['change']= $this->hasOutstandingBalance() ? ($balance == $this->outstanding_balance ? 'I': 'D') :'n'; // increase vs decrease $result['value']=DELT::currency_value(abs($amount), $currency); return $result; } public function hasOutstandingBalance() { return in_array($this->outstanding_balance, array('D', 'C')); } public function sorted($order='code ASC') { $this->getDbCriteria()->mergeWith(array( 'order'=>$order, )); return $this; } public function belongingTo($firm_id, $order='code ASC') { $this->getDbCriteria()->mergeWith(array( 'condition'=>'t.firm_id = :firm_id', 'params'=>array(':firm_id'=>$firm_id), 'order'=>$order, )); return $this; } public function hidden($hidden) { $this->getDbCriteria()->mergeWith(array( 'condition'=>($hidden?'type <> 0':'type = 0'), )); return $this; } public function selectable($selectable) { $this->getDbCriteria()->mergeWith(array( 'condition'=>($selectable?'is_selectable <> 0':'is_selectable = 0'), )); return $this; } public function withOneOfTypes($in=array()) { $this->getDbCriteria()->addInCondition('type', $in); return $this; } public function ofLevel($level, $comparison='=') { $this->getDbCriteria()->mergeWith(array( 'condition'=>'t.level '. $comparison . ':level', 'params'=>array(':level'=>$level), )); return $this; } public function withPosition($position) { $this->getDbCriteria()->mergeWith(array( 'condition'=>'t.position = :position', 'params'=>array(':position' => $position), )); return $this; } public function withOutstandingBalance($balance=null) { if($balance) { $this->getDbCriteria()->mergeWith(array( 'condition'=>'t.outstanding_balance = "' . $balance .'"', )); } else { $this->getDbCriteria()->mergeWith(array( 'condition'=>'t.outstanding_balance is null', )); } return $this; } public function childrenOf($id) { $this->getDbCriteria()->mergeWith(array( 'condition'=>'t.account_parent_id = :id', 'params'=>array(':id'=>$id), )); return $this; } public function getNumberOfJournalentries() { return Posting::model()->countByAttributes(array('account_id'=>$this->id)); } /** * This method is invoked before deleting a record. * @return boolean whether the record should be deleted. Defaults to true. */ protected function beforeDelete() { if($this->getNumberOfJournalentries() > 0) { return false; } else return parent::beforeDelete(); } protected function _computeLevel() { $this->level = sizeof(explode('.', $this->code)); } protected function beforeSave() { $this->_computeLevel(); if($this->level > 1) { $parent = Account::model()->findByAttributes(array('firm_id'=>$this->firm_id, 'code'=>$this->getComputedParentCode())); if(!$parent) { $this->addError('code', Yii::t('delt', 'The parent account does not exist.')); return false; } $this->account_parent_id = $parent->id; } else { $this->account_parent_id = null; } if(!in_array($this->outstanding_balance, array('D', 'C'))) { $this->outstanding_balance = null; } if ($this->hasSubchoices()) { $this->subchoices = 2; } return parent::beforeSave(); } public function save($runValidation=true,$attributes=null) { $this->_computeRcode(); $this->setName(); try { parent::save($runValidation, $attributes); return true; } catch(Exception $e) { $this->addError('code', Yii::t('delt', 'This code is already in use.')); return false; } } public function basicSave($runValidation=true,$attributes=null) { $this->_computeRcode(); $this->setName(); try { return parent::save($runValidation, $attributes); } catch (Exception $e) { throw $e; } } /* * Computes a reversed code, that will be used for sorting accounts * in a children-to-parent order * */ private function _computeRcode() { $this->rcode = $this->code . str_repeat('~', max(0, 16-strlen($this->code))); } /* * Checks whether the code contains only valid characters * @return boolean true if the code is legal, false otherwise */ private function _codeContainsOnlyValidChars() { if($this->position=='?') { return !preg_match('/^[a-zA-Z0-9\.\!]*$/', $this->code); } return preg_match('/^[a-zA-Z0-9\.]*$/', $this->code); } public function setDefaultForNames(Firm $firm=null, $name='') { $languages = $this->firm->languages; $this->textnames = ''; { foreach($languages as $language) { $this->textnames .= $language->locale . ': '; if($firm && $language->id == $firm->language_id) { $this->textnames .= $name; } $this->textnames .= "\n"; } } $this->textnames = substr($this->textnames, 0, strlen($this->textnames)-1); } public function fixDefaultForNames() { if(!$this->textnames) { return $this->setDefaultForNames(); } $languages = $this->firm->languages; $names = $this->getNamesAsArray($languages); $this->textnames = ''; foreach($languages as $language) { $this->textnames .= $language->locale . ': '; if(isset($names[$language->locale])) { $this->textnames .= $names[$language->locale]; } $this->textnames .= "\n"; } $this->textnames = substr($this->textnames, 0, strlen($this->textnames)-1); } public function getNumberOfChildren() { return Account::model()->countByAttributes(array('account_parent_id'=>$this->id)); } public function getChildren() { return Account::model()->childrenOf($this->id)->sorted()->findAll(); } public function getParentAccount() { return Account::model()->findByPk($this->account_parent_id); } public function getComputedParentCode() { return substr($this->code, 0, strrpos($this->code, '.')); } public function setParentCode($value) { $this->code = $value . substr($this->code, strrpos($this->code, '.')); } public function getFirstAncestor() { $code = substr($this->code, 0, strpos($this->code, '.')); return Account::model()->findByAttributes(array('code'=>$code, 'firm_id'=>$this->firm_id)); } public function getIs_deletable() { return $this->number_of_children == 0; } public function getPostingsAsDataProvider() { return new CActiveDataProvider(Posting::model()->with('journalentry')->visible()->belongingTo($this->id), array( 'pagination'=>array( 'pageSize'=>30, ), ) ); } public function getPostings() { return Posting::model()->with('journalentry')->belongingTo($this->id)->notClosing()->findAll(); } public function checkCode() { if(!$this->_codeContainsOnlyValidChars()) { $this->addError('code', Yii::t('delt', 'The code contains illegal characters.')); } if(substr($this->code, -1, 1)=='.') { $this->addError('code', Yii::t('delt', 'The code cannot end with a dot.')); } $parent_code = $this->getComputedParentCode(); if($parent_code && !Account::model()->findByAttributes(array('firm_id'=>$this->firm_id, 'code'=>$parent_code))) { $this->addError('code', Yii::t('delt', 'The parent account, with code «{code}», does not exist.', array('{code}'=>$parent_code))); } } public function isHidden() { return $this->type != 0; } public function checkPosition() { if($this->position=='?' && substr($this->code, 0, 1)!='!') { $this->addError('position', Yii::t('delt', 'This position is allowed only for bang accounts.')); } if(!$this->isHidden()) { if(!$this->hasValidPosition()) { $this->addError('position', Yii::t('delt', 'Not a valid position.')); } } else { $this->_computeLevel(); if($this->level==1 and $this->position!=strtoupper($this->position)) { $this->addError('position', Yii::t('delt', 'The position code must be uppercase.')); } } } public function hasValidPosition() { return in_array(strtolower($this->position), array_map('strtolower', array_keys($this->firm->getValidPositions(array(1,2,3))))); } public function checkComment() { if($this->comment != strip_tags($this->comment)) { $this->addError('comment', Yii::t('delt', 'The text cannot contain HTML tags.')); } } public function checkNames() { if($this->textnames == '') { $this->setDefaultForNames($this->firm); $this->addError('textnames', Yii::t('delt', 'There must be at least one name for the account.')); return; } $names = $this->getNamesAsArray(); if(sizeof($names)==0) { $this->setDefaultForNames($this->firm, $this->textnames); $this->addError('textnames', Yii::t('delt', 'You cannot remove the locale (language code). It was put back.')); } } public function getConsolidatedBalance($without_closing=false, $subchoice='') { $amount = Yii::app()->db->createCommand() ->select('SUM(amount) as total') ->from('{{posting}} dc') ->leftJoin('{{account}} a', 'dc.account_id = a.id') ->leftJoin('{{journalentry}} p', 'dc.journalentry_id = p.id') ->where('a.code REGEXP "^' . $this->code .'"') ->andWhere($subchoice ? 'dc.subchoice = :subchoice': 'LENGTH(:subchoice)=0', array(':subchoice'=>$subchoice)) ->andWhere('p.firm_id = :id', array(':id'=>$this->firm_id)) ->andWhere($without_closing ? 'p.is_closing = 0': 'true') ->andWhere('p.is_included = 1') ->andWhere('p.is_visible = 1') ->queryScalar(); return $amount; } public function getNamesAsArray($languages=array()) { $result=array(); $temp=array(); foreach(explode("\n", str_replace("\r", "", $this->textnames)) as $line) { $info = explode(':', $line); if (sizeof($info)!=2) { continue; } $locale=trim($info[0]); $language = DELT::LocaleToLanguage($locale); $name=str_replace(array('#', '@', '§'), '', strip_tags(trim($info[1]))); $result[$locale]=$name; DELT::array_add_if_unset($temp, $language, $name); } foreach($languages as $language) { if(!array_key_exists($language->locale, $result)) { $result[$language->locale] = ''; } } foreach($result as $key=>&$value) { if(trim($value)=='') { $tl=DELT::LocaleToLanguage($key); if(isset($temp[$tl])) { $value=$temp[$tl]; } } } ksort($result); return $result; } public function setName() { $names=$this->getNamesAsArray(); if(array_key_exists($this->firm->language->getLocale(), $names) && $names[$this->firm->language->getLocale()]!='') { $this->currentname = str_replace('--', '—', $names[$this->firm->language->getLocale()]); } else { //$n = array_filter($names); // filters out empty values //$this->currentname = array_shift($n); // takes the first item of the array (we don't know the key) $this->currentname = str_replace("\n", '', $this->textnames); } } public function cleanup(Firm $firm) { $this->code = str_replace('!', '~', $this->id); unset($this->id); $this->currentname = trim(str_replace('!', '', $this->currentname)); $this->setDefaultForNames($firm, $this->currentname); } /** * Returns the path of an account, in terms of concatenated string of names * @param integer $id the account id to look for * @return string the path of the account */ public function getPath($id, $separator=':') { $items = array(); while ($account = Account::model()->findByPk($id)) { $items[] = $account->name; $id = $account->account_parent_id; } return implode($separator, array_reverse($items)); } public function getKeywordsAndValuesFromComment() { $result=array(0=>''); $matches = array(); foreach(explode("\n", $this->comment) as $line) { if(preg_match('/^@[a-z][^\ ]*/ ', $line, $matches)) { $keyword=$matches[0]; $value = trim(substr($line, strlen($keyword)+1)); $result[$keyword]=$value; } else { $result[0] .= $line; } } return $result; } public function getValueFromCommentByKeyword($keyword, $default=null) { $values=$this->getKeywordsAndValuesFromComment(); $with_locale = $keyword .'-' . $this->firm->language->locale; return isset($values[$with_locale]) ? $values[$with_locale] : (isset($values[$keyword]) ? $values[$keyword] : $default); } public function getSubchoices() { $kw = $this->getValueFromCommentByKeyword('@subchoices', ''); return array_filter(array_map('trim', explode(',', $kw))); } public function hasSubchoices() { return $this->getValueFromCommentByKeyword('@subchoices', '')!=''; } public function setClassesFromComment(Account $parent = null) { //FIXME This should be definitely done in a better way $text = $this->getValueFromCommentByKeyword('@classes'); $inherit = (strpos($text, '!')===false); // if we find an exclamation mark, we don't consider the parent's classes // otherwise, we inherit... $text=str_replace('!', '', $text); $values=array_flip(array_flip(explode(' ', trim(preg_replace('/\s+/', ' ', $text))))); // we remove double spaces and duplicates $newclasses = implode(' ', $values); if($parent && $inherit) { $newclasses = trim(implode(' ', array_merge($values, explode(' ', $parent->classes)))); } $this->classes=$newclasses; } public function searchAndReplaceOnNames($firm_id, $search, $replace) { $count = 0; foreach(Account::model()->belongingTo($firm_id)->findAll() as $account) { $lines=array(); foreach(explode("\n", $account->textnames) as $line) { $newname = @preg_replace($search, $replace, $line); if ($newname && $newname != $line) { $lines[]=$newname; } else { $lines[]=$line; } } $text = implode("\n", $lines); if ($text!=$account->textnames) { $account->textnames = $text; $account->save(true); $count++; } } return $count; } public static function getPostfix($subchoices) { switch ($subchoices) { case 1: return ' @'; case 2: return ' §'; default: return ''; } } }
agpl-3.0
FilotasSiskos/hopsworks
hopsworks-common/src/main/java/io/hops/hopsworks/common/jobs/CancellableJob.java
360
package io.hops.hopsworks.common.jobs; /** * Allows a job that has been submitted to be cancelled. The CancellableJob * is responsible of unregistering with the RunningJobTracker upon cancellation. */ public interface CancellableJob { /** * Cancel the running job. * <p/> * @throws Exception */ public void cancelJob() throws Exception; }
agpl-3.0
jitsni/k3po
driver/src/test/java/org/kaazing/robot/driver/behavior/handler/event/DisconnectedHandlerTest.java
14830
/* * Copyright (c) 2014 "Kaazing Corporation," (www.kaazing.com) * * This file is part of Robot. * * Robot 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/>. */ package org.kaazing.robot.driver.behavior.handler.event; import static java.lang.System.currentTimeMillis; import static org.jboss.netty.channel.ChannelState.CONNECTED; import static org.jboss.netty.channel.ChannelState.INTEREST_OPS; import static org.jboss.netty.channel.Channels.fireChannelBound; import static org.jboss.netty.channel.Channels.fireChannelClosed; import static org.jboss.netty.channel.Channels.fireChannelConnected; import static org.jboss.netty.channel.Channels.fireChannelDisconnected; import static org.jboss.netty.channel.Channels.fireChannelInterestChanged; import static org.jboss.netty.channel.Channels.fireChannelUnbound; import static org.jboss.netty.channel.Channels.fireExceptionCaught; import static org.jboss.netty.channel.Channels.fireMessageReceived; import static org.jboss.netty.channel.Channels.fireWriteComplete; import static org.jboss.netty.channel.Channels.pipeline; import static org.jboss.netty.channel.Channels.succeededFuture; import static org.jboss.netty.handler.timeout.IdleState.ALL_IDLE; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.ChildChannelStateEvent; import org.jboss.netty.channel.DefaultChildChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.WriteCompletionEvent; import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; import org.jboss.netty.channel.local.LocalAddress; import org.jboss.netty.handler.timeout.DefaultIdleStateEvent; import org.jboss.netty.handler.timeout.IdleStateEvent; import org.junit.Before; import org.junit.Test; import org.kaazing.robot.driver.jmock.Expectations; import org.kaazing.robot.driver.jmock.Mockery; import org.kaazing.robot.driver.behavior.handler.TestChannelEvent; import org.kaazing.robot.driver.behavior.handler.prepare.PreparationEvent; public class DisconnectedHandlerTest { private Mockery context; private ChannelUpstreamHandler upstream; private ChannelPipeline pipeline; private ChannelFactory channelFactory; private DisconnectedHandler handler; private boolean blockChannelOpen = true; @Before public void setUp() throws Exception { context = new Mockery() { { setThrowFirstErrorOnAssertIsSatisfied(true); } }; upstream = context.mock(ChannelUpstreamHandler.class); handler = new DisconnectedHandler(); pipeline = pipeline(new SimpleChannelHandler() { @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // block implicit channel open? if (!blockChannelOpen) { ctx.sendUpstream(e); } } }, handler, new SimpleChannelHandler() { @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { upstream.handleUpstream(ctx, e); super.handleUpstream(ctx, e); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { // prevent console error message } }); channelFactory = new DefaultLocalClientChannelFactory(); } @Test public void shouldPropagateUpstreamChildOpenedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(ChildChannelStateEvent.class))); } }); Channel parentChannel = channelFactory.newChannel(pipeline); Channel childChannel = channelFactory.newChannel(pipeline(new SimpleChannelUpstreamHandler())); // child channel is open pipeline.sendUpstream(new DefaultChildChannelStateEvent(parentChannel, childChannel)); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamChildClosedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(ChildChannelStateEvent.class))); } }); Channel parentChannel = channelFactory.newChannel(pipeline); Channel childChannel = channelFactory.newChannel(pipeline(new SimpleChannelUpstreamHandler())); childChannel.close().sync(); // child channel is closed pipeline.sendUpstream(new DefaultChildChannelStateEvent(parentChannel, childChannel)); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamInterestOpsEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(INTEREST_OPS))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelInterestChanged(channel); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamIdleStateEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(IdleStateEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); pipeline.sendUpstream(new DefaultIdleStateEvent(channel, ALL_IDLE, currentTimeMillis())); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamWriteCompletionEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(WriteCompletionEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); fireWriteComplete(channel, 1024); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamExceptionEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(ExceptionEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireExceptionCaught(channel, new Exception().fillInStackTrace()); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamUnknownEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(TestChannelEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); pipeline.sendUpstream(new TestChannelEvent(channel, succeededFuture(channel))); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamOpenedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); blockChannelOpen = false; channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamBoundEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelBound(channel, new LocalAddress("test")); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamConnectedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelConnected(channel, new LocalAddress("test")); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamMessageEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireMessageReceived(channel, new Object()); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamDisconnectedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelDisconnected(channel); assertTrue(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamUnboundEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelUnbound(channel); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamClosedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelClosed(channel); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamConnectedEventAfterFutureDone() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(same(CONNECTED), aNull(Object.class)))); } }); Channel channel = channelFactory.newChannel(pipeline); fireChannelDisconnected(channel); fireChannelDisconnected(channel); context.assertIsSatisfied(); } }
agpl-3.0
pietrosperoni/Vilfredo
recover__complete.php
337
<!-- pwd reset complete --> <h2>Password Reset Complete</h2> <p><span class="errorMessage"><?=$error_message?></span></p> <p>Hello <span class="user"><?=$user['username']?></span></p> <p>Your have successfully reset your password and logged in.</p> <p><a href="viewquestions.php">Click here to continue to the questions page</a></p>
agpl-3.0
medsob/Tanaguru
rules/accessiweb2.2/src/main/java/org/tanaguru/rules/accessiweb22/Aw22Rule07041.java
1500
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * 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/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.accessiweb22; import org.tanaguru.ruleimplementation.AbstractNotTestedRuleImplementation; /** * Implementation of the rule 7.4.1 of the referential Accessiweb 2.2. * <br/> * For more details about the implementation, refer to <a href="http://www.tanaguru.org/en/content/aw22-rule-7-4-1">the rule 7.4.1 design page.</a> * @see <a href="http://www.accessiweb.org/index.php/accessiweb-22-english-version.html#test-7-4-1"> 7.4.1 rule specification</a> * * @author jkowalczyk */ public class Aw22Rule07041 extends AbstractNotTestedRuleImplementation { /** * Default constructor */ public Aw22Rule07041 () { super(); } }
agpl-3.0
vtellez/MailTrack
app/controllers/ayuda.php
1361
<?php /* * Copyright 2010 Víctor Téllez Lozano <vtellez@us.es> * * This file is part of Seguimiento. * * Seguimiento 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. * * Seguimiento 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 Seguimiento. If not, see * <http://www.gnu.org/licenses/>. */ class Ayuda extends CI_Controller { function __construct() { parent::__construct(); } function index() { //Obtenemos la tabla de estados $this->db->order_by("codigo", "asc"); $estados = $this->db->get('estados'); $data = array( 'subtitulo' => 'Ayuda', 'controlador' => 'ayuda', 'estados' => $estados, 'parent' => '', ); $this->load->view('cabecera', $data); $this->load->view('ayuda.php'); $this->load->view('pie.php'); } }
agpl-3.0
ProximoSrl/Jarvis.DocumentStore
src/Jarvis.DocumentStore.Jobs/Jarvis.DocumentStore.Jobs.PdfConverter/Properties/AssemblyInfo.cs
1450
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplication1")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7318ff00-b255-40a0-b80a-3fecd379d4d0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
agpl-3.0
skavanagh/EC2Box
src/main/java/io/bastillion/manage/db/PrivateKeyDB.java
3061
/** * Copyright (C) 2013 Loophole, LLC * <p> * 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. * <p> * 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. * <p> * 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/>. * <p> * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ package io.bastillion.manage.db; import io.bastillion.manage.model.ApplicationKey; import io.bastillion.manage.util.DBUtils; import io.bastillion.manage.util.EncryptionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * DAO that returns public / private key for the system generated private key */ public class PrivateKeyDB { private static Logger log = LoggerFactory.getLogger(PrivateKeyDB.class); private PrivateKeyDB() { } /** * returns public private key for application * @return app key values */ public static ApplicationKey getApplicationKey() { ApplicationKey appKey = null; Connection con = null; try { con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("select * from application_key"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { appKey = new ApplicationKey(); appKey.setId(rs.getLong("id")); appKey.setPassphrase(EncryptionUtil.decrypt(rs.getString("passphrase"))); appKey.setPrivateKey(EncryptionUtil.decrypt(rs.getString("private_key"))); appKey.setPublicKey(rs.getString("public_key")); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); } catch (Exception e) { log.error(e.toString(), e); } finally { DBUtils.closeConn(con); } return appKey; } }
agpl-3.0
Linaro/lava-server
google_analytics/admin.py
306
from django.conf import settings from django.contrib import admin from google_analytics.models import Analytic class AnalyticAdmin(admin.ModelAdmin): list_display = ('site', 'analytics_code',) if getattr(settings, 'GOOGLE_ANALYTICS_MODEL', False): admin.site.register(Analytic, AnalyticAdmin)
agpl-3.0
datea/datea-webapp-react
src/components/dateo/index.js
315
import './dateo.scss'; import React from 'react'; import PropTypes from 'prop-types'; import DetailView from './detail-view'; import TeaserView from './teaser-view'; import DateoTeaserList from './dateo-teaser-list'; export {DetailView as DateoDetail}; export {TeaserView as DateoTeaser}; export {DateoTeaserList}
agpl-3.0
sgmap/pix
live/app/routes/assessments/rating.js
401
import Route from '@ember/routing/route'; export default Route.extend({ afterModel(assessment) { this.get('store').createRecord('assessment-result', { assessment }).save(); assessment.get('type') === 'CERTIFICATION' ? this.transitionTo('certifications.results', assessment.get('certificationNumber')) : this.transitionTo('assessments.results', assessment.get('id')); } });
agpl-3.0
Sina30/PHP-Fusion-9.00
locale/Danish/defender.php
3464
<?php $locale['validate'] = "Kontroller og gentag valideringen af feltet."; // Admin Login $locale['cookie_title'] = "Din session fik timeout"; $locale['cookie_description'] = "Valideringen kunne ikke gennemføres eller også har din session fået time out. Prøv at logge på igen."; $locale['cookie_expired'] = "Administrationscookien er udløbet. Log på igen."; $locale['password_invalid'] = "Forkert eller ubrugeligt kodeord"; $locale['password_invalid_description'] = "Kodeordet var forkert. Prøv igen."; $locale['cookie_error'] = "Fejl i forbindelse med cookie"; $locale['cookie_error_description'] = "Du skal tillade din browser at bruge cookies for at komme ind i administrationen."; $locale['validate_title'] = "Måske er der noget, du skal kontrollere!"; // Address errors $locale['street_error'] = "Adressen har fejl."; $locale['country_error'] = "Landeangivelsen har fejl."; $locale['state_error'] = "Distriktsangivelsen har fejl."; $locale['city_error'] = "Bynavnet har fejl."; $locale['postcode_error'] = "Postnummeret skal kontrolleres."; $locale['field_error_blank'] = "%s må ikke være tomt."; // Name errors $locale['firstname_error'] = "Fornavn skal kontrolleres."; $locale['lastname_error'] = "Efternavn skal kontrolleres."; $locale['name_error'] = "Fornavn og efternavn må ikke være identiske."; // Document errors $locale['doc_type_error'] = "Dokumenttypen skal kontrolleres."; $locale['doc_series_error'] = "Dokumentserien er fejlbehæftet."; $locale['doc_number_error'] = "Dokumentnummeret skal kontrolleres."; $locale['doc_authority_error'] = "Document authority requires attention."; $locale['date_issue_error'] = "Dokumentdatoen skal kontrolleres."; // Tokens $locale['token_error_title'] = "Fejl i forbindelse med token"; $locale['token_error'] = "Vi beklager, men vi er rendt ind i en fejl. Gå tilbage, genopfrisk siden og prøv igen."; $locale['token_error_1'] = "Din session blev ikke startet."; $locale['token_error_2'] = "Din token blev ikke gemt."; $locale['token_error_3'] = "Din token er forkert."; $locale['token_error_4'] = "Der er brugt et forkert brugernavn i forbindelse med din token."; $locale['token_error_5'] = "Datoen i din token er ikke anvendelig."; $locale['token_error_6'] = "Indklægget blev lavet for hurtigt."; $locale['token_error_7'] = "Der er brugt en forkert nøgle."; $locale['token_error_8'] = "Formatet for din token er forkert."; $locale['df_400'] = "%s indeholder ubrugelige karakterer."; $locale['df_401'] = "%s er ikke en gyldig mail adresse."; $locale['df_402'] = "%s er ikke et gyldigt kodeord."; $locale['df_403'] = "%s er ikke et gyldigt tal."; $locale['df_404'] = "%s er ikke en gyldig dato."; $locale['df_415'] = "Fejlagtigt filnavn."; $locale['df_416'] = "Din fil er for stor. Filer til upload skal være mindre end %s."; $locale['df_417'] = "Filtypen er ikke tilladt. Billedfiler skal være en af følgende typer: - %s"; $locale['df_418'] = "Filen er i orden, men den har et forbudt typenavn. Giv filen et nyt navn og prøv igen."; $locale['df_419'] = "Grafikfilen fik fejl i kontrollen. Lav en ny fil."; $locale['df_420'] = "Folderen eksisterer ikke. Lav folderen med din FTP-klient og prøv så igen."; $locale['df_421'] = "Billedet må ikke være større end %uw x %uh pixels."; $locale['df_422'] = "Ukendt fejl (Query)"; $locale['df_423'] = "Billedet blev ikke uploadet korrekt. Prøv igen"; $locale['df_error_text'] = "%s er fejlbehæftet og kræver din opmærksomhed."; ?>
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-admin/src/main/java/com/ephesoft/gxt/admin/client/event/BatchClassManagementMenuItemEnableEvent.java
2852
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft 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 EPHESOFT, EPHESOFT 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 Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * 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 "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.gxt.admin.client.event; import com.ephesoft.gxt.core.client.constant.PropertyAccessModel; import com.google.web.bindery.event.shared.binder.GenericEvent; public class BatchClassManagementMenuItemEnableEvent<T> extends GenericEvent { private PropertyAccessModel propertyAccessModel; private boolean isEnable; public BatchClassManagementMenuItemEnableEvent(PropertyAccessModel propertyAccessModel, boolean isEnable) { this.propertyAccessModel = propertyAccessModel; this.isEnable = isEnable; } public PropertyAccessModel getPropertyAccessModel() { return propertyAccessModel; } public void setPropertyAccessModel(PropertyAccessModel propertyAccessModel) { this.propertyAccessModel = propertyAccessModel; } public boolean isEnable() { return isEnable; } public void setEnable(boolean isEnable) { this.isEnable = isEnable; } }
agpl-3.0
editorsnotes/editorsnotes
editorsnotes/main/migrations/0013_auto_20151013_1155.py
1515
# -*- coding: utf-8 -*- from django.db import migrations, models import django.contrib.postgres.fields class Migration(migrations.Migration): dependencies = [ ('main', '0012_auto_20151013_1106'), ] operations = [ migrations.RemoveField( model_name='legacytopic', name='merged_into', ), migrations.RemoveField( model_name='topicnode', name='creator', ), migrations.RemoveField( model_name='topicnode', name='last_updater', ), migrations.RemoveField( model_name='topicnode', name='merged_into', ), migrations.AddField( model_name='topic', name='same_as', field=django.contrib.postgres.fields.ArrayField(default=list, base_field=models.URLField(), size=None), ), migrations.AddField( model_name='topic', name='types', field=django.contrib.postgres.fields.ArrayField(default=list, base_field=models.URLField(), size=None), ), migrations.AlterUniqueTogether( name='topic', unique_together=set([('project', 'preferred_name')]), ), migrations.DeleteModel( name='LegacyTopic', ), migrations.RemoveField( model_name='topic', name='topic_node', ), migrations.DeleteModel( name='TopicNode', ), ]
agpl-3.0
Minds/engine
Core/SEO/Sitemaps/Manager.php
3201
<?php namespace Minds\Core\SEO\Sitemaps; use Minds\Core\Config; use Minds\Core\Di\Di; use Spatie\Sitemap\SitemapGenerator; use Aws\S3\S3Client; class Manager { /** @var Config */ protected $config; /** @var SitemapGenerator */ protected $generator; /** @var S3 */ protected $s3; /** @var string */ protected $tmpOutputDirPath; protected $resolvers = [ Resolvers\MarketingResolver::class, Resolvers\DiscoveryResolver::class, Resolvers\ActivityResolver::class, Resolvers\UsersResolver::class, Resolvers\HelpdeskResolver::class, Resolvers\BlogsResolver::class, ]; public function __construct($config = null, $generator = null, $s3 = null) { $this->config = $config ?: Di::_()->get('Config'); $this->tmpOutputDirPath = $this->getOutputDir(); $this->generator = $generator ?: new \Icamys\SitemapGenerator\SitemapGenerator(substr($this->config->get('site_url'), 0, -1), $this->tmpOutputDirPath); $this->s3 = $s3 ?? new S3Client([ 'version' => '2006-03-01', 'region' => 'us-east-1' ]); } /** * Set the resolvers to user * @param array $resolvers * @return self */ public function setResolvers(array $resolvers): self { $this->resolvers = $resolvers; return $this; } /** * Build the sitemap * @return void */ public function build(): void { $this->generator->setSitemapFileName("sitemaps/sitemap.xml"); $this->generator->setSitemapIndexFileName("sitemaps/sitemap.xml"); $this->generator->setMaxURLsPerSitemap(50000); foreach ($this->resolvers as $resolver) { $resolver = is_object($resolver) ? $resolver : new $resolver; foreach ($resolver->getUrls() as $sitemapUrl) { $this->generator->addURL( $sitemapUrl->getLoc(), $sitemapUrl->getLastModified(), $sitemapUrl->getChangeFreq(), $sitemapUrl->getPriority() ); } } $this->generator->flush(); $this->generator->finalize(); // Upload to s3 $this->uploadToS3(); $this->generator->submitSitemap(); } /** * Get and make an output directory * @return string */ protected function getOutputDir(): string { $outputDir = sys_get_temp_dir() . '/' . uniqid(); mkdir($outputDir . '/sitemaps', 0700, true); return $outputDir; } /** * Uploads to S3 * @return void */ protected function uploadToS3(): void { $dir = $this->tmpOutputDirPath . '/sitemaps/'; $files = scandir($dir); foreach ($files as $file) { if ($file === '.' || $file === '..') { continue; } $this->s3->putObject([ 'ACL' => 'public-read', 'Bucket' => 'minds-sitemaps', 'Key' => "minds.com/$file", 'Body' => fopen($dir.$file, 'r'), ]); unlink($dir.$file); } rmdir($dir); } }
agpl-3.0
philanthropy-u/edx-platform
lms/djangoapps/onboarding/migrations/0016_auto_20180911_0305.py
614
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('onboarding', '0015_auto_20180809_0412'), ] operations = [ migrations.AddField( model_name='historicaluserextendedprofile', name='is_alquity_user', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userextendedprofile', name='is_alquity_user', field=models.BooleanField(default=False), ), ]
agpl-3.0
EaglesoftZJ/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/rpc/ResponseRawRequest.java
1587
package im.actor.core.api.rpc; /* * Generated by the Actor API Scheme generator. DO NOT EDIT! */ import im.actor.runtime.bser.*; import im.actor.runtime.collections.*; import static im.actor.runtime.bser.Utils.*; import im.actor.core.network.parser.*; import androidx.annotation.Nullable; import org.jetbrains.annotations.NotNull; import com.google.j2objc.annotations.ObjectiveCName; import java.io.IOException; import java.util.List; import java.util.ArrayList; import im.actor.core.api.*; public class ResponseRawRequest extends Response { public static final int HEADER = 0xa0a; public static ResponseRawRequest fromBytes(byte[] data) throws IOException { return Bser.parse(new ResponseRawRequest(), data); } private ApiRawValue result; public ResponseRawRequest(@NotNull ApiRawValue result) { this.result = result; } public ResponseRawRequest() { } @NotNull public ApiRawValue getResult() { return this.result; } @Override public void parse(BserValues values) throws IOException { this.result = ApiRawValue.fromBytes(values.getBytes(1)); } @Override public void serialize(BserWriter writer) throws IOException { if (this.result == null) { throw new IOException(); } writer.writeBytes(1, this.result.buildContainer()); } @Override public String toString() { String res = "tuple RawRequest{"; res += "}"; return res; } @Override public int getHeaderKey() { return HEADER; } }
agpl-3.0
kusumandaru/pa53
app/timesheet_details.php
113
<?php namespace App; use Illuminate\Database\Eloquent\Model; class timesheet_details extends Model { // }
agpl-3.0
mtucker6784/snipe-it
resources/lang/fil/admin/locations/table.php
2134
<?php return [ 'about_locations_title' => 'Ang Tungkol sa mga Lokasyon', 'about_locations' => 'Ang lokasyon ay ginagamit para magsubaybay sa lokasyon ng impormasyon para sa mga gumagamit, mga asset, at iba pang mga aytem', 'assets_rtd' => 'Ang mga asset', // This has NEVER meant Assets Retired. I don't know how it keeps getting reverted. 'assets_checkedout' => 'Ang Naktalagang mga Asset', 'id' => 'Ang ID', 'city' => 'Ang Siyudad', 'state' => 'Ang Estado', 'country' => 'Ang Bansa', 'create' => 'Magsagawa ng Lokasyon', 'update' => 'I-update ang Lokasyon', 'print_assigned' => 'Print Assigned', 'print_all_assigned' => 'Print All Assigned', 'name' => 'Ang Pangalan ng Lokasyon', 'address' => 'Ang Address', 'zip' => 'Ang Postal Code', 'locations' => 'Ang mga Lokasyon', 'parent' => 'Ang Pinagmulan', 'currency' => 'Ang Salapi ng Lugar', 'ldap_ou' => 'Ang LDAP Search OU', 'user_name' => 'User Name', 'department' => 'Department', 'location' => 'Location', 'asset_tag' => 'Assets Tag', 'asset_name' => 'Name', 'asset_category' => 'Category', 'asset_manufacturer' => 'Manufacturer', 'asset_model' => 'Model', 'asset_serial' => 'Serial', 'asset_location' => 'Location', 'asset_checked_out' => 'Checked Out', 'asset_expected_checkin' => 'Expected Checkin', 'date' => 'Date:', 'signed_by_asset_auditor' => 'Signed By (Asset Auditor):', 'signed_by_finance_auditor' => 'Signed By (Finance Auditor):', 'signed_by_location_manager' => 'Signed By (Location Manager):', 'signed_by' => 'Signed Off By:', ];
agpl-3.0
grafana/grafana
public/app/features/admin/ldap/LdapUserGroups.tsx
2294
import React, { FC } from 'react'; import { Tooltip, Icon } from '@grafana/ui'; import { LdapRole } from 'app/types'; interface Props { groups: LdapRole[]; showAttributeMapping?: boolean; } export const LdapUserGroups: FC<Props> = ({ groups, showAttributeMapping }) => { const items = showAttributeMapping ? groups : groups.filter((item) => item.orgRole); return ( <div className="gf-form-group"> <div className="gf-form"> <table className="filter-table form-inline"> <thead> <tr> {showAttributeMapping && <th>LDAP Group</th>} <th> Organization <Tooltip placement="top" content="Only the first match for an Organization will be used" theme={'info'}> <span className="gf-form-help-icon"> <Icon name="info-circle" /> </span> </Tooltip> </th> <th>Role</th> </tr> </thead> <tbody> {items.map((group, index) => { return ( <tr key={`${group.orgId}-${index}`}> {showAttributeMapping && ( <> <td>{group.groupDN}</td> {!group.orgRole && ( <> <td /> <td> <span className="text-warning"> No match <Tooltip placement="top" content="No matching groups found" theme={'info'}> <span className="gf-form-help-icon"> <Icon name="info-circle" /> </span> </Tooltip> </span> </td> </> )} </> )} {group.orgName && ( <> <td>{group.orgName}</td> <td>{group.orgRole}</td> </> )} </tr> ); })} </tbody> </table> </div> </div> ); };
agpl-3.0
KDE/ocs-webserver
application/modules/default/views/helpers/PrintDateSince.php
1754
<?php /** * ocs-webserver * * Copyright 2016 by pling GmbH. * * This file is part of ocs-webserver. * * 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/>. **/ class Default_View_Helper_PrintDateSince extends Zend_View_Helper_Abstract { public function printDateSince($strTime, $fromFormat='Y-m-d H:i:s') { if (empty($strTime)) { return null; } if(strtotime($strTime) == strtotime('0000-00-00 00:00:00')){ return ''; } $date = DateTime::createFromFormat($fromFormat, $strTime); $now = new DateTime(); $interval = $date->diff($now); $tokens = array( 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second' ); foreach ($tokens as $unit => $text) { if ($interval->$unit == 0) continue; return $interval->$unit . ' ' . $text .(($interval->$unit > 1) ? 's' : ''). ' ago'; } return null; } }
agpl-3.0
UM-USElab/gradecraft-development
db/migrate/20170613191442_remove_file_processing_columns.rb
398
class RemoveFileProcessingColumns < ActiveRecord::Migration[5.0] def change remove_column :assignment_files, :file_processing, :boolean remove_column :badge_files, :file_processing, :boolean remove_column :challenge_files, :file_processing, :boolean remove_column :file_uploads, :file_processing, :boolean remove_column :submission_files, :file_processing, :boolean end end
agpl-3.0
rockfruit/bika.lims
bika/lims/tests/test_calculations.py
21977
# This file is part of Bika LIMS # # Copyright 2011-2016 by it's authors. # Some rights reserved. See LICENSE.txt, AUTHORS.txt. from bika.lims import logger from bika.lims.content.analysis import Analysis from bika.lims.testing import BIKA_FUNCTIONAL_TESTING from bika.lims.tests.base import BikaFunctionalTestCase from bika.lims.utils.analysisrequest import create_analysisrequest from bika.lims.workflow import doActionFor from plone.app.testing import login, logout from plone.app.testing import TEST_USER_NAME from Products.CMFCore.utils import getToolByName import unittest try: import unittest2 as unittest except ImportError: # Python 2.7 import unittest class TestCalculations(BikaFunctionalTestCase): layer = BIKA_FUNCTIONAL_TESTING def setUp(self): super(TestCalculations, self).setUp() login(self.portal, TEST_USER_NAME) # Calculation: Total Hardness # Initial formula: [Ca] + [Mg] calcs = self.portal.bika_setup.bika_calculations self.calculation = [calcs[k] for k in calcs if calcs[k].title=='Total Hardness'][0] # Service with calculation: Tot. Hardness (THCaCO3) servs = self.portal.bika_setup.bika_analysisservices self.calcservice = [servs[k] for k in servs if servs[k].title=='Tot. Hardness (THCaCO3)'][0] self.calcservice.setUseDefaultCalculation(False) self.calcservice.setDeferredCalculation(self.calculation) # Analysis Services: Ca and Mg self.services = [servs[k] for k in servs if servs[k].getKeyword() in ('Ca', 'Mg')] # Allow Manual DLs for s in self.services: s.setLowerDetectionLimit('10') s.setUpperDetectionLimit('20') s.setDetectionLimitSelector(True) s.setAllowManualDetectionLimit(True) # Formulas to test # Ca and Mg detection Limits: LDL: 10, UDL: 20 self.formulas = [ {'formula' : '[Ca]+[Mg]', 'analyses': {'Ca':'10', 'Mg': '15'}, 'interims': {}, 'exresult': '25' }, {'formula' : '[Ca]+[Mg]', 'analyses': {'Ca':'-20', 'Mg': '5'}, 'interims': {}, 'exresult': '-15' }, {'formula' : '[Ca]+[Mg]+[IN1]', 'analyses': {'Ca': '10', 'Mg': '15'}, 'interims': {'IN1':'2'}, 'exresult': '27' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '5', 'Mg': '1'}, 'interims': {'IN1':'5'}, 'exresult': '15' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '10', 'Mg': '1'}, 'interims': {'IN1':'5'}, 'exresult': '16' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '10', 'Mg': '2'}, 'interims': {'IN1':'5'}, 'exresult': '17' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '15', 'Mg': '2'}, 'interims': {'IN1':'5'}, 'exresult': '22' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '15', 'Mg': '3'}, 'interims': {'IN1':'5'}, 'exresult': '23' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '20', 'Mg': '3'}, 'interims': {'IN1':'5'}, 'exresult': '28' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '20', 'Mg': '3'}, 'interims': {'IN1':'10'}, 'exresult': '33' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '30', 'Mg': '3'}, 'interims': {'IN1':'10'}, 'exresult': '50' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '>30', 'Mg': '5'}, 'interims': {'IN1':'10'}, 'exresult': '60' }, {'formula' : '([Ca]+[Ca.LDL]) if [Ca.BELOWLDL] else (([Ca.UDL] + [Ca]) if [Ca.ABOVEUDL] else [Ca.RESULT] + [Mg] + [IN1])', 'analyses': {'Ca': '<5', 'Mg': '5'}, 'interims': {'IN1':'10'}, 'exresult': '10' }, ] # New formulas for precision testing self.formulas_precision = [ {'formula' : '[Ca]/[Mg]', 'analyses': {'Ca':'10', 'Mg': '15'}, 'interims': {}, 'test_fixed_precision': [ {'fixed_precision': 5, 'expected_result': '0.66667', }, {'fixed_precision': 2, 'expected_result': '0.67' }, {'fixed_precision': 1, 'expected_result': '0.7' }, {'fixed_precision': 0, 'expected_result': '1' }, {'fixed_precision': -1, 'expected_result': '1' }, {'fixed_precision': -5, 'expected_result': '1' }, ], 'test_uncertainties_precision':[ {'uncertainties': [ {'intercept_min': 0, 'intercept_max': 10, 'errorvalue': 0.056}, ], 'expected_result': '0.67' }, {'uncertainties': [ {'intercept_min': 0.002, 'intercept_max': 20, 'errorvalue': 0.1} ], 'expected_result': '0.7' }, ], }, {'formula' : '[Ca]/[Mg]*[IN1]', 'analyses': {'Ca':'100', 'Mg': '20'}, 'interims': {'IN1':'0.12'}, 'test_fixed_precision': [ {'fixed_precision': 5, 'expected_result': '0.60000', }, {'fixed_precision': 2, 'expected_result': '0.60' }, {'fixed_precision': 1, 'expected_result': '0.6' }, {'fixed_precision': 0, 'expected_result': '1' }, {'fixed_precision': -1, 'expected_result': '1' }, {'fixed_precision': -5, 'expected_result': '1' }, ], 'test_uncertainties_precision':[ {'uncertainties': [ {'intercept_min': 0, 'intercept_max': 10, 'errorvalue': 0.1}, {'intercept_min': 11, 'intercept_max': 20, 'errorvalue': 0.056} ], 'expected_result': '0.6' }, {'uncertainties': [ {'intercept_min': 0.1, 'intercept_max': 0.6, 'errorvalue': 0.1}, {'intercept_min': 0.66, 'intercept_max': 20, 'errorvalue': 0.056} ], 'expected_result': '0.6', }, ], }, {'formula' : '[Ca]/[Mg]', 'analyses': {'Ca':'10', 'Mg': 1}, 'interims': {}, 'test_fixed_precision': [ {'fixed_precision': 5, 'expected_result': '10.00000', }, {'fixed_precision': 2, 'expected_result': '10.00' }, {'fixed_precision': 1, 'expected_result': '10.0' }, {'fixed_precision': 0, 'expected_result': '10' }, {'fixed_precision': -1, 'expected_result': '10' }, {'fixed_precision': -5, 'expected_result': '10' }, ], 'test_uncertainties_precision':[ {'uncertainties': [ {'intercept_min': 0, 'intercept_max': 10, 'errorvalue': 0.1}, {'intercept_min': 11, 'intercept_max': 20, 'errorvalue': 0.056} ], 'expected_result': '10.0' }, ], }, {'formula' : '[Ca]/[Mg]', 'analyses': {'Ca':'1', 'Mg': '20'}, 'interims': {}, 'test_fixed_precision': [ {'fixed_precision': 5, 'expected_result': '0.05000', }, {'fixed_precision': 2, 'expected_result': '0.05' }, {'fixed_precision': 1, 'expected_result': '0.1' }, {'fixed_precision': 0, 'expected_result': '0' }, {'fixed_precision': -1, 'expected_result': '0' }, {'fixed_precision': -5, 'expected_result': '0' }, ], 'test_uncertainties_precision':[ {'uncertainties': [ {'intercept_min': 0, 'intercept_max': 0.01, 'errorvalue': 0.01}, {'intercept_min': 11, 'intercept_max': 20, 'errorvalue': 0.056} ], 'expected_result': '0.05' }, ], }, ] def tearDown(self): # Service with calculation: Tot. Harndess (THCaCO3) self.calculation.setFormula('[Ca] + [Mg]') self.calcservice.setUseDefaultCalculation(True) # Allow Manual DLs for s in self.services: s.setLowerDetectionLimit('0') s.setUpperDetectionLimit('10000') s.setAllowManualDetectionLimit(False) super(TestCalculations, self).tearDown() def test_analysis_method_calculation(self): # Input results # Client: Happy Hills # SampleType: Apple Pulp # Contact: Rita Mohale # Analyses: [Calcium, Mg, Total Hardness] for f in self.formulas: # Set custom calculation self.calculation.setFormula(f['formula']) self.assertEqual(self.calculation.getFormula(), f['formula']) interims = [] for k,v in f['interims'].items(): interims.append({'keyword': k, 'title':k, 'value': v, 'hidden': False, 'type': 'int', 'unit': ''}); self.calculation.setInterimFields(interims) self.assertEqual(self.calculation.getInterimFields(), interims) # Create the AR client = self.portal.clients['client-1'] sampletype = self.portal.bika_setup.bika_sampletypes['sampletype-1'] values = {'Client': client.UID(), 'Contact': client.getContacts()[0].UID(), 'SamplingDate': '2015-01-01', 'SampleType': sampletype.UID()} request = {} services = [s.UID() for s in self.services] + [self.calcservice.UID()] ar = create_analysisrequest(client, request, values, services) wf = getToolByName(ar, 'portal_workflow') wf.doActionFor(ar, 'receive') # Set results and interims calcanalysis = None for an in ar.getAnalyses(): an = an.getObject() key = an.getKeyword() if key in f['analyses']: an.setResult(f['analyses'][key]) if an.isLowerDetectionLimit() \ or an.isUpperDetectionLimit(): operator = an.getDetectionLimitOperand() strres = f['analyses'][key].replace(operator, '') self.assertEqual(an.getResult(), str(float(strres))) else: self.assertEqual(an.getResult(), f['analyses'][key]) elif key == self.calcservice.getKeyword(): calcanalysis = an # Set interims interims = an.getInterimFields() intermap = [] for i in interims: if i['keyword'] in f['interims']: ival = float(f['interims'][i['keyword']]) intermap.append({'keyword': i['keyword'], 'value': ival, 'title': i['title'], 'hidden': i['hidden'], 'type': i['type'], 'unit': i['unit']}) else: intermap.append(i) an.setInterimFields(intermap) self.assertEqual(an.getInterimFields(), intermap) # Let's go.. calculate and check result calcanalysis.calculateResult(override=True, cascade=True) self.assertEqual(float(calcanalysis.getResult()), float(f['exresult'])) def test_calculation_fixed_precision(self): # Input results # Client: Happy Hills # SampleType: Apple Pulp # Contact: Rita Mohale # Analyses: [Calcium, Mg, Total Hardness] for f in self.formulas_precision: self.calculation.setFormula(f['formula']) self.assertEqual(self.calculation.getFormula(), f['formula']) interims = [] for k,v in f['interims'].items(): interims.append({'keyword': k, 'title':k, 'value': v, 'hidden': False, 'type': 'int', 'unit': ''}); self.calculation.setInterimFields(interims) self.assertEqual(self.calculation.getInterimFields(), interims) for case in f['test_fixed_precision']: # Define precision services_obj = [s for s in self.services] + [self.calcservice] for service in services_obj: service.setPrecision(case['fixed_precision']) # Create the AR client = self.portal.clients['client-1'] sampletype = self.portal.bika_setup.bika_sampletypes['sampletype-1'] values = {'Client': client.UID(), 'Contact': client.getContacts()[0].UID(), 'SamplingDate': '2015-01-01', 'SampleType': sampletype.UID()} request = {} services = [s.UID() for s in self.services] + [self.calcservice.UID()] ar = create_analysisrequest(client, request, values, services) wf = getToolByName(ar, 'portal_workflow') wf.doActionFor(ar, 'receive') # Set results and interims calcanalysis = None for an in ar.getAnalyses(): an = an.getObject() key = an.getKeyword() if key in f['analyses']: an.setResult(f['analyses'][key]) if an.isLowerDetectionLimit() \ or an.isUpperDetectionLimit(): operator = an.getDetectionLimitOperand() strres = f['analyses'][key].replace(operator, '') self.assertEqual(an.getResult(), str(float(strres))) else: # The analysis' results have to be always strings self.assertEqual(an.getResult(), str(f['analyses'][key])) elif key == self.calcservice.getKeyword(): calcanalysis = an # Set interims interims = an.getInterimFields() intermap = [] for i in interims: if i['keyword'] in f['interims']: ival = float(f['interims'][i['keyword']]) intermap.append({'keyword': i['keyword'], 'value': ival, 'title': i['title'], 'hidden': i['hidden'], 'type': i['type'], 'unit': i['unit']}) else: intermap.append(i) an.setInterimFields(intermap) self.assertEqual(an.getInterimFields(), intermap) # Let's go.. calculate and check result calcanalysis.calculateResult(override=True, cascade=True) self.assertEqual(calcanalysis.getFormattedResult(), case['expected_result']) def test_calculation_uncertainties_precision(self): # Input results # Client: Happy Hills # SampleType: Apple Pulp # Contact: Rita Mohale # Analyses: [Calcium, Mg, Total Hardness] for f in self.formulas_precision: self.calculation.setFormula(f['formula']) self.assertEqual(self.calculation.getFormula(), f['formula']) interims = [] for k,v in f['interims'].items(): interims.append({'keyword': k, 'title':k, 'value': v, 'hidden': False, 'type': 'int', 'unit': ''}); self.calculation.setInterimFields(interims) self.assertEqual(self.calculation.getInterimFields(), interims) for case in f['test_uncertainties_precision']: # Define precision services_obj = [s for s in self.services] + [self.calcservice] for service in services_obj: service.setPrecisionFromUncertainty(True) service.setUncertainties(case['uncertainties']) # Create the AR client = self.portal.clients['client-1'] sampletype = self.portal.bika_setup.bika_sampletypes['sampletype-1'] values = {'Client': client.UID(), 'Contact': client.getContacts()[0].UID(), 'SamplingDate': '2015-01-01', 'SampleType': sampletype.UID()} request = {} services = [s.UID() for s in self.services] + [self.calcservice.UID()] ar = create_analysisrequest(client, request, values, services) wf = getToolByName(ar, 'portal_workflow') wf.doActionFor(ar, 'receive') # Set results and interims calcanalysis = None for an in ar.getAnalyses(): an = an.getObject() key = an.getKeyword() if key in f['analyses']: an.setResult(f['analyses'][key]) if an.isLowerDetectionLimit() \ or an.isUpperDetectionLimit(): operator = an.getDetectionLimitOperand() strres = f['analyses'][key].replace(operator, '') self.assertEqual(an.getResult(), str(float(strres))) else: # The analysis' results have to be always strings self.assertEqual(an.getResult(), str(f['analyses'][key])) elif key == self.calcservice.getKeyword(): calcanalysis = an # Set interims interims = an.getInterimFields() intermap = [] for i in interims: if i['keyword'] in f['interims']: ival = float(f['interims'][i['keyword']]) intermap.append({'keyword': i['keyword'], 'value': ival, 'title': i['title'], 'hidden': i['hidden'], 'type': i['type'], 'unit': i['unit']}) else: intermap.append(i) an.setInterimFields(intermap) self.assertEqual(an.getInterimFields(), intermap) # Let's go.. calculate and check result calcanalysis.calculateResult(override=True, cascade=True) self.assertEqual(calcanalysis.getFormattedResult(), case['expected_result']) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestCalculations)) suite.layer = BIKA_FUNCTIONAL_TESTING return suite
agpl-3.0
songokas/manovalstybe_rss
libs/template.php
1792
<?php /* * Template loader class * * @author Tomas Jakstas * @license GNU AFFERO GENERAL PUBLIC LICENSE * @date 2010-10-01 */ class Template { public $template_dir ;//= APP_PATH.'/templates/'; public $template_ext = '.php'; public $template_main = 'template'; protected $tpl_arr = array(); private static $s_template; function __construct() { $this->template_dir = APP_PATH.'templates/'; } /** * retrieve class instance * @return <type> */ static function get_instance() { if ( ! self::$s_template ) self::$s_template = new Template(); return self::$s_template; } /** * load template using array keys as variables * @param <type> $name * @param <type> $var_array * @param <type> $return * @return <type> */ function load( $type, $name, $var_array, $return = false ) { global $config, $lang; $fullpath = $this->template_dir.$name.$this->template_ext; if ( file_exists($fullpath)) { if ( !is_array($var_array)) $var_array = (array)$var_array; ob_start(); extract($var_array); include $fullpath; $msg=ob_get_clean(); if ( $return ) return $msg; //if template exists append if ( isset($this->tpl_arr[$type]) ) $this->tpl_arr[$type] .= $msg; else $this->tpl_arr[$type] = $msg; } else { throw new Exception('file not found '.$fullpath); } } /** * render final output * @param <type> $return * @return <type> */ function render( $return = false ) { $arr = $this->tpl_arr; $this->tpl_arr = array(); if ( $return ) return $this->load('main_template', $this->template_main, $arr, true); echo $this->load('main_template', $this->template_main, $arr, true); } }
agpl-3.0
gnosygnu/xowa_android
_100_core/src/main/java/gplx/core/ios/streams/IoStream.java
505
package gplx.core.ios.streams; import gplx.*; import gplx.core.*; import gplx.core.ios.*; public interface IoStream extends Rls_able { Object UnderRdr(); Io_url Url(); long Pos(); long Len(); int ReadAry(byte[] array); int Read(byte[] array, int offset, int count); long Seek(long pos); void WriteAry(byte[] ary); void Write(byte[] array, int offset, int count); void Transfer(IoStream trg, int bufferLength); void Flush(); void Write_and_flush(byte[] bry, int bgn, int end); }
agpl-3.0
OCA/sale-workflow
sale_wishlist/models/__init__.py
52
from . import product_set from . import res_partner
agpl-3.0
elimence/edx-platform
lms/djangoapps/courseware/grades.py
16519
# Compute grades using real division, with no integer truncation from __future__ import division import random import logging from collections import defaultdict from django.conf import settings from django.contrib.auth.models import User from .model_data import ModelDataCache, LmsKeyValueStore from xblock.core import Scope from .module_render import get_module, get_module_for_descriptor from xmodule import graders from xmodule.capa_module import CapaModule from xmodule.graders import Score from .models import StudentModule log = logging.getLogger("mitx.courseware") def yield_module_descendents(module): stack = module.get_display_items() stack.reverse() while len(stack) > 0: next_module = stack.pop() stack.extend(next_module.get_display_items()) yield next_module def yield_dynamic_descriptor_descendents(descriptor, module_creator): """ This returns all of the descendants of a descriptor. If the descriptor has dynamic children, the module will be created using module_creator and the children (as descriptors) of that module will be returned. """ def get_dynamic_descriptor_children(descriptor): if descriptor.has_dynamic_children(): module = module_creator(descriptor) return module.get_child_descriptors() else: return descriptor.get_children() stack = [descriptor] while len(stack) > 0: next_descriptor = stack.pop() stack.extend(get_dynamic_descriptor_children(next_descriptor)) yield next_descriptor def yield_problems(request, course, student): """ Return an iterator over capa_modules that this student has potentially answered. (all that student has answered will definitely be in the list, but there may be others as well). """ grading_context = course.grading_context descriptor_locations = (descriptor.location.url() for descriptor in grading_context['all_descriptors']) existing_student_modules = set(StudentModule.objects.filter( module_state_key__in=descriptor_locations ).values_list('module_state_key', flat=True)) sections_to_list = [] for _, sections in grading_context['graded_sections'].iteritems(): for section in sections: section_descriptor = section['section_descriptor'] # If the student hasn't seen a single problem in the section, skip it. for moduledescriptor in section['xmoduledescriptors']: if moduledescriptor.location.url() in existing_student_modules: sections_to_list.append(section_descriptor) break model_data_cache = ModelDataCache(sections_to_list, course.id, student) for section_descriptor in sections_to_list: section_module = get_module(student, request, section_descriptor.location, model_data_cache, course.id) if section_module is None: # student doesn't have access to this module, or something else # went wrong. # log.debug("couldn't get module for student {0} for section location {1}" # .format(student.username, section_descriptor.location)) continue for problem in yield_module_descendents(section_module): if isinstance(problem, CapaModule): yield problem def answer_distributions(request, course): """ Given a course_descriptor, compute frequencies of answers for each problem: Format is: dict: (problem url_name, problem display_name, problem_id) -> (dict : answer -> count) TODO (vshnayder): this is currently doing a full linear pass through all students and all problems. This will be just a little slow. """ counts = defaultdict(lambda: defaultdict(int)) enrolled_students = User.objects.filter(courseenrollment__course_id=course.id) for student in enrolled_students: for capa_module in yield_problems(request, course, student): for problem_id in capa_module.lcp.student_answers: # Answer can be a list or some other unhashable element. Convert to string. answer = str(capa_module.lcp.student_answers[problem_id]) key = (capa_module.url_name, capa_module.display_name_with_default, problem_id) counts[key][answer] += 1 return counts def grade(student, request, course, model_data_cache=None, keep_raw_scores=False): """ This grades a student as quickly as possible. It returns the output from the course grader, augmented with the final letter grade. The keys in the output are: course: a CourseDescriptor - grade : A final letter grade. - percent : The final percent for the class (rounded up). - section_breakdown : A breakdown of each section that makes up the grade. (For display) - grade_breakdown : A breakdown of the major components that make up the final grade. (For display) - keep_raw_scores : if True, then value for key 'raw_scores' contains scores for every graded module More information on the format is in the docstring for CourseGrader. """ grading_context = course.grading_context raw_scores = [] if model_data_cache is None: model_data_cache = ModelDataCache(grading_context['all_descriptors'], course.id, student) totaled_scores = {} # This next complicated loop is just to collect the totaled_scores, which is # passed to the grader for section_format, sections in grading_context['graded_sections'].iteritems(): format_scores = [] for section in sections: section_descriptor = section['section_descriptor'] section_name = section_descriptor.display_name_with_default should_grade_section = False # If we haven't seen a single problem in the section, we don't have to grade it at all! We can assume 0% for moduledescriptor in section['xmoduledescriptors']: # some problems have state that is updated independently of interaction # with the LMS, so they need to always be scored. (E.g. foldit.) if moduledescriptor.always_recalculate_grades: should_grade_section = True break # Create a fake key to pull out a StudentModule object from the ModelDataCache key = LmsKeyValueStore.Key( Scope.user_state, student.id, moduledescriptor.location, None ) if model_data_cache.find(key): should_grade_section = True break if should_grade_section: scores = [] def create_module(descriptor): '''creates an XModule instance given a descriptor''' # TODO: We need the request to pass into here. If we could forego that, our arguments # would be simpler return get_module_for_descriptor(student, request, descriptor, model_data_cache, course.id) for module_descriptor in yield_dynamic_descriptor_descendents(section_descriptor, create_module): (correct, total) = get_score(course.id, student, module_descriptor, create_module, model_data_cache) if correct is None and total is None: continue if settings.GENERATE_PROFILE_SCORES: # for debugging! if total > 1: correct = random.randrange(max(total - 2, 1), total + 1) else: correct = total graded = module_descriptor.lms.graded if not total > 0: #We simply cannot grade a problem that is 12/0, because we might need it as a percentage graded = False scores.append(Score(correct, total, graded, module_descriptor.display_name_with_default)) _, graded_total = graders.aggregate_scores(scores, section_name) if keep_raw_scores: raw_scores += scores else: graded_total = Score(0.0, 1.0, True, section_name) #Add the graded total to totaled_scores if graded_total.possible > 0: format_scores.append(graded_total) else: log.exception("Unable to grade a section with a total possible score of zero. " + str(section_descriptor.location)) totaled_scores[section_format] = format_scores grade_summary = course.grader.grade(totaled_scores, generate_random_scores=settings.GENERATE_PROFILE_SCORES) # We round the grade here, to make sure that the grade is an whole percentage and # doesn't get displayed differently than it gets grades grade_summary['percent'] = round(grade_summary['percent'] * 100 + 0.05) / 100 letter_grade = grade_for_percentage(course.grade_cutoffs, grade_summary['percent']) grade_summary['grade'] = letter_grade grade_summary['totaled_scores'] = totaled_scores # make this available, eg for instructor download & debugging if keep_raw_scores: grade_summary['raw_scores'] = raw_scores # way to get all RAW scores out to instructor # so grader can be double-checked return grade_summary def grade_for_percentage(grade_cutoffs, percentage): """ Returns a letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None. Arguments - grade_cutoffs is a dictionary mapping a grade to the lowest possible percentage to earn that grade. - percentage is the final percent across all problems in a course """ letter_grade = None # Possible grades, sorted in descending order of score descending_grades = sorted(grade_cutoffs, key=lambda x: grade_cutoffs[x], reverse=True) for possible_grade in descending_grades: if percentage >= grade_cutoffs[possible_grade]: letter_grade = possible_grade break return letter_grade # TODO: This method is not very good. It was written in the old course style and # then converted over and performance is not good. Once the progress page is redesigned # to not have the progress summary this method should be deleted (so it won't be copied). def progress_summary(student, request, course, model_data_cache): """ This pulls a summary of all problems in the course. Returns - courseware_summary is a summary of all sections with problems in the course. It is organized as an array of chapters, each containing an array of sections, each containing an array of scores. This contains information for graded and ungraded problems, and is good for displaying a course summary with due dates, etc. Arguments: student: A User object for the student to grade course: A Descriptor containing the course to grade model_data_cache: A ModelDataCache initialized with all instance_modules for the student If the student does not have access to load the course module, this function will return None. """ # TODO: We need the request to pass into here. If we could forego that, our arguments # would be simpler course_module = get_module(student, request, course.location, model_data_cache, course.id, depth=None) if not course_module: # This student must not have access to the course. return None chapters = [] # Don't include chapters that aren't displayable (e.g. due to error) for chapter_module in course_module.get_display_items(): # Skip if the chapter is hidden if chapter_module.lms.hide_from_toc: continue sections = [] for section_module in chapter_module.get_display_items(): # Skip if the section is hidden if section_module.lms.hide_from_toc: continue # Same for sections graded = section_module.lms.graded scores = [] module_creator = section_module.system.get_module for module_descriptor in yield_dynamic_descriptor_descendents(section_module.descriptor, module_creator): course_id = course.id (correct, total) = get_score(course_id, student, module_descriptor, module_creator, model_data_cache) if correct is None and total is None: continue scores.append(Score(correct, total, graded, module_descriptor.display_name_with_default)) scores.reverse() section_total, _ = graders.aggregate_scores( scores, section_module.display_name_with_default) module_format = section_module.lms.format if section_module.lms.format is not None else '' sections.append({ 'display_name': section_module.display_name_with_default, 'url_name': section_module.url_name, 'scores': scores, 'section_total': section_total, 'format': module_format, 'due': section_module.lms.due, 'graded': graded, }) chapters.append({'course': course.display_name_with_default, 'display_name': chapter_module.display_name_with_default, 'url_name': chapter_module.url_name, 'sections': sections}) return chapters def get_score(course_id, user, problem_descriptor, module_creator, model_data_cache): """ Return the score for a user on a problem, as a tuple (correct, total). e.g. (5,7) if you got 5 out of 7 points. If this problem doesn't have a score, or we couldn't load it, returns (None, None). user: a Student object problem_descriptor: an XModuleDescriptor module_creator: a function that takes a descriptor, and returns the corresponding XModule for this user. Can return None if user doesn't have access, or if something else went wrong. cache: A ModelDataCache """ if not user.is_authenticated(): return (None, None) # some problems have state that is updated independently of interaction # with the LMS, so they need to always be scored. (E.g. foldit.) if problem_descriptor.always_recalculate_grades: problem = module_creator(problem_descriptor) score = problem.get_score() if score is not None: return (score['score'], score['total']) else: return (None, None) if not (problem_descriptor.stores_state and problem_descriptor.has_score): # These are not problems, and do not have a score return (None, None) # Create a fake KeyValueStore key to pull out the StudentModule key = LmsKeyValueStore.Key( Scope.user_state, user.id, problem_descriptor.location, None ) student_module = model_data_cache.find(key) if student_module is not None and student_module.max_grade is not None: correct = student_module.grade if student_module.grade is not None else 0 total = student_module.max_grade else: # If the problem was not in the cache, or hasn't been graded yet, # we need to instantiate the problem. # Otherwise, the max score (cached in student_module) won't be available problem = module_creator(problem_descriptor) if problem is None: return (None, None) correct = 0.0 total = problem.max_score() # Problem may be an error module (if something in the problem builder failed) # In which case total might be None if total is None: return (None, None) # Now we re-weight the problem, if specified weight = problem_descriptor.weight if weight is not None: if total == 0: log.exception("Cannot reweight a problem with zero total points. Problem: " + str(student_module)) return (correct, total) correct = correct * weight / total total = weight return (correct, total)
agpl-3.0
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/codehosting/sshserver/daemon.py
3390
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Glues the codehosting SSH daemon together.""" __metaclass__ = type __all__ = [ 'ACCESS_LOG_NAME', 'CodehostingAvatar', 'get_key_path', 'get_portal', 'LOG_NAME', 'make_portal', 'PRIVATE_KEY_FILE', 'PUBLIC_KEY_FILE', ] import os from twisted.conch.interfaces import ISession from twisted.conch.ssh import filetransfer from twisted.cred.portal import ( IRealm, Portal, ) from twisted.python import components from twisted.web.xmlrpc import Proxy from zope.interface import implements from lp.codehosting import sftp from lp.codehosting.sshserver.session import launch_smart_server from lp.services.config import config from lp.services.sshserver.auth import ( LaunchpadAvatar, PublicKeyFromLaunchpadChecker, ) # The names of the key files of the server itself. The directory itself is # given in config.codehosting.host_key_pair_path. PRIVATE_KEY_FILE = 'ssh_host_key_rsa' PUBLIC_KEY_FILE = 'ssh_host_key_rsa.pub' OOPS_CONFIG_SECTION = 'codehosting' LOG_NAME = 'codehosting' ACCESS_LOG_NAME = 'codehosting.access' class CodehostingAvatar(LaunchpadAvatar): """An SSH avatar specific to codehosting. :ivar codehosting_proxy: A Twisted XML-RPC client for the private XML-RPC server. The server must implement `ICodehostingAPI`. """ def __init__(self, user_dict, codehosting_proxy): LaunchpadAvatar.__init__(self, user_dict) self.codehosting_proxy = codehosting_proxy components.registerAdapter(launch_smart_server, CodehostingAvatar, ISession) components.registerAdapter( sftp.avatar_to_sftp_server, CodehostingAvatar, filetransfer.ISFTPServer) class Realm: implements(IRealm) def __init__(self, authentication_proxy, codehosting_proxy): self.authentication_proxy = authentication_proxy self.codehosting_proxy = codehosting_proxy def requestAvatar(self, avatar_id, mind, *interfaces): # Fetch the user's details from the authserver deferred = mind.lookupUserDetails( self.authentication_proxy, avatar_id) # Once all those details are retrieved, we can construct the avatar. def got_user_dict(user_dict): avatar = CodehostingAvatar(user_dict, self.codehosting_proxy) return interfaces[0], avatar, avatar.logout return deferred.addCallback(got_user_dict) def get_portal(authentication_proxy, codehosting_proxy): """Get a portal for connecting to Launchpad codehosting.""" portal = Portal(Realm(authentication_proxy, codehosting_proxy)) portal.registerChecker( PublicKeyFromLaunchpadChecker(authentication_proxy)) return portal def get_key_path(key_filename): key_directory = config.codehosting.host_key_pair_path return os.path.join(config.root, key_directory, key_filename) def make_portal(): """Create and return a `Portal` for the SSH service. This portal accepts SSH credentials and returns our customized SSH avatars (see `CodehostingAvatar`). """ authentication_proxy = Proxy( config.codehosting.authentication_endpoint) codehosting_proxy = Proxy(config.codehosting.codehosting_endpoint) return get_portal(authentication_proxy, codehosting_proxy)
agpl-3.0
bb010g/otouto
otouto/plugins/id.lua
2434
--[[ id.lua Returns usernames, IDs, and display names of given users. Copyright 2016 topkecleon <drew@otou.to> This code is licensed under the GNU AGPLv3. See /LICENSE for details. ]]-- local utilities = require('otouto.utilities') local id = {name = 'id'} function id:init() assert( self.named_plugins.users or self.named_plugins.administration, 'This plugin requires users.lua or administration.lua to be loaded first.' ) id.triggers = utilities.triggers(self.info.username, self.config.cmd_pat):t('id', true).table id.command = 'id <user>' id.doc = self.config.cmd_pat .. [[id <user> ... Returns the name, ID, and username (if applicable) for the given users. Arguments must be usernames and/or IDs. Input is also accepted via reply. If no input is given, returns info for the user. ]] end function id.format(t) if t.username then return string.format( '@%s, AKA <b>%s</b> <code>[%s]</code>.\n', t.username, utilities.html_escape(utilities.build_name(t.first_name, t.last_name)), t.id ) else return string.format( '<b>%s</b> <code>[%s]</code>.\n', utilities.html_escape(utilities.build_name(t.first_name, t.last_name)), t.id ) end end function id:action(msg) local output local input = utilities.input(msg.text) if msg.reply_to_message then output = id.format(msg.reply_to_message.from) elseif input then output = '' for user in input:gmatch('%g+') do if tonumber(user) then if self.database.users[user] then output = output .. id.format(self.database.users[user]) else output = output .. 'I don\'t recognize that ID (' .. user .. ').\n' end elseif user:match('^@') then local t = utilities.resolve_username(self, user) if t then output = output .. id.format(t) else output = output .. 'I don\'t recognize that username (' .. user .. ').\n' end else output = output .. 'Invalid username or ID (' .. user .. ').\n' end end else output = id.format(msg.from) end utilities.send_reply(msg, output, 'html') end return id
agpl-3.0
NullVoxPopuli/aeonvera
vendor/bundle/ruby/2.4.0/gems/dry-validation-0.11.0/spec/integration/schema/predicates/hash_spec.rb
1461
RSpec.describe 'Predicates: hash?' do shared_examples 'hash predicate' do context 'with valid input' do let(:input) { { foo: { a: 1 } } } it 'is successful' do expect(result).to be_successful end end context 'with nil input' do let(:input) { { foo: nil } } it 'is not successful' do expect(result).to be_failing ['must be a hash'] end end context 'with blank input' do let(:input) { { foo: '' } } it 'is not successful' do expect(result).to be_failing ['must be a hash'] end end context 'with invalid type' do let(:input) { { foo: 1 } } it 'is not successful' do expect(result).to be_failing ['must be a hash'] end end end context 'with required' do subject(:schema) do Dry::Validation.Schema do required(:foo) { hash? } end end it_behaves_like 'hash predicate' do context 'with missing input' do let(:input) { {} } it 'is not successful' do expect(result).to be_failing ['is missing'] end end end end context 'with optional' do subject(:schema) do Dry::Validation.Schema do optional(:foo) { hash? } end end it_behaves_like 'hash predicate' do let(:input) { {} } it 'is successful when key is no present' do expect(result).to be_successful end end end end
agpl-3.0
brosnanyuen/Project-S
Babylon.js-master/Exporters/3ds Max/Max2Babylon/Forms/LightPropertiesForm.Designer.cs
18204
namespace Max2Babylon { partial class LightPropertiesForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.butOK = new System.Windows.Forms.Button(); this.butCancel = new System.Windows.Forms.Button(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.grpAutoAnimate = new System.Windows.Forms.GroupBox(); this.chkLoop = new System.Windows.Forms.CheckBox(); this.nupTo = new System.Windows.Forms.NumericUpDown(); this.label4 = new System.Windows.Forms.Label(); this.nupFrom = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.chkAutoAnimate = new System.Windows.Forms.CheckBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.chkNoExport = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.grpBlurInfo = new System.Windows.Forms.GroupBox(); this.nupBlurBoxOffset = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.nupBlurScale = new System.Windows.Forms.NumericUpDown(); this.cbCameraType = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.nupBias = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.groupBox3.SuspendLayout(); this.grpAutoAnimate.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nupTo)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nupFrom)).BeginInit(); this.groupBox4.SuspendLayout(); this.groupBox1.SuspendLayout(); this.grpBlurInfo.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nupBlurBoxOffset)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nupBlurScale)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nupBias)).BeginInit(); this.SuspendLayout(); // // butOK // this.butOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.butOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.butOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.butOK.Location = new System.Drawing.Point(93, 454); this.butOK.Name = "butOK"; this.butOK.Size = new System.Drawing.Size(75, 23); this.butOK.TabIndex = 1; this.butOK.Text = "OK"; this.butOK.UseVisualStyleBackColor = true; this.butOK.Click += new System.EventHandler(this.butOK_Click); // // butCancel // this.butCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.butCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.butCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.butCancel.Location = new System.Drawing.Point(174, 454); this.butCancel.Name = "butCancel"; this.butCancel.Size = new System.Drawing.Size(75, 23); this.butCancel.TabIndex = 2; this.butCancel.Text = "Cancel"; this.butCancel.UseVisualStyleBackColor = true; // // groupBox3 // this.groupBox3.Controls.Add(this.grpAutoAnimate); this.groupBox3.Controls.Add(this.chkAutoAnimate); this.groupBox3.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox3.Location = new System.Drawing.Point(12, 284); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(319, 156); this.groupBox3.TabIndex = 5; this.groupBox3.TabStop = false; this.groupBox3.Text = "Animations"; // // grpAutoAnimate // this.grpAutoAnimate.Controls.Add(this.chkLoop); this.grpAutoAnimate.Controls.Add(this.nupTo); this.grpAutoAnimate.Controls.Add(this.label4); this.grpAutoAnimate.Controls.Add(this.nupFrom); this.grpAutoAnimate.Controls.Add(this.label5); this.grpAutoAnimate.Enabled = false; this.grpAutoAnimate.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.grpAutoAnimate.Location = new System.Drawing.Point(21, 51); this.grpAutoAnimate.Name = "grpAutoAnimate"; this.grpAutoAnimate.Size = new System.Drawing.Size(292, 99); this.grpAutoAnimate.TabIndex = 3; this.grpAutoAnimate.TabStop = false; // // chkLoop // this.chkLoop.AutoSize = true; this.chkLoop.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkLoop.Location = new System.Drawing.Point(9, 66); this.chkLoop.Name = "chkLoop"; this.chkLoop.Size = new System.Drawing.Size(47, 17); this.chkLoop.TabIndex = 5; this.chkLoop.Text = "Loop"; this.chkLoop.ThreeState = true; this.chkLoop.UseVisualStyleBackColor = true; // // nupTo // this.nupTo.Location = new System.Drawing.Point(47, 40); this.nupTo.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.nupTo.Name = "nupTo"; this.nupTo.Size = new System.Drawing.Size(120, 20); this.nupTo.TabIndex = 3; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 42); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(23, 13); this.label4.TabIndex = 4; this.label4.Text = "To:"; // // nupFrom // this.nupFrom.Location = new System.Drawing.Point(47, 14); this.nupFrom.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.nupFrom.Name = "nupFrom"; this.nupFrom.Size = new System.Drawing.Size(120, 20); this.nupFrom.TabIndex = 1; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(6, 16); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(33, 13); this.label5.TabIndex = 2; this.label5.Text = "From:"; // // chkAutoAnimate // this.chkAutoAnimate.AutoSize = true; this.chkAutoAnimate.Location = new System.Drawing.Point(21, 28); this.chkAutoAnimate.Name = "chkAutoAnimate"; this.chkAutoAnimate.Size = new System.Drawing.Size(88, 17); this.chkAutoAnimate.TabIndex = 0; this.chkAutoAnimate.Text = "Auto animate"; this.chkAutoAnimate.ThreeState = true; this.chkAutoAnimate.UseVisualStyleBackColor = true; this.chkAutoAnimate.CheckedChanged += new System.EventHandler(this.chkAutoAnimate_CheckedChanged); // // groupBox4 // this.groupBox4.Controls.Add(this.chkNoExport); this.groupBox4.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox4.Location = new System.Drawing.Point(12, 12); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(319, 59); this.groupBox4.TabIndex = 7; this.groupBox4.TabStop = false; this.groupBox4.Text = "Misc."; // // chkNoExport // this.chkNoExport.AutoSize = true; this.chkNoExport.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkNoExport.Location = new System.Drawing.Point(21, 28); this.chkNoExport.Name = "chkNoExport"; this.chkNoExport.Size = new System.Drawing.Size(87, 17); this.chkNoExport.TabIndex = 4; this.chkNoExport.Text = "Do not export"; this.chkNoExport.ThreeState = true; this.chkNoExport.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Controls.Add(this.grpBlurInfo); this.groupBox1.Controls.Add(this.nupBias); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.cbCameraType); this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox1.Location = new System.Drawing.Point(12, 77); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(319, 201); this.groupBox1.TabIndex = 6; this.groupBox1.TabStop = false; this.groupBox1.Text = "Shadows"; // // grpBlurInfo // this.grpBlurInfo.Controls.Add(this.nupBlurBoxOffset); this.grpBlurInfo.Controls.Add(this.label3); this.grpBlurInfo.Controls.Add(this.nupBlurScale); this.grpBlurInfo.Controls.Add(this.label2); this.grpBlurInfo.Enabled = false; this.grpBlurInfo.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.grpBlurInfo.Location = new System.Drawing.Point(21, 108); this.grpBlurInfo.Name = "grpBlurInfo"; this.grpBlurInfo.Size = new System.Drawing.Size(292, 87); this.grpBlurInfo.TabIndex = 13; this.grpBlurInfo.TabStop = false; this.grpBlurInfo.Text = "Blur info"; // // nupBlurBoxOffset // this.nupBlurBoxOffset.Location = new System.Drawing.Point(89, 50); this.nupBlurBoxOffset.Maximum = new decimal(new int[] { 3, 0, 0, 0}); this.nupBlurBoxOffset.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.nupBlurBoxOffset.Name = "nupBlurBoxOffset"; this.nupBlurBoxOffset.Size = new System.Drawing.Size(120, 20); this.nupBlurBoxOffset.TabIndex = 13; this.nupBlurBoxOffset.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 52); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(77, 13); this.label3.TabIndex = 14; this.label3.Text = "Blur box offset:"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(21, 55); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(34, 13); this.label6.TabIndex = 8; this.label6.Text = "Type:"; // // nupBlurScale // this.nupBlurScale.Location = new System.Drawing.Point(89, 24); this.nupBlurScale.Maximum = new decimal(new int[] { 10, 0, 0, 0}); this.nupBlurScale.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.nupBlurScale.Name = "nupBlurScale"; this.nupBlurScale.Size = new System.Drawing.Size(120, 20); this.nupBlurScale.TabIndex = 11; this.nupBlurScale.Value = new decimal(new int[] { 1, 0, 0, 0}); // // cbCameraType // this.cbCameraType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbCameraType.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cbCameraType.FormattingEnabled = true; this.cbCameraType.Items.AddRange(new object[] { "Hard shadows", "Poisson Sampling", "Variance", "Blurred Variance"}); this.cbCameraType.Location = new System.Drawing.Point(24, 71); this.cbCameraType.Name = "cbCameraType"; this.cbCameraType.Size = new System.Drawing.Size(289, 21); this.cbCameraType.TabIndex = 7; this.cbCameraType.SelectedIndexChanged += new System.EventHandler(this.cbCameraType_SelectedIndexChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 26); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 13); this.label2.TabIndex = 12; this.label2.Text = "Blur scale:"; // // nupBias // this.nupBias.DecimalPlaces = 5; this.nupBias.Location = new System.Drawing.Point(57, 26); this.nupBias.Maximum = new decimal(new int[] { 1, 0, 0, 0}); this.nupBias.Name = "nupBias"; this.nupBias.Size = new System.Drawing.Size(120, 20); this.nupBias.TabIndex = 9; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(21, 28); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(30, 13); this.label1.TabIndex = 10; this.label1.Text = "Bias:"; // // LightPropertiesForm // this.AcceptButton = this.butOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.butCancel; this.ClientSize = new System.Drawing.Size(343, 489); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox4); this.Controls.Add(this.groupBox3); this.Controls.Add(this.butCancel); this.Controls.Add(this.butOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "LightPropertiesForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Babylon.js - Light Properties"; this.Load += new System.EventHandler(this.LightPropertiesForm_Load); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.grpAutoAnimate.ResumeLayout(false); this.grpAutoAnimate.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nupTo)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nupFrom)).EndInit(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.grpBlurInfo.ResumeLayout(false); this.grpBlurInfo.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nupBlurBoxOffset)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nupBlurScale)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nupBias)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button butOK; private System.Windows.Forms.Button butCancel; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox grpAutoAnimate; private System.Windows.Forms.CheckBox chkLoop; private System.Windows.Forms.NumericUpDown nupTo; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown nupFrom; private System.Windows.Forms.Label label5; private System.Windows.Forms.CheckBox chkAutoAnimate; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.CheckBox chkNoExport; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cbCameraType; private System.Windows.Forms.NumericUpDown nupBlurScale; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown nupBias; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox grpBlurInfo; private System.Windows.Forms.NumericUpDown nupBlurBoxOffset; private System.Windows.Forms.Label label3; } }
agpl-3.0
ushahidi/SwiftRiver
themes/default/views/pages/login/main.php
3430
<div id="content"> <div class="center"> <article class="modal"> <hgroup class="page-title modal-title cf"> <a href="#" class="modal-close button-white"><i class="icon-cancel"></i>Close</a> <h1><i class="icon-login"></i><?php echo __('Get Started'); ?></h1> </hgroup> <div class="modal-body modal-tabs-container"> <div class="base"> <ul class="modal-tabs-menu"> <li class="<?php echo 'login'== $active ? 'active' : ''; ?>"> <a href="#login"><span class="label"><?php echo __("Current users"); ?></span></a> </li> <li class="<?php echo 'register'== $active ? 'active' : ''; ?>"> <a href="#signup"><span class="label"><?php echo __("New users"); ?></span></a> </li> </ul> <div class="modal-tabs-window"> <!-- Log in --> <div id="login" class="<?php echo 'login'== $active ? 'active' : ''; ?>"> <?php echo Form::open(URL::site('login', TRUE)); ?> <div class="modal-field"> <h3 class="label"><?php echo __("Email address"); ?></h3> <?php echo Form::input("username", "", array("placeholder" => "Email")); ?> </div> <div class="modal-field"> <h3 class="label"><?php echo __("Password"); ?></h3> <?php echo Form::password("password", "", array('placeholder' => 'Password')); ?> </div> <div class="modal-field"> <?php echo Form::checkbox('remember', 1); ?> <?php echo __('Remember me'); ?> </div> <div class="modal-base-toolbar"> <a href="#" class="button-submit button-primary modal-close" onclick="submitForm(this); return false;">Log in</a> <a href="<?php echo URL::site('login/forgot_password', TRUE); ?>" class="button-destruct button-secondary modal-transition">Forgot your password?</a> </div> <?php echo Form::hidden('referrer', $referrer); ?> <?php echo Form::close(); ?> </div> <!-- Sign up --> <div id="signup" class="<?php echo 'register'== $active ? 'active' : ''; ?>"> <?php echo Form::open(URL::site('login/register')); ?> <div class="modal-field"> <h3 class="label">Name</h3> <?php echo Form::input("fullname", isset($fullname) ? $fullname : '', array("placeholder" => "Full name")); ?> </div> <div class="modal-field"> <h3 class="label">Email</h3> <?php echo Form::input("email", isset($email) ? $email : '', array("placeholder" => "Email")); ?> </div> <div class="modal-field"> <h3 class="label">Username</h3> <?php echo Form::input("username", isset($username) ? $username : '', array("placeholer" => "Username")); ?> </div> <div class="modal-field"> <h3 class="label">Create your password</h3> <?php echo Form::password("password", "", array('placeholder' => 'Password')); ?> </div> <div class="modal-field"> <h3 class="label">Confirm your password</h3> <?php echo Form::password("password_confirm", "", array('placeholder' => 'Confirm password')); ?> </div> <div class="modal-base-toolbar"> <a href="#" class="button-submit button-primary modal-close" onclick="submitForm(this); return false;">Create account and log in</a> </div> <?php echo Form::close(); ?> </div> </div> </div> </div> </article> </div> </div>
agpl-3.0
mjs/juju
cmd/juju/commands/sshkeys_test.go
6590
// Copyright 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package commands import ( "fmt" "strings" "github.com/juju/cmd/cmdtesting" jc "github.com/juju/testing/checkers" sshtesting "github.com/juju/utils/ssh/testing" gc "gopkg.in/check.v1" keymanagerserver "github.com/juju/juju/apiserver/keymanager" keymanagertesting "github.com/juju/juju/apiserver/keymanager/testing" "github.com/juju/juju/juju/osenv" jujutesting "github.com/juju/juju/juju/testing" coretesting "github.com/juju/juju/testing" ) type SSHKeysSuite struct { coretesting.FakeJujuXDGDataHomeSuite } var _ = gc.Suite(&SSHKeysSuite{}) func (s *SSHKeysSuite) assertHelpOutput(c *gc.C, cmd, args string) { if args != "" { args = " " + args } expected := fmt.Sprintf("Usage: juju %s [options]%s", cmd, args) out := badrun(c, 0, cmd, "--help") lines := strings.Split(out, "\n") c.Assert(lines[0], gc.Equals, expected) } func (s *SSHKeysSuite) TestHelpList(c *gc.C) { s.assertHelpOutput(c, "ssh-keys", "") } func (s *SSHKeysSuite) TestHelpAdd(c *gc.C) { s.assertHelpOutput(c, "add-ssh-key", "<ssh key> ...") } func (s *SSHKeysSuite) TestHelpRemove(c *gc.C) { s.assertHelpOutput(c, "remove-ssh-key", "<ssh key id> ...") } func (s *SSHKeysSuite) TestHelpImport(c *gc.C) { s.assertHelpOutput(c, "import-ssh-key", "<lp|gh>:<user identity> ...") } type keySuiteBase struct { jujutesting.JujuConnSuite coretesting.CmdBlockHelper } func (s *keySuiteBase) SetUpSuite(c *gc.C) { s.JujuConnSuite.SetUpSuite(c) s.PatchEnvironment(osenv.JujuModelEnvKey, "controller") } func (s *keySuiteBase) SetUpTest(c *gc.C) { s.JujuConnSuite.SetUpTest(c) s.CmdBlockHelper = coretesting.NewCmdBlockHelper(s.APIState) c.Assert(s.CmdBlockHelper, gc.NotNil) s.AddCleanup(func(*gc.C) { s.CmdBlockHelper.Close() }) } func (s *keySuiteBase) setAuthorizedKeys(c *gc.C, keys ...string) { keyString := strings.Join(keys, "\n") err := s.State.UpdateModelConfig(map[string]interface{}{"authorized-keys": keyString}, nil) c.Assert(err, jc.ErrorIsNil) envConfig, err := s.State.ModelConfig() c.Assert(err, jc.ErrorIsNil) c.Assert(envConfig.AuthorizedKeys(), gc.Equals, keyString) } func (s *keySuiteBase) assertEnvironKeys(c *gc.C, expected ...string) { envConfig, err := s.State.ModelConfig() c.Assert(err, jc.ErrorIsNil) keys := envConfig.AuthorizedKeys() c.Assert(keys, gc.Equals, strings.Join(expected, "\n")) } type ListKeysSuite struct { keySuiteBase } var _ = gc.Suite(&ListKeysSuite{}) func (s *ListKeysSuite) TestListKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key + " another@host" s.setAuthorizedKeys(c, key1, key2) context, err := cmdtesting.RunCommand(c, NewListKeysCommand()) c.Assert(err, jc.ErrorIsNil) output := strings.TrimSpace(cmdtesting.Stdout(context)) c.Assert(err, jc.ErrorIsNil) c.Assert(output, gc.Matches, "Keys used in model: controller\n.*\\(user@host\\)\n.*\\(another@host\\)") } func (s *ListKeysSuite) TestListFullKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key + " another@host" s.setAuthorizedKeys(c, key1, key2) context, err := cmdtesting.RunCommand(c, NewListKeysCommand(), "--full") c.Assert(err, jc.ErrorIsNil) output := strings.TrimSpace(cmdtesting.Stdout(context)) c.Assert(err, jc.ErrorIsNil) c.Assert(output, gc.Matches, "Keys used in model: controller\n.*user@host\n.*another@host") } func (s *ListKeysSuite) TestTooManyArgs(c *gc.C) { _, err := cmdtesting.RunCommand(c, NewListKeysCommand(), "foo") c.Assert(err, gc.ErrorMatches, `unrecognized args: \["foo"\]`) } type AddKeySuite struct { keySuiteBase } var _ = gc.Suite(&AddKeySuite{}) func (s *AddKeySuite) TestAddKey(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" s.setAuthorizedKeys(c, key1) key2 := sshtesting.ValidKeyTwo.Key + " another@host" context, err := cmdtesting.RunCommand(c, NewAddKeysCommand(), key2, "invalid-key") c.Assert(err, jc.ErrorIsNil) c.Assert(cmdtesting.Stderr(context), gc.Matches, `cannot add key "invalid-key".*\n`) s.assertEnvironKeys(c, key1, key2) } func (s *AddKeySuite) TestBlockAddKey(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" s.setAuthorizedKeys(c, key1) key2 := sshtesting.ValidKeyTwo.Key + " another@host" // Block operation s.BlockAllChanges(c, "TestBlockAddKey") _, err := cmdtesting.RunCommand(c, NewAddKeysCommand(), key2, "invalid-key") coretesting.AssertOperationWasBlocked(c, err, ".*TestBlockAddKey.*") } type RemoveKeySuite struct { keySuiteBase } var _ = gc.Suite(&RemoveKeySuite{}) func (s *RemoveKeySuite) TestRemoveKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key + " another@host" s.setAuthorizedKeys(c, key1, key2) context, err := cmdtesting.RunCommand(c, NewRemoveKeysCommand(), sshtesting.ValidKeyTwo.Fingerprint, "invalid-key") c.Assert(err, jc.ErrorIsNil) c.Assert(cmdtesting.Stderr(context), gc.Matches, `cannot remove key id "invalid-key".*\n`) s.assertEnvironKeys(c, key1) } func (s *RemoveKeySuite) TestBlockRemoveKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key + " another@host" s.setAuthorizedKeys(c, key1, key2) // Block operation s.BlockAllChanges(c, "TestBlockRemoveKeys") _, err := cmdtesting.RunCommand(c, NewRemoveKeysCommand(), sshtesting.ValidKeyTwo.Fingerprint, "invalid-key") coretesting.AssertOperationWasBlocked(c, err, ".*TestBlockRemoveKeys.*") } type ImportKeySuite struct { keySuiteBase } var _ = gc.Suite(&ImportKeySuite{}) func (s *ImportKeySuite) SetUpTest(c *gc.C) { s.keySuiteBase.SetUpTest(c) s.PatchValue(&keymanagerserver.RunSSHImportId, keymanagertesting.FakeImport) } func (s *ImportKeySuite) TestImportKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" s.setAuthorizedKeys(c, key1) context, err := cmdtesting.RunCommand(c, NewImportKeysCommand(), "lp:validuser", "lp:invalid-key") c.Assert(err, jc.ErrorIsNil) c.Assert(cmdtesting.Stderr(context), gc.Matches, `cannot import key id "lp:invalid-key".*\n`) s.assertEnvironKeys(c, key1, sshtesting.ValidKeyThree.Key) } func (s *ImportKeySuite) TestBlockImportKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" s.setAuthorizedKeys(c, key1) // Block operation s.BlockAllChanges(c, "TestBlockImportKeys") _, err := cmdtesting.RunCommand(c, NewImportKeysCommand(), "lp:validuser", "lp:invalid-key") coretesting.AssertOperationWasBlocked(c, err, ".*TestBlockImportKeys.*") }
agpl-3.0
a-gogo/agogo
AMW_maia_federation/src/test/java/ch/puzzle/itc/mobiliar/maiafederationservice/usecasetests/MaiaAmwFederationServiceUseCase7IntegrationTest.java
17031
/* * AMW - Automated Middleware allows you to manage the configurations of * your Java EE applications on an unlimited number of different environments * with various versions, including the automated deployment of those apps. * Copyright (C) 2013-2016 by Puzzle ITC * * 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/>. */ package ch.puzzle.itc.mobiliar.maiafederationservice.usecasetests; import ch.mobi.xml.datatype.ch.mobi.maia.amw.maiaamwfederationservicetypes.v1_0.UpdateResponse; import ch.mobi.xml.datatype.common.commons.v3.MessageSeverity; import ch.mobi.xml.service.ch.mobi.maia.amw.maiaamwfederationservice.v1_0.BusinessException; import ch.mobi.xml.service.ch.mobi.maia.amw.maiaamwfederationservice.v1_0.TechnicalException; import ch.mobi.xml.service.ch.mobi.maia.amw.maiaamwfederationservice.v1_0.ValidationException; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Calendar; import java.util.Date; import static org.junit.Assert.*; /** * Test case to verify creation/remove/decorate of properties on consumed resource relation */ public class MaiaAmwFederationServiceUseCase7IntegrationTest extends BaseUseCaseIntegrationTest { // usecase files private static final String REQUEST_1 = "usecase7_8/request1.xml"; // private static final String REQUEST_2 = "usecase7_8/request2.xml"; private static final String RELATED_RESOURCE_NAME = "adExtern"; // verify add and remove cpi // Use // 1 ./generateModel.sh model_small uc_dev_iterations/model_02_add_puzzleshop/ // <!-- updaterequest calculated from difference between model 'model_small' and // 'uc_dev_iterations/model_02_add_puzzleshop' but then altered such that shop and bank does not have // any properties on consumed/provided relations--> // 2 ./generateModel.sh model_small uc_dev_iterations/model_02_add_puzzleshop/ // <!-- updaterequest calculated from difference between model 'model_small' and // 'uc_dev_iterations/model_02_add_puzzleshop' but then altered such that all consumed and provided // ports does have property 'puzzleBankPaymentProperty', 'puzzleBankCustomerProperty' and 'puzzleShopPaymentStuffProperty' --> // to generate the Requests @Before public void setUp() { super.setUp(); createAndAddMainRelease16_04(); createAndAddReleaseIfNotYetExist(MINOR_RELEASE_16_05, new Date(2016, Calendar.MAY, 1), false); createAndAddReleaseIfNotYetExist(MINOR_RELEASE_16_06, new Date(2016, Calendar.JUNE, 1), false); addResourceTypes(); } @After public void tearDown() { super.tearDown(); } @Test public void createMinorReleaseBasedOnMaiaMainRlWithCpiWithoutPropertiesThenUpdateMaiaWithCpiWithPropertiesShouldAddCpiPropertiesToEachMinorRelease() throws Exception { executeRequest1(); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 1); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); createMinorReleasesForResource(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, MINOR_RELEASE_16_06); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 3); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); //second Maia Request adds properties to CPI on Shop executeRequest2(); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); } @Test public void createMinorReleaseBasedOnMaiaMainRlWithCpiWithPropertiesThenUpdateMaiaWithCpiWithoutPropertiesShouldRemoveCpiPropertiesFromEachMinorRelease() throws Exception { executeRequest2(); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 1); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); createMinorReleasesForResource(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, MINOR_RELEASE_16_06); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 3); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); //second Maia Request removes properties from CPI from Shop executeRequest1(); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); } @Test public void decorateConsumedRelationPropertyOnMainRlWithCpiWithoutPropertiesThenCreateMinorReleaseThenUpdateMainRlWithCpiWithPropertiesShouldAddMainRlCpiPropertiesAndKeepDecoratedRelationPropertyOnEachMinorRelease() throws Exception { executeRequest1(); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 1); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); decorateAMWPropertyOnResourceForRelease(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); createMinorReleasesForResource(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, MINOR_RELEASE_16_06); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 3); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); //second Maia Request adds properties to CPI on Shop executeRequest2(); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); } @Test public void decorateConsumedRelationPropertiesOnMainRlWithCpiWithPropertiesThenCreateMinorReleaseThenUpdateMainRlWithCpiWithoutPropertiesCpiShouldRemoveMainRlCpiPropertiesButKeepDecoratedRelationPropertiesOnEachMinorRelease() throws Exception { executeRequest2(); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 1); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); decorateAMWPropertyOnResourceForRelease(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); createMinorReleasesForResource(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, MINOR_RELEASE_16_06); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 3); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); //second Maia Request removes properties from CPI from Shop executeRequest1(); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, buildPropertyNameFor(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04)); } @Test public void decorateConsumedRelationWithAmwPropertyOnMainRlWithCpiWithoutPropertiesThenCreateMinorReleaseThenUpdateMainRlWithCpiWithAlreadyExistingPropertyShouldGenerateImportExceptionForAgregate() throws Exception { executeRequest1(); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 1); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); decorateAMWPropertyOnResourceForRelease(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); createMinorReleasesForResource(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, MINOR_RELEASE_16_06); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 3); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); UpdateResponse updateResponse = doExecuteRequest2(); assertEquals(2, updateResponse.getProcessedApplications().size()); assertEquals(MessageSeverity.INFO, updateResponse.getProcessedApplications().get(0).getMessages().get(0).getSeverity()); assertEquals(MessageSeverity.ERROR, updateResponse.getProcessedApplications().get(1).getMessages().get(0).getSeverity()); assertTrue(updateResponse.getProcessedApplications().get(1).getMessages().get(0).getHumanReadableMessage().contains(PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY)); } @Test public void createMinorReleaseThenDecorateWithAmwPropertyThenUpdateMainRlWithCpiWithAlreadyExistingPropertyShouldGenerateImportExceptionForAgregate() throws Exception { executeRequest1(); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 1); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); createMinorReleasesForResource(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, MINOR_RELEASE_16_06); verifyNumberReleasesFor(PUZZLE_SHOP_V_1, 3); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MAIN_RELEASE_16_04, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_06, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04); decorateAMWPropertyOnResourceForRelease(PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); verifyPropertiesPresentInConsumedRelation(PUZZLE_SHOP_V_1, MINOR_RELEASE_16_05, PUZZLE_SHOP_V_1_CPI_PAYMENTSTUFF, MAIN_RELEASE_16_04, PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY); UpdateResponse updateResponse = doExecuteRequest2(); assertEquals(2, updateResponse.getProcessedApplications().size()); assertEquals(MessageSeverity.INFO, updateResponse.getProcessedApplications().get(0).getMessages().get(0).getSeverity()); assertEquals(MessageSeverity.ERROR, updateResponse.getProcessedApplications().get(1).getMessages().get(0).getSeverity()); assertTrue(updateResponse.getProcessedApplications().get(1).getMessages().get(0).getHumanReadableMessage().contains(PUZZLE_SHOP_PAYMENTSTUFF_PROPERTY)); } /** * small -->02: [Grundzustand] Create PuzzleShop (CPI) and PuzzleBank (PPI) */ private void executeRequest1() throws BusinessException, TechnicalException, ValidationException { // when UpdateResponse updateResponse = doUpdate(REQUEST_1); // then assertNotNull(updateResponse); assertEquals(2, updateResponse.getProcessedApplications().size()); assertEquals(MessageSeverity.INFO, updateResponse.getProcessedApplications().get(0).getMessages().get(0).getSeverity()); assertEquals(MessageSeverity.INFO, updateResponse.getProcessedApplications().get(1).getMessages().get(0).getSeverity()); } /** * small -->02: [Grundzustand] additional Property */ private void executeRequest2() throws BusinessException, TechnicalException, ValidationException { // when UpdateResponse updateResponse = doExecuteRequest2(); // then assertEquals(2, updateResponse.getProcessedApplications().size()); assertEquals(MessageSeverity.INFO, updateResponse.getProcessedApplications().get(0).getMessages().get(0).getSeverity()); assertEquals(MessageSeverity.INFO, updateResponse.getProcessedApplications().get(1).getMessages().get(0).getSeverity()); } private UpdateResponse doExecuteRequest2() throws BusinessException, TechnicalException, ValidationException { // when UpdateResponse updateResponse = doUpdate(REQUEST_2); // then assertNotNull(updateResponse); return updateResponse; } }
agpl-3.0
neo4j-attic/graphdb
backup/src/main/java/org/neo4j/backup/OnlineBackupExtension.java
3054
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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/>. */ package org.neo4j.backup; import static org.neo4j.kernel.Config.ENABLE_ONLINE_BACKUP; import static org.neo4j.kernel.Config.KEEP_LOGICAL_LOGS; import static org.neo4j.kernel.Config.parseMapFromConfigValue; import java.util.Map; import org.neo4j.helpers.Service; import org.neo4j.kernel.KernelData; import org.neo4j.kernel.KernelExtension; @Service.Implementation( KernelExtension.class ) public class OnlineBackupExtension extends KernelExtension<BackupServer> { static final String KEY = "online backup"; public OnlineBackupExtension() { super( KEY ); } @Override protected void loadConfiguration( KernelData kernel ) { if ( parsePort( (String) kernel.getParam( ENABLE_ONLINE_BACKUP ) ) != null ) { // Means that online backup will be enabled kernel.getConfig().getParams().put( KEEP_LOGICAL_LOGS, "true" ); } } @Override protected BackupServer load( KernelData kernel ) { Integer port = parsePort( (String) kernel.getParam( ENABLE_ONLINE_BACKUP ) ); if ( port != null ) { TheBackupInterface backup = new BackupImpl( kernel.graphDatabase() ); BackupServer server = new BackupServer( backup, port.intValue(), (String) kernel.getConfig().getParams().get( "store_dir" ) ); return server; } return null; } public static Integer parsePort( String backupConfigValue ) { if ( backupConfigValue != null ) { int port = BackupServer.DEFAULT_PORT; if ( backupConfigValue.contains( "=" ) ) { Map<String, String> args = parseMapFromConfigValue( ENABLE_ONLINE_BACKUP, backupConfigValue ); if ( args.containsKey( "port" ) ) { port = Integer.parseInt( args.get( "port" ) ); } } else if ( !Boolean.parseBoolean( backupConfigValue ) ) { return null; } return Integer.valueOf( port ); } return null; } @Override protected void unload( BackupServer server ) { server.shutdown(); } }
agpl-3.0
infinitech-unipd/Premi
public/modules/editor/tests/editor.client.service.test.js
4661
/** * Nome del file: editor.client.service.test.js * Percorso: /public/modules/editor/tests/editor.client.service.test.js * Autore: InfiniTech * Data creazione: 2015-08-28 * E-mail: info.infinitech@gmail.com * * Questo file è proprietà del gruppo InfiniTech e viene rilasciato sotto * licenza GNU AGPLv3. * * Diario delle modifiche: * 2015-08-28 - Aggiunti test per metodi di Editor - Alex Ruzzante */ 'use strict'; (function() { describe('EditorService', function() { //Initialize global variables var $httpBackend; var mockPresentation; var Presentations; var $stateParams; var Editor; // Load the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(inject(function(_$stateParams_, _$httpBackend_, _Editor_, _Presentations_) { $httpBackend = _$httpBackend_; Editor = _Editor_; Presentations = _Presentations_; $stateParams = _$stateParams_; mockPresentation = { _id: '12234', info: { title: 'A sample presentation', description: 'Premi rocks!' }, containers: [ 'First container', 'Second container' ], productionWidth: '500', overviewWidth: '500', resolution: { width: '500', height: '500' } }; })); it('Editor.updatePresentationInfo() should update the presentation\'s info', function() { Editor.updatePresentationInfo(mockPresentation.info); // Test scope value expect(Editor.getPresentationInfo()).toEqual(mockPresentation.info); }); it('Editor.getPresentationInfo() should return the updated presentation\'s info', function() { Editor.updatePresentationInfo(mockPresentation.info); // Test scope value expect(Editor.getPresentationInfo()).toEqual(mockPresentation.info); }); it('Editor.init() should obtain the presentation to edit', function() { $stateParams.presentationId = mockPresentation._id; $httpBackend.expectGET('/presentations/12234').respond(mockPresentation); Editor.init(); $httpBackend.flush(); // Test scope value expect(Editor.getPresentationInfo()).toEqual(mockPresentation.info); }); it('Editor.saveContainers(containers) should save the presentation\'s containers', function() { Editor.saveContainers(mockPresentation.containers); // Test scope value expect(Editor.getContainers()).toEqual(mockPresentation.containers); }); it('Editor.getContainers() should get the presentation\'s containers', function() { Editor.saveContainers(mockPresentation.containers); // Test scope value expect(Editor.getContainers()).toEqual(mockPresentation.containers); }); it('Editor.saveContainer(container, index) should save the presentation\'s container', function() { Editor.saveContainers({}); Editor.saveContainer(mockPresentation.containers[0],0); // Test scope value expect(Editor.getContainer(0)).toEqual(mockPresentation.containers[0]); }); it('Editor.getContainer() should get the presentation\'s container', function() { Editor.saveContainers({}); Editor.saveContainer(mockPresentation.containers[1],0); expect(Editor.getContainer(0)).toEqual(mockPresentation.containers[1]); }); //getResolution setResolution it('Editor.getResolution() should get the presentation\'s resolution', function() { Editor.setResolution(mockPresentation.resolution); // Test scope value expect(Editor.getResolution()).toEqual(mockPresentation.resolution); }); it('Editor.setResolution(resolution) should set the presentation\'s resolution', function() { Editor.setResolution(mockPresentation.resolution); // Test scope value expect(Editor.getResolution()).toEqual(mockPresentation.resolution); }); it('Editor.saveProductionWidth(width) should save the presentation\'s production width', function() { Editor.saveProductionWidth(mockPresentation.productionWidth); // Test scope value expect(Editor.getProductionWidth()).toEqual(mockPresentation. productionWidth); }); it('Editor.getProductionWidth() should get the presentation\'s production width', function() { Editor.saveProductionWidth(mockPresentation.productionWidth); // Test scope value expect(Editor.getProductionWidth()).toEqual(mockPresentation. productionWidth); }); }); })();
agpl-3.0
akatsuki10b/ByteJudge
ByteJudge/home.php
802
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="" /> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <title>ByteJudge</title> </head> <body onload="change('tab1')"> <div id="wrapper"> <?php include("./includes/header.php"); ?> <?php include("includes/nav.php"); ?> <div id="content"> <?php include('./includes/home_again.php'); ?> </div> <!-- end #content --> <?php include("./includes/footer.php"); ?> </div> <!-- End #wrapper --> </body> </html>
agpl-3.0
codeback/openerp-cbk_product_cost_incl_bom
wizard/__init__.py
1081
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Codeback Software S.L. (www.codeback.es). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import store_price # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
paulmartel/voltdb
src/frontend/org/voltdb/utils/PersistentBinaryDeque.java
33613
/* This file is part of VoltDB. * Copyright (C) 2008-2016 VoltDB Inc. * * 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/>. */ package org.voltdb.utils; import java.io.EOFException; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.DBBPool; import org.voltcore.utils.DBBPool.BBContainer; import org.voltcore.utils.DeferredSerialization; import org.voltdb.EELibraryLoader; import org.voltdb.utils.BinaryDeque.TruncatorResponse.Status; import org.voltdb.utils.PBDSegment.PBDSegmentReader; import com.google_voltpatches.common.base.Joiner; import com.google_voltpatches.common.base.Throwables; /** * A deque that specializes in providing persistence of binary objects to disk. Any object placed * in the deque will be persisted to disk asynchronously. Objects placed in the deque can * be persisted synchronously by invoking sync. The files backing this deque all start with a nonce * provided at construction time followed by a segment index that is stored in the filename. Files grow to * a maximum size of 64 megabytes and then a new segment is created. The index starts at 0. Segments are deleted * once all objects from the segment have been polled and all the containers returned by poll have been discarded. * Push is implemented by creating new segments at the head of the deque containing the objects to be pushed. * */ public class PersistentBinaryDeque implements BinaryDeque { private static final VoltLogger LOG = new VoltLogger("HOST"); public static class UnsafeOutputContainerFactory implements OutputContainerFactory { @Override public BBContainer getContainer(int minimumSize) { final BBContainer origin = DBBPool.allocateUnsafeByteBuffer(minimumSize); final BBContainer retcont = new BBContainer(origin.b()) { private boolean discarded = false; @Override public synchronized void discard() { checkDoubleFree(); if (discarded) { LOG.error("Avoided double discard in PBD"); return; } discarded = true; origin.discard(); } }; return retcont; } } /** * Used to read entries from the PBD. Multiple readers may be active at the same time, * but only one read or write may happen concurrently. */ private class ReadCursor implements BinaryDequeReader { private final String m_cursorId; private PBDSegment m_segment; // Number of objects out of the total //that were deleted at the time this cursor was created private final int m_numObjectsDeleted; private int m_numRead; public ReadCursor(String cursorId, int numObjectsDeleted) throws IOException { m_cursorId = cursorId; m_numObjectsDeleted = numObjectsDeleted; } @Override public BBContainer poll(OutputContainerFactory ocf) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Reader " + m_cursorId + " has been closed"); } assertions(); moveToValidSegment(); PBDSegmentReader segmentReader = m_segment.getReader(m_cursorId); if (segmentReader == null) { segmentReader = m_segment.openForRead(m_cursorId); } long lastSegmentId = peekLastSegment().segmentId(); while (!segmentReader.hasMoreEntries()) { if (m_segment.segmentId() == lastSegmentId) { // nothing more to read return null; } segmentReader.close(); m_segment = m_segments.higherEntry(m_segment.segmentId()).getValue(); // push to PBD will rewind cursors. So, this cursor may have already opened this segment segmentReader = m_segment.getReader(m_cursorId); if (segmentReader == null) segmentReader = m_segment.openForRead(m_cursorId); } BBContainer retcont = segmentReader.poll(ocf); m_numRead++; assertions(); assert (retcont.b() != null); return wrapRetCont(m_segment, retcont); } } private void moveToValidSegment() { PBDSegment firstSegment = peekFirstSegment(); // It is possible that m_segment got closed and removed if (m_segment == null || m_segment.segmentId() < firstSegment.segmentId()) { m_segment = firstSegment; } } @Override public int getNumObjects() throws IOException { if (m_closed) { throw new IOException("Reader " + m_cursorId + " has been closed"); } return m_numObjects - m_numObjectsDeleted - m_numRead; } /* * Don't use size in bytes to determine empty, could potentially * diverge from object count on crash or power failure * although incredibly unlikely */ @Override public long sizeInBytes() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Reader " + m_cursorId + " has been closed"); } assertions(); moveToValidSegment(); long size = 0; boolean inclusive = true; if (m_segment.isOpenForReading(m_cursorId)) { //this reader has started reading from curr segment. // Find out how much is left to read. size = m_segment.getReader(m_cursorId).uncompressedBytesToRead(); inclusive = false; } // Get the size of all unread segments for (PBDSegment currSegment : m_segments.tailMap(m_segment.segmentId(), inclusive).values()) { size += currSegment.size(); } return size; } } @Override public boolean isEmpty() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Closed"); } assertions(); moveToValidSegment(); boolean inclusive = true; if (m_segment.isOpenForReading(m_cursorId)) { //this reader has started reading from curr segment. // Check if there are more to read. if (m_segment.getReader(m_cursorId).hasMoreEntries()) return false; inclusive = false; } for (PBDSegment currSegment : m_segments.tailMap(m_segment.segmentId(), inclusive).values()) { if (currSegment.getNumEntries() > 0) return false; } return true; } } private BBContainer wrapRetCont(PBDSegment segment, final BBContainer retcont) { return new BBContainer(retcont.b()) { @Override public void discard() { synchronized(PersistentBinaryDeque.this) { checkDoubleFree(); retcont.discard(); assert(m_closed || m_segments.containsKey(segment.segmentId())); //Don't do anything else if we are closed if (m_closed) { return; } //Segment is potentially ready for deletion try { PBDSegmentReader segmentReader = segment.getReader(m_cursorId); // Don't delete if this is the last segment. // Cannot be deleted if this reader hasn't finished discarding this. if (segment == peekLastSegment() || !segmentReader.allReadAndDiscarded()) { return; } if (canDeleteSegment(segment)) { m_segments.remove(segment.segmentId()); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + segment.file() + " has been closed and deleted after discarding last buffer"); } closeAndDeleteSegment(segment); } } catch (IOException e) { LOG.error("Exception closing and deleting PBD segment", e); } } } }; } } public static final OutputContainerFactory UNSAFE_CONTAINER_FACTORY = new UnsafeOutputContainerFactory(); /** * Processors also log using this facility. */ private final VoltLogger m_usageSpecificLog; private final File m_path; private final String m_nonce; private boolean m_initializedFromExistingFiles = false; //Segments that are no longer being written to and can be polled //These segments are "immutable". They will not be modified until deletion private final TreeMap<Long, PBDSegment> m_segments = new TreeMap<>(); private volatile boolean m_closed = false; private final HashMap<String, ReadCursor> m_readCursors = new HashMap<>(); private RandomAccessFile m_cursorsWriter; private int m_numObjects; private int m_numDeleted; /** * Create a persistent binary deque with the specified nonce and storage * back at the specified path. Existing files will * * @param nonce * @param path * @param logger * @throws IOException */ public PersistentBinaryDeque(final String nonce, final File path, VoltLogger logger) throws IOException { this(nonce, path, logger, true); } /** * Create a persistent binary deque with the specified nonce and storage back at the specified path. * This is convenient method for test so that * poll with delete can be tested. * * @param nonce * @param path * @param deleteEmpty * @throws IOException */ public PersistentBinaryDeque(final String nonce, final File path, VoltLogger logger, final boolean deleteEmpty) throws IOException { EELibraryLoader.loadExecutionEngineLibrary(true); m_path = path; m_nonce = nonce; m_usageSpecificLog = logger; if (!path.exists() || !path.canRead() || !path.canWrite() || !path.canExecute() || !path.isDirectory()) { throw new IOException(path + " is not usable ( !exists || !readable " + "|| !writable || !executable || !directory)"); } final TreeMap<Long, PBDSegment> segments = new TreeMap<Long, PBDSegment>(); //Parse the files in the directory by name to find files //that are part of this deque try { path.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { // PBD file names have three parts: nonce.seq.pbd // nonce may contain '.', seq is a sequence number. String[] parts = pathname.getName().split("\\."); String parsedNonce = null; String seqNum = null; String extension = null; // If more than 3 parts, it means nonce contains '.', assemble them. if (parts.length > 3) { Joiner joiner = Joiner.on('.').skipNulls(); parsedNonce = joiner.join(Arrays.asList(parts).subList(0, parts.length - 2)); seqNum = parts[parts.length - 2]; extension = parts[parts.length - 1]; } else if (parts.length == 3) { parsedNonce = parts[0]; seqNum = parts[1]; extension = parts[2]; } if (nonce.equals(parsedNonce) && "pbd".equals(extension)) { if (pathname.length() == 4) { //Doesn't have any objects, just the object count pathname.delete(); return false; } Long index = Long.valueOf(seqNum); PBDSegment qs = newSegment( index, pathname ); try { m_initializedFromExistingFiles = true; if (deleteEmpty) { if (qs.getNumEntries() == 0) { LOG.info("Found Empty Segment with entries: " + qs.getNumEntries() + " For: " + pathname.getName()); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + qs.file() + " has been closed and deleted during init"); } qs.closeAndDelete(); return false; } } if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + qs.file() + " has been recovered"); } qs.close(); segments.put(index, qs); } catch (IOException e) { throw new RuntimeException(e); } } return false; } }); } catch (RuntimeException e) { if (e.getCause() instanceof IOException) { throw new IOException(e); } Throwables.propagate(e); } Long lastKey = null; for (Map.Entry<Long, PBDSegment> e : segments.entrySet()) { final Long key = e.getKey(); if (lastKey == null) { lastKey = key; } else { if (lastKey + 1 != key) { try { for (PBDSegment pbds : segments.values()) { pbds.close(); } } catch (Exception ex) {} throw new IOException("Missing " + nonce + " pbd segments between " + lastKey + " and " + key + " in directory " + path + ". The data files found in the export overflow directory were inconsistent."); } lastKey = key; } m_segments.put(e.getKey(), e.getValue()); } //Find the first and last segment for polling and writing (after) Long writeSegmentIndex = 0L; try { writeSegmentIndex = segments.lastKey() + 1; } catch (NoSuchElementException e) {} PBDSegment writeSegment = newSegment( writeSegmentIndex, new VoltFile(m_path, m_nonce + "." + writeSegmentIndex + ".pbd")); m_segments.put(writeSegmentIndex, writeSegment); writeSegment.openForWrite(true); m_numObjects = countNumObjects(); // load saved cursors readCursorFile(new File(m_path, m_nonce + ".pbd.cursors")); assertions(); } private int countNumObjects() throws IOException { int numObjects = 0; for (PBDSegment segment : m_segments.values()) { numObjects += segment.getNumEntries(); } return numObjects; } private void readCursorFile(File file) { try { m_cursorsWriter = new RandomAccessFile(file, "rwd"); String cursorId = null; while ((cursorId=m_cursorsWriter.readUTF()) != null) { m_readCursors.put(cursorId, new ReadCursor(cursorId, m_numDeleted)); m_cursorsWriter.readUTF(); } } catch(EOFException e) { // Nothing to read } catch(IOException e) { throw new RuntimeException(e); } } @Override public synchronized void parseAndTruncate(BinaryDequeTruncator truncator) throws IOException { if (m_closed) { throw new IOException("PBD has been closed"); } assertions(); if (m_segments.isEmpty()) { m_usageSpecificLog.debug("PBD " + m_nonce + " has no finished segments"); return; } // Close the last write segment for now, will reopen after truncation peekLastSegment().close(); /* * Iterator all the objects in all the segments and pass them to the truncator * When it finds the truncation point */ Long lastSegmentIndex = null; for (PBDSegment segment : m_segments.values()) { final long segmentIndex = segment.segmentId(); final int truncatedEntries = segment.parseAndTruncate(truncator); if (truncatedEntries == -1) { lastSegmentIndex = segmentIndex - 1; break; } else if (truncatedEntries > 0) { m_numObjects -= truncatedEntries; //Set last segment and break the loop over this segment lastSegmentIndex = segmentIndex; break; } // truncatedEntries == 0 means nothing is truncated in this segment, // should move on to the next segment. } /* * If it was found that no truncation is necessary, lastSegmentIndex will be null. * Return and the parseAndTruncate is a noop. */ if (lastSegmentIndex == null) { // Reopen the last segment for write peekLastSegment().openForWrite(true); return; } /* * Now truncate all the segments after the truncation point */ Iterator<Long> iterator = m_segments.descendingKeySet().iterator(); while (iterator.hasNext()) { Long segmentId = iterator.next(); if (segmentId <= lastSegmentIndex) { break; } PBDSegment segment = m_segments.get(segmentId); m_numObjects -= segment.getNumEntries(); iterator.remove(); m_usageSpecificLog.debug("Segment " + segment.file() + " has been closed and deleted by truncator"); segment.closeAndDelete(); } /* * Reset the poll and write segments */ //Find the first and last segment for polling and writing (after) Long newSegmentIndex = 0L; if (peekLastSegment() != null) newSegmentIndex = peekLastSegment().segmentId() + 1; PBDSegment newSegment = newSegment(newSegmentIndex, new VoltFile(m_path, m_nonce + "." + newSegmentIndex + ".pbd")); newSegment.openForWrite(true); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + newSegment.file() + " has been created by PBD truncator"); } m_segments.put(newSegment.segmentId(), newSegment); assertions(); } private PBDSegment newSegment(long segmentId, File file) { return new PBDRegularSegment(segmentId, file); } /** * Close the tail segment if it's not being read from currently, then offer the new segment. * @throws IOException */ private void closeTailAndOffer(PBDSegment newSegment) throws IOException { PBDSegment last = peekLastSegment(); if (last != null && !last.isBeingPolled()) { last.close(); } m_segments.put(newSegment.segmentId(), newSegment); } private PBDSegment peekFirstSegment() { Map.Entry<Long, PBDSegment> entry = m_segments.firstEntry(); // entry may be null in ctor and while we are manipulating m_segments in addSegment, for example return (entry==null) ? null : entry.getValue(); } private PBDSegment peekLastSegment() { Map.Entry<Long, PBDSegment> entry = m_segments.lastEntry(); // entry may be null in ctor and while we are manipulating m_segments in addSegment, for example return (entry==null) ? null : entry.getValue(); } private PBDSegment pollLastSegment() { Map.Entry<Long, PBDSegment> entry = m_segments.pollLastEntry(); return (entry!=null) ? entry.getValue() : null; } @Override public synchronized void offer(BBContainer object) throws IOException { offer(object, true); } @Override public synchronized void offer(BBContainer object, boolean allowCompression) throws IOException { assertions(); if (m_closed) { throw new IOException("Closed"); } PBDSegment tail = peekLastSegment(); final boolean compress = object.b().isDirect() && allowCompression; if (!tail.offer(object, compress)) { tail = addSegment(tail); final boolean success = tail.offer(object, compress); if (!success) { throw new IOException("Failed to offer object in PBD"); } } m_numObjects++; assertions(); } @Override public synchronized int offer(DeferredSerialization ds) throws IOException { assertions(); if (m_closed) { throw new IOException("Closed"); } PBDSegment tail = peekLastSegment(); int written = tail.offer(ds); if (written < 0) { tail = addSegment(tail); written = tail.offer(ds); if (written < 0) { throw new IOException("Failed to offer object in PBD"); } } m_numObjects++; assertions(); return written; } private PBDSegment addSegment(PBDSegment tail) throws IOException { //Check to see if the tail is completely consumed so we can close and delete it if (tail.hasAllFinishedReading() && canDeleteSegment(tail)) { pollLastSegment(); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + tail.file() + " has been closed and deleted because of empty queue"); } closeAndDeleteSegment(tail); } Long nextIndex = tail.segmentId() + 1; tail = newSegment(nextIndex, new VoltFile(m_path, m_nonce + "." + nextIndex + ".pbd")); tail.openForWrite(true); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + tail.file() + " has been created because of an offer"); } closeTailAndOffer(tail); return tail; } private void closeAndDeleteSegment(PBDSegment segment) throws IOException { int toDelete = segment.getNumEntries(); segment.closeAndDelete(); m_numDeleted += toDelete; } @Override public synchronized void push(BBContainer objects[]) throws IOException { assertions(); if (m_closed) { throw new IOException("Closed"); } ArrayDeque<ArrayDeque<BBContainer>> segments = new ArrayDeque<ArrayDeque<BBContainer>>(); ArrayDeque<BBContainer> currentSegment = new ArrayDeque<BBContainer>(); //Take the objects that were provided and separate them into deques of objects //that will fit in a single write segment int available = PBDSegment.CHUNK_SIZE - 4; for (BBContainer object : objects) { int needed = PBDSegment.OBJECT_HEADER_BYTES + object.b().remaining(); if (available - needed < 0) { if (needed > PBDSegment.CHUNK_SIZE - 4) { throw new IOException("Maximum object size is " + (PBDSegment.CHUNK_SIZE - 4)); } segments.offer( currentSegment ); currentSegment = new ArrayDeque<BBContainer>(); available = PBDSegment.CHUNK_SIZE - 4; } available -= needed; currentSegment.add(object); } segments.add(currentSegment); assert(segments.size() > 0); //Calculate the index for the first segment to push at the front //This will be the index before the first segment available for read or //before the write segment if there are no finished segments Long nextIndex = 0L; if (m_segments.size() > 0) { nextIndex = peekFirstSegment().segmentId() - 1; } while (segments.peek() != null) { ArrayDeque<BBContainer> currentSegmentContents = segments.poll(); PBDSegment writeSegment = newSegment( nextIndex, new VoltFile(m_path, m_nonce + "." + nextIndex + ".pbd")); writeSegment.openForWrite(true); nextIndex--; if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + writeSegment.file() + " has been created because of a push"); } while (currentSegmentContents.peek() != null) { writeSegment.offer(currentSegmentContents.pollFirst(), false); m_numObjects++; } // Don't close the last one, it'll be used for writes if (!m_segments.isEmpty()) { writeSegment.close(); } m_segments.put(writeSegment.segmentId(), writeSegment); } // Because we inserted at the beginning, cursors need to be rewound to the beginning rewindCursors(); assertions(); } private void rewindCursors() { PBDSegment firstSegment = peekFirstSegment(); for (ReadCursor cursor : m_readCursors.values()) { cursor.m_segment = firstSegment; } } @Override public synchronized BinaryDequeReader openForRead(String cursorId) throws IOException { if (m_closed) { throw new IOException("Closed"); } ReadCursor reader = m_readCursors.get(cursorId); if (reader == null) { reader = new ReadCursor(cursorId, m_numDeleted); m_readCursors.put(cursorId, reader); persistCursor(cursorId); } return reader; } private void persistCursor(String cursorId) throws IOException { m_cursorsWriter.writeUTF(cursorId); m_cursorsWriter.writeUTF(System.getProperty("line.separator")); } private boolean canDeleteSegment(PBDSegment segment) throws IOException { for (ReadCursor cursor : m_readCursors.values()) { if (cursor.m_segment != null && (cursor.m_segment.segmentId() >= segment.segmentId())) { PBDSegmentReader segmentReader = segment.getReader(cursor.m_cursorId); if (segmentReader == null) { assert(cursor.m_segment.segmentId() == segment.segmentId()); segmentReader = segment.openForRead(cursor.m_cursorId); } if (!segmentReader.allReadAndDiscarded()) return false; } else { // this cursor hasn't reached this segment yet return false; } } return true; } @Override public synchronized void sync() throws IOException { if (m_closed) { throw new IOException("Closed"); } for (PBDSegment segment : m_segments.values()) { if (!segment.isClosed()) { segment.sync(); } } } @Override //TODO: Should we get rid of persisted cursors on close? public synchronized void close() throws IOException { if (m_closed) { return; } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_cursorsWriter.close(); m_closed = true; } /* * Don't use size in bytes to determine empty, could potentially * diverge from object count on crash or power failure * although incredibly unlikely */ @Override public synchronized long sizeInBytes() throws IOException { long size = 0; for (PBDSegment segment : m_segments.values()) { size += segment.size(); } return size; } @Override public synchronized void closeAndDelete() throws IOException { if (m_closed) return; m_closed = true; for (PBDSegment qs : m_segments.values()) { m_usageSpecificLog.debug("Segment " + qs.file() + " has been closed and deleted due to delete all"); closeAndDeleteSegment(qs); } } public static class ByteBufferTruncatorResponse extends TruncatorResponse { private final ByteBuffer m_retval; public ByteBufferTruncatorResponse(ByteBuffer retval) { super(Status.PARTIAL_TRUNCATE); assert retval.remaining() > 0; m_retval = retval; } @Override public int writeTruncatedObject(ByteBuffer output) { int objectSize = m_retval.remaining(); output.putInt(objectSize); output.putInt(PBDSegment.NO_FLAGS); output.put(m_retval); return objectSize; } } public static class DeferredSerializationTruncatorResponse extends TruncatorResponse { public static interface Callback { public void bytesWritten(int bytes); } private final DeferredSerialization m_ds; private final Callback m_truncationCallback; public DeferredSerializationTruncatorResponse(DeferredSerialization ds, Callback truncationCallback) { super(Status.PARTIAL_TRUNCATE); m_ds = ds; m_truncationCallback = truncationCallback; } @Override public int writeTruncatedObject(ByteBuffer output) throws IOException { int bytesWritten = PBDUtils.writeDeferredSerialization(output, m_ds); if (m_truncationCallback != null) { m_truncationCallback.bytesWritten(bytesWritten); } return bytesWritten; } } public static TruncatorResponse fullTruncateResponse() { return new TruncatorResponse(Status.FULL_TRUNCATE); } @Override public int getNumObjects() throws IOException { int numObjects = 0; for (PBDSegment segment : m_segments.values()) { numObjects += segment.getNumEntries(); } return numObjects; } @Override public boolean initializedFromExistingFiles() { return m_initializedFromExistingFiles; } private static final boolean assertionsOn; static { boolean assertOn = false; assert(assertOn = true); assertionsOn = assertOn; } private void assertions() { if (!assertionsOn || m_closed) return; for (ReadCursor cursor : m_readCursors.values()) { int numObjects = 0; try { for (PBDSegment segment : m_segments.values()) { PBDSegmentReader reader = segment.getReader(cursor.m_cursorId); if (reader == null) { numObjects += segment.getNumEntries(); } else { numObjects += segment.getNumEntries() - reader.readIndex(); } } assert numObjects == cursor.getNumObjects() : numObjects + " != " + cursor.getNumObjects(); } catch (Exception e) { Throwables.propagate(e); } } } // Used by test only int numOpenSegments() { int numOpen = 0; for (PBDSegment segment : m_segments.values()) { if (!segment.isClosed()) numOpen++; } return numOpen; } }
agpl-3.0
zvini/website
www/bar-charts/delete/submit.php
630
<?php include_once '../../../lib/defaults.php'; $fnsDir = '../../fns'; include_once "$fnsDir/require_same_domain_referer.php"; require_same_domain_referer('..'); include_once '../fns/require_bar_chart.php'; include_once '../../lib/mysqli.php'; list($bar_chart, $id, $user) = require_bar_chart($mysqli); include_once "$fnsDir/Users/BarCharts/delete.php"; Users\BarCharts\delete($mysqli, $bar_chart); unset($_SESSION['bar-charts/errors']); $_SESSION['bar-charts/messages'] = ["Bar chart #$id has been deleted."]; include_once "$fnsDir/redirect.php"; include_once "$fnsDir/ItemList/listUrl.php"; redirect(ItemList\listUrl());
agpl-3.0
precog/labcoat-legacy
js/ace/mode/lisp.js
3364
/* * _ _ _ * | | | | | | * | | __ _| |__ ___ ___ __ _| |_ Labcoat (R) * | |/ _` | '_ \ / __/ _ \ / _` | __| Powerful development environment for Quirrel. * | | (_| | |_) | (_| (_) | (_| | |_ Copyright (C) 2010 - 2013 SlamData, Inc. * |_|\__,_|_.__/ \___\___/ \__,_|\__| All Rights Reserved. * * * 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/>. * */ /* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of Ajax.org B.V. 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 AJAX.ORG B.V. 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. * * * ***** END LICENSE BLOCK ***** */ /* THIS FILE WAS AUTOGENERATED BY mode.tmpl.js */ define(function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LispHighlightRules = require("./lisp_highlight_rules").LispHighlightRules; var Mode = function() { var highlighter = new LispHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = ";"; }).call(Mode.prototype); exports.Mode = Mode; });
agpl-3.0
mebiusashan/beaker
controller/error.go
814
package controller import ( "fmt" "github.com/gin-gonic/gin" "github.com/mebiusashan/beaker/common" ) type ErrerController struct { BaseController } func (ct *ErrerController) Do404(c *gin.Context) { bodyStr, err := ct.Context.Cache.GET(common.TEMPLATE_NotFound, "") if err == nil && bodyStr != "" { c.Writer.WriteHeader(404) c.Writer.WriteString(bodyStr) return } vars := ct.Context.View.GetVarMap() vars.Set("title", "404") str, err := ct.Context.View.Render(common.TEMPLATE_NotFound, vars) if err != nil { fmt.Println(err) ct.Do500(c) return } ct.Context.Cache.SETNX(common.TAG_NOTFOUND, "", str, ct.Context.Config.Redis.EXPIRE_TIME) c.Writer.WriteHeader(404) c.Writer.WriteString(str) } func (ct *ErrerController) Do500(c *gin.Context) { c.String(500, "500 Server Error") }
agpl-3.0
ratliff/server
alpha/lib/model/om/Baseentry.php
221629
<?php /** * Base class that represents a row from the 'entry' table. * * * * @package Core * @subpackage model.om */ abstract class Baseentry extends BaseObject implements Persistent { /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. * @var entryPeer */ protected static $peer; /** * The value for the id field. * @var string */ protected $id; /** * The value for the kshow_id field. * @var string */ protected $kshow_id; /** * The value for the kuser_id field. * @var int */ protected $kuser_id; /** * The value for the name field. * @var string */ protected $name; /** * The value for the type field. * @var int */ protected $type; /** * The value for the media_type field. * @var int */ protected $media_type; /** * The value for the data field. * @var string */ protected $data; /** * The value for the thumbnail field. * @var string */ protected $thumbnail; /** * The value for the views field. * Note: this column has a database default value of: 0 * @var int */ protected $views; /** * The value for the votes field. * Note: this column has a database default value of: 0 * @var int */ protected $votes; /** * The value for the comments field. * Note: this column has a database default value of: 0 * @var int */ protected $comments; /** * The value for the favorites field. * Note: this column has a database default value of: 0 * @var int */ protected $favorites; /** * The value for the total_rank field. * Note: this column has a database default value of: 0 * @var int */ protected $total_rank; /** * The value for the rank field. * Note: this column has a database default value of: 0 * @var int */ protected $rank; /** * The value for the tags field. * @var string */ protected $tags; /** * The value for the anonymous field. * @var int */ protected $anonymous; /** * The value for the status field. * @var int */ protected $status; /** * The value for the source field. * @var int */ protected $source; /** * The value for the source_id field. * @var string */ protected $source_id; /** * The value for the source_link field. * @var string */ protected $source_link; /** * The value for the license_type field. * @var int */ protected $license_type; /** * The value for the credit field. * @var string */ protected $credit; /** * The value for the length_in_msecs field. * Note: this column has a database default value of: 0 * @var int */ protected $length_in_msecs; /** * The value for the created_at field. * @var string */ protected $created_at; /** * The value for the updated_at field. * @var string */ protected $updated_at; /** * The value for the partner_id field. * Note: this column has a database default value of: 0 * @var int */ protected $partner_id; /** * The value for the display_in_search field. * @var int */ protected $display_in_search; /** * The value for the subp_id field. * Note: this column has a database default value of: 0 * @var int */ protected $subp_id; /** * The value for the custom_data field. * @var string */ protected $custom_data; /** * The value for the screen_name field. * @var string */ protected $screen_name; /** * The value for the site_url field. * @var string */ protected $site_url; /** * The value for the permissions field. * Note: this column has a database default value of: 1 * @var int */ protected $permissions; /** * The value for the group_id field. * @var string */ protected $group_id; /** * The value for the plays field. * Note: this column has a database default value of: 0 * @var int */ protected $plays; /** * The value for the partner_data field. * @var string */ protected $partner_data; /** * The value for the int_id field. * @var int */ protected $int_id; /** * The value for the indexed_custom_data_1 field. * @var int */ protected $indexed_custom_data_1; /** * The value for the description field. * @var string */ protected $description; /** * The value for the media_date field. * @var string */ protected $media_date; /** * The value for the admin_tags field. * @var string */ protected $admin_tags; /** * The value for the moderation_status field. * @var int */ protected $moderation_status; /** * The value for the moderation_count field. * @var int */ protected $moderation_count; /** * The value for the modified_at field. * @var string */ protected $modified_at; /** * The value for the puser_id field. * @var string */ protected $puser_id; /** * The value for the access_control_id field. * @var int */ protected $access_control_id; /** * The value for the conversion_profile_id field. * @var int */ protected $conversion_profile_id; /** * The value for the categories field. * @var string */ protected $categories; /** * The value for the categories_ids field. * @var string */ protected $categories_ids; /** * The value for the start_date field. * @var string */ protected $start_date; /** * The value for the end_date field. * @var string */ protected $end_date; /** * The value for the flavor_params_ids field. * @var string */ protected $flavor_params_ids; /** * The value for the available_from field. * @var string */ protected $available_from; /** * The value for the last_played_at field. * @var string */ protected $last_played_at; /** * @var kshow */ protected $akshow; /** * @var kuser */ protected $akuser; /** * @var accessControl */ protected $aaccessControl; /** * @var conversionProfile2 */ protected $aconversionProfile2; /** * @var array LiveChannelSegment[] Collection to store aggregation of LiveChannelSegment objects. */ protected $collLiveChannelSegmentsRelatedByChannelId; /** * @var Criteria The criteria used to select the current contents of collLiveChannelSegmentsRelatedByChannelId. */ private $lastLiveChannelSegmentRelatedByChannelIdCriteria = null; /** * @var array LiveChannelSegment[] Collection to store aggregation of LiveChannelSegment objects. */ protected $collLiveChannelSegmentsRelatedByEntryId; /** * @var Criteria The criteria used to select the current contents of collLiveChannelSegmentsRelatedByEntryId. */ private $lastLiveChannelSegmentRelatedByEntryIdCriteria = null; /** * @var array kvote[] Collection to store aggregation of kvote objects. */ protected $collkvotes; /** * @var Criteria The criteria used to select the current contents of collkvotes. */ private $lastkvoteCriteria = null; /** * @var array conversion[] Collection to store aggregation of conversion objects. */ protected $collconversions; /** * @var Criteria The criteria used to select the current contents of collconversions. */ private $lastconversionCriteria = null; /** * @var array WidgetLog[] Collection to store aggregation of WidgetLog objects. */ protected $collWidgetLogs; /** * @var Criteria The criteria used to select the current contents of collWidgetLogs. */ private $lastWidgetLogCriteria = null; /** * @var array moderationFlag[] Collection to store aggregation of moderationFlag objects. */ protected $collmoderationFlags; /** * @var Criteria The criteria used to select the current contents of collmoderationFlags. */ private $lastmoderationFlagCriteria = null; /** * @var array roughcutEntry[] Collection to store aggregation of roughcutEntry objects. */ protected $collroughcutEntrysRelatedByRoughcutId; /** * @var Criteria The criteria used to select the current contents of collroughcutEntrysRelatedByRoughcutId. */ private $lastroughcutEntryRelatedByRoughcutIdCriteria = null; /** * @var array roughcutEntry[] Collection to store aggregation of roughcutEntry objects. */ protected $collroughcutEntrysRelatedByEntryId; /** * @var Criteria The criteria used to select the current contents of collroughcutEntrysRelatedByEntryId. */ private $lastroughcutEntryRelatedByEntryIdCriteria = null; /** * @var array widget[] Collection to store aggregation of widget objects. */ protected $collwidgets; /** * @var Criteria The criteria used to select the current contents of collwidgets. */ private $lastwidgetCriteria = null; /** * @var array assetParamsOutput[] Collection to store aggregation of assetParamsOutput objects. */ protected $collassetParamsOutputs; /** * @var Criteria The criteria used to select the current contents of collassetParamsOutputs. */ private $lastassetParamsOutputCriteria = null; /** * @var array asset[] Collection to store aggregation of asset objects. */ protected $collassets; /** * @var Criteria The criteria used to select the current contents of collassets. */ private $lastassetCriteria = null; /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. * @var boolean */ protected $alreadyInSave = false; /** * Flag to indicate if save action actually affected the db. * @var boolean */ protected $objectSaved = false; /** * Flag to prevent endless validation loop, if this object is referenced * by another object which falls in this transaction. * @var boolean */ protected $alreadyInValidation = false; /** * Store columns old values before the changes * @var array */ protected $oldColumnsValues = array(); /** * @return array */ public function getColumnsOldValues() { return $this->oldColumnsValues; } /** * @return mixed field value or null */ public function getColumnsOldValue($name) { if(isset($this->oldColumnsValues[$name])) return $this->oldColumnsValues[$name]; return null; } /** * Applies default values to this object. * This method should be called from the object's constructor (or * equivalent initialization method). * @see __construct() */ public function applyDefaultValues() { $this->views = 0; $this->votes = 0; $this->comments = 0; $this->favorites = 0; $this->total_rank = 0; $this->rank = 0; $this->length_in_msecs = 0; $this->partner_id = 0; $this->subp_id = 0; $this->permissions = 1; $this->plays = 0; } /** * Initializes internal state of Baseentry object. * @see applyDefaults() */ public function __construct() { parent::__construct(); $this->applyDefaultValues(); } /** * Get the [id] column value. * * @return string */ public function getId() { return $this->id; } /** * Get the [kshow_id] column value. * * @return string */ public function getKshowId() { return $this->kshow_id; } /** * Get the [kuser_id] column value. * * @return int */ public function getKuserId() { return $this->kuser_id; } /** * Get the [name] column value. * * @return string */ public function getName() { return $this->name; } /** * Get the [type] column value. * * @return int */ public function getType() { return $this->type; } /** * Get the [media_type] column value. * * @return int */ public function getMediaType() { return $this->media_type; } /** * Get the [data] column value. * * @return string */ public function getData() { return $this->data; } /** * Get the [thumbnail] column value. * * @return string */ public function getThumbnail() { return $this->thumbnail; } /** * Get the [views] column value. * * @return int */ public function getViews() { return $this->views; } /** * Get the [votes] column value. * * @return int */ public function getVotes() { return $this->votes; } /** * Get the [comments] column value. * * @return int */ public function getComments() { return $this->comments; } /** * Get the [favorites] column value. * * @return int */ public function getFavorites() { return $this->favorites; } /** * Get the [total_rank] column value. * * @return int */ public function getTotalRank() { return $this->total_rank; } /** * Get the [rank] column value. * * @return int */ public function getRank() { return $this->rank; } /** * Get the [tags] column value. * * @return string */ public function getTags() { return $this->tags; } /** * Get the [anonymous] column value. * * @return int */ public function getAnonymous() { return $this->anonymous; } /** * Get the [status] column value. * * @return int */ public function getStatus() { return $this->status; } /** * Get the [source] column value. * * @return int */ public function getSource() { return $this->source; } /** * Get the [source_id] column value. * * @return string */ public function getSourceId() { return $this->source_id; } /** * Get the [source_link] column value. * * @return string */ public function getSourceLink() { return $this->source_link; } /** * Get the [license_type] column value. * * @return int */ public function getLicenseType() { return $this->license_type; } /** * Get the [credit] column value. * * @return string */ public function getCredit() { return $this->credit; } /** * Get the [length_in_msecs] column value. * * @return int */ public function getLengthInMsecs() { return $this->length_in_msecs; } /** * Get the [optionally formatted] temporal [created_at] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getCreatedAt($format = 'Y-m-d H:i:s') { if ($this->created_at === null) { return null; } if ($this->created_at === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->created_at); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->created_at, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Get the [optionally formatted] temporal [updated_at] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getUpdatedAt($format = 'Y-m-d H:i:s') { if ($this->updated_at === null) { return null; } if ($this->updated_at === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->updated_at); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->updated_at, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Get the [partner_id] column value. * * @return int */ public function getPartnerId() { return $this->partner_id; } /** * Get the [display_in_search] column value. * * @return int */ public function getDisplayInSearch() { return $this->display_in_search; } /** * Get the [subp_id] column value. * * @return int */ public function getSubpId() { return $this->subp_id; } /** * Get the [custom_data] column value. * * @return string */ public function getCustomData() { return $this->custom_data; } /** * Get the [screen_name] column value. * * @return string */ public function getScreenName() { return $this->screen_name; } /** * Get the [site_url] column value. * * @return string */ public function getSiteUrl() { return $this->site_url; } /** * Get the [permissions] column value. * * @return int */ public function getPermissions() { return $this->permissions; } /** * Get the [group_id] column value. * * @return string */ public function getGroupId() { return $this->group_id; } /** * Get the [plays] column value. * * @return int */ public function getPlays() { return $this->plays; } /** * Get the [partner_data] column value. * * @return string */ public function getPartnerData() { return $this->partner_data; } /** * Get the [int_id] column value. * * @return int */ public function getIntId() { return $this->int_id; } /** * Get the [indexed_custom_data_1] column value. * * @return int */ public function getIndexedCustomData1() { return $this->indexed_custom_data_1; } /** * Get the [description] column value. * * @return string */ public function getDescription() { return $this->description; } /** * Get the [optionally formatted] temporal [media_date] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getMediaDate($format = 'Y-m-d H:i:s') { if ($this->media_date === null) { return null; } if ($this->media_date === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->media_date); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->media_date, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Get the [admin_tags] column value. * * @return string */ public function getAdminTags() { return $this->admin_tags; } /** * Get the [moderation_status] column value. * * @return int */ public function getModerationStatus() { return $this->moderation_status; } /** * Get the [moderation_count] column value. * * @return int */ public function getModerationCount() { return $this->moderation_count; } /** * Get the [optionally formatted] temporal [modified_at] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getModifiedAt($format = 'Y-m-d H:i:s') { if ($this->modified_at === null) { return null; } if ($this->modified_at === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->modified_at); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->modified_at, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Get the [puser_id] column value. * * @return string */ public function getPuserId() { return $this->puser_id; } /** * Get the [access_control_id] column value. * * @return int */ public function getAccessControlId() { return $this->access_control_id; } /** * Get the [conversion_profile_id] column value. * * @return int */ public function getConversionProfileId() { return $this->conversion_profile_id; } /** * Get the [categories] column value. * * @return string */ public function getCategories() { return $this->categories; } /** * Get the [categories_ids] column value. * * @return string */ public function getCategoriesIds() { return $this->categories_ids; } /** * Get the [optionally formatted] temporal [start_date] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getStartDate($format = 'Y-m-d H:i:s') { if ($this->start_date === null) { return null; } if ($this->start_date === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->start_date); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->start_date, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Get the [optionally formatted] temporal [end_date] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getEndDate($format = 'Y-m-d H:i:s') { if ($this->end_date === null) { return null; } if ($this->end_date === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->end_date); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->end_date, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Get the [flavor_params_ids] column value. * * @return string */ public function getFlavorParamsIds() { return $this->flavor_params_ids; } /** * Get the [optionally formatted] temporal [available_from] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getAvailableFrom($format = 'Y-m-d H:i:s') { if ($this->available_from === null) { return null; } if ($this->available_from === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->available_from); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->available_from, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Get the [optionally formatted] temporal [last_played_at] column value. * * This accessor only only work with unix epoch dates. Consider enabling the propel.useDateTimeClass * option in order to avoid converstions to integers (which are limited in the dates they can express). * * @param string $format The date/time format string (either date()-style or strftime()-style). * If format is NULL, then the raw unix timestamp integer will be returned. * @return mixed Formatted date/time value as string or (integer) unix timestamp (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 * @throws PropelException - if unable to parse/validate the date/time value. */ public function getLastPlayedAt($format = 'Y-m-d H:i:s') { if ($this->last_played_at === null) { return null; } if ($this->last_played_at === '0000-00-00 00:00:00') { // while technically this is not a default value of NULL, // this seems to be closest in meaning. return null; } else { try { $dt = new DateTime($this->last_played_at); } catch (Exception $x) { throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->last_played_at, true), $x); } } if ($format === null) { // We cast here to maintain BC in API; obviously we will lose data if we're dealing with pre-/post-epoch dates. return (int) $dt->format('U'); } elseif (strpos($format, '%') !== false) { return strftime($format, $dt->format('U')); } else { return $dt->format($format); } } /** * Set the value of [id] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setId($v) { if(!isset($this->oldColumnsValues[entryPeer::ID])) $this->oldColumnsValues[entryPeer::ID] = $this->id; if ($v !== null) { $v = (string) $v; } if ($this->id !== $v) { $this->id = $v; $this->modifiedColumns[] = entryPeer::ID; } return $this; } // setId() /** * Set the value of [kshow_id] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setKshowId($v) { if(!isset($this->oldColumnsValues[entryPeer::KSHOW_ID])) $this->oldColumnsValues[entryPeer::KSHOW_ID] = $this->kshow_id; if ($v !== null) { $v = (string) $v; } if ($this->kshow_id !== $v) { $this->kshow_id = $v; $this->modifiedColumns[] = entryPeer::KSHOW_ID; } if ($this->akshow !== null && $this->akshow->getId() !== $v) { $this->akshow = null; } return $this; } // setKshowId() /** * Set the value of [kuser_id] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setKuserId($v) { if(!isset($this->oldColumnsValues[entryPeer::KUSER_ID])) $this->oldColumnsValues[entryPeer::KUSER_ID] = $this->kuser_id; if ($v !== null) { $v = (int) $v; } if ($this->kuser_id !== $v) { $this->kuser_id = $v; $this->modifiedColumns[] = entryPeer::KUSER_ID; } if ($this->akuser !== null && $this->akuser->getId() !== $v) { $this->akuser = null; } return $this; } // setKuserId() /** * Set the value of [name] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setName($v) { if(!isset($this->oldColumnsValues[entryPeer::NAME])) $this->oldColumnsValues[entryPeer::NAME] = $this->name; if ($v !== null) { $v = (string) $v; } if ($this->name !== $v) { $this->name = $v; $this->modifiedColumns[] = entryPeer::NAME; } return $this; } // setName() /** * Set the value of [type] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setType($v) { if(!isset($this->oldColumnsValues[entryPeer::TYPE])) $this->oldColumnsValues[entryPeer::TYPE] = $this->type; if ($v !== null) { $v = (int) $v; } if ($this->type !== $v) { $this->type = $v; $this->modifiedColumns[] = entryPeer::TYPE; } return $this; } // setType() /** * Set the value of [media_type] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setMediaType($v) { if(!isset($this->oldColumnsValues[entryPeer::MEDIA_TYPE])) $this->oldColumnsValues[entryPeer::MEDIA_TYPE] = $this->media_type; if ($v !== null) { $v = (int) $v; } if ($this->media_type !== $v) { $this->media_type = $v; $this->modifiedColumns[] = entryPeer::MEDIA_TYPE; } return $this; } // setMediaType() /** * Set the value of [data] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setData($v) { if(!isset($this->oldColumnsValues[entryPeer::DATA])) $this->oldColumnsValues[entryPeer::DATA] = $this->data; if ($v !== null) { $v = (string) $v; } if ($this->data !== $v) { $this->data = $v; $this->modifiedColumns[] = entryPeer::DATA; } return $this; } // setData() /** * Set the value of [thumbnail] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setThumbnail($v) { if(!isset($this->oldColumnsValues[entryPeer::THUMBNAIL])) $this->oldColumnsValues[entryPeer::THUMBNAIL] = $this->thumbnail; if ($v !== null) { $v = (string) $v; } if ($this->thumbnail !== $v) { $this->thumbnail = $v; $this->modifiedColumns[] = entryPeer::THUMBNAIL; } return $this; } // setThumbnail() /** * Set the value of [views] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setViews($v) { if(!isset($this->oldColumnsValues[entryPeer::VIEWS])) $this->oldColumnsValues[entryPeer::VIEWS] = $this->views; if ($v !== null) { $v = (int) $v; } if ($this->views !== $v || $this->isNew()) { $this->views = $v; $this->modifiedColumns[] = entryPeer::VIEWS; } return $this; } // setViews() /** * Set the value of [votes] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setVotes($v) { if(!isset($this->oldColumnsValues[entryPeer::VOTES])) $this->oldColumnsValues[entryPeer::VOTES] = $this->votes; if ($v !== null) { $v = (int) $v; } if ($this->votes !== $v || $this->isNew()) { $this->votes = $v; $this->modifiedColumns[] = entryPeer::VOTES; } return $this; } // setVotes() /** * Set the value of [comments] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setComments($v) { if(!isset($this->oldColumnsValues[entryPeer::COMMENTS])) $this->oldColumnsValues[entryPeer::COMMENTS] = $this->comments; if ($v !== null) { $v = (int) $v; } if ($this->comments !== $v || $this->isNew()) { $this->comments = $v; $this->modifiedColumns[] = entryPeer::COMMENTS; } return $this; } // setComments() /** * Set the value of [favorites] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setFavorites($v) { if(!isset($this->oldColumnsValues[entryPeer::FAVORITES])) $this->oldColumnsValues[entryPeer::FAVORITES] = $this->favorites; if ($v !== null) { $v = (int) $v; } if ($this->favorites !== $v || $this->isNew()) { $this->favorites = $v; $this->modifiedColumns[] = entryPeer::FAVORITES; } return $this; } // setFavorites() /** * Set the value of [total_rank] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setTotalRank($v) { if(!isset($this->oldColumnsValues[entryPeer::TOTAL_RANK])) $this->oldColumnsValues[entryPeer::TOTAL_RANK] = $this->total_rank; if ($v !== null) { $v = (int) $v; } if ($this->total_rank !== $v || $this->isNew()) { $this->total_rank = $v; $this->modifiedColumns[] = entryPeer::TOTAL_RANK; } return $this; } // setTotalRank() /** * Set the value of [rank] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setRank($v) { if(!isset($this->oldColumnsValues[entryPeer::RANK])) $this->oldColumnsValues[entryPeer::RANK] = $this->rank; if ($v !== null) { $v = (int) $v; } if ($this->rank !== $v || $this->isNew()) { $this->rank = $v; $this->modifiedColumns[] = entryPeer::RANK; } return $this; } // setRank() /** * Set the value of [tags] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setTags($v) { if(!isset($this->oldColumnsValues[entryPeer::TAGS])) $this->oldColumnsValues[entryPeer::TAGS] = $this->tags; if ($v !== null) { $v = (string) $v; } if ($this->tags !== $v) { $this->tags = $v; $this->modifiedColumns[] = entryPeer::TAGS; } return $this; } // setTags() /** * Set the value of [anonymous] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setAnonymous($v) { if(!isset($this->oldColumnsValues[entryPeer::ANONYMOUS])) $this->oldColumnsValues[entryPeer::ANONYMOUS] = $this->anonymous; if ($v !== null) { $v = (int) $v; } if ($this->anonymous !== $v) { $this->anonymous = $v; $this->modifiedColumns[] = entryPeer::ANONYMOUS; } return $this; } // setAnonymous() /** * Set the value of [status] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setStatus($v) { if(!isset($this->oldColumnsValues[entryPeer::STATUS])) $this->oldColumnsValues[entryPeer::STATUS] = $this->status; if ($v !== null) { $v = (int) $v; } if ($this->status !== $v) { $this->status = $v; $this->modifiedColumns[] = entryPeer::STATUS; } return $this; } // setStatus() /** * Set the value of [source] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setSource($v) { if(!isset($this->oldColumnsValues[entryPeer::SOURCE])) $this->oldColumnsValues[entryPeer::SOURCE] = $this->source; if ($v !== null) { $v = (int) $v; } if ($this->source !== $v) { $this->source = $v; $this->modifiedColumns[] = entryPeer::SOURCE; } return $this; } // setSource() /** * Set the value of [source_id] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setSourceId($v) { if(!isset($this->oldColumnsValues[entryPeer::SOURCE_ID])) $this->oldColumnsValues[entryPeer::SOURCE_ID] = $this->source_id; if ($v !== null) { $v = (string) $v; } if ($this->source_id !== $v) { $this->source_id = $v; $this->modifiedColumns[] = entryPeer::SOURCE_ID; } return $this; } // setSourceId() /** * Set the value of [source_link] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setSourceLink($v) { if(!isset($this->oldColumnsValues[entryPeer::SOURCE_LINK])) $this->oldColumnsValues[entryPeer::SOURCE_LINK] = $this->source_link; if ($v !== null) { $v = (string) $v; } if ($this->source_link !== $v) { $this->source_link = $v; $this->modifiedColumns[] = entryPeer::SOURCE_LINK; } return $this; } // setSourceLink() /** * Set the value of [license_type] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setLicenseType($v) { if(!isset($this->oldColumnsValues[entryPeer::LICENSE_TYPE])) $this->oldColumnsValues[entryPeer::LICENSE_TYPE] = $this->license_type; if ($v !== null) { $v = (int) $v; } if ($this->license_type !== $v) { $this->license_type = $v; $this->modifiedColumns[] = entryPeer::LICENSE_TYPE; } return $this; } // setLicenseType() /** * Set the value of [credit] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setCredit($v) { if(!isset($this->oldColumnsValues[entryPeer::CREDIT])) $this->oldColumnsValues[entryPeer::CREDIT] = $this->credit; if ($v !== null) { $v = (string) $v; } if ($this->credit !== $v) { $this->credit = $v; $this->modifiedColumns[] = entryPeer::CREDIT; } return $this; } // setCredit() /** * Set the value of [length_in_msecs] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setLengthInMsecs($v) { if(!isset($this->oldColumnsValues[entryPeer::LENGTH_IN_MSECS])) $this->oldColumnsValues[entryPeer::LENGTH_IN_MSECS] = $this->length_in_msecs; if ($v !== null) { $v = (int) $v; } if ($this->length_in_msecs !== $v || $this->isNew()) { $this->length_in_msecs = $v; $this->modifiedColumns[] = entryPeer::LENGTH_IN_MSECS; } return $this; } // setLengthInMsecs() /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setCreatedAt($v) { // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->created_at !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->created_at !== null && $tmpDt = new DateTime($this->created_at)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->created_at = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::CREATED_AT; } } // if either are not null return $this; } // setCreatedAt() /** * Sets the value of [updated_at] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setUpdatedAt($v) { // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->updated_at !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->updated_at !== null && $tmpDt = new DateTime($this->updated_at)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->updated_at = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::UPDATED_AT; } } // if either are not null return $this; } // setUpdatedAt() /** * Set the value of [partner_id] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setPartnerId($v) { if(!isset($this->oldColumnsValues[entryPeer::PARTNER_ID])) $this->oldColumnsValues[entryPeer::PARTNER_ID] = $this->partner_id; if ($v !== null) { $v = (int) $v; } if ($this->partner_id !== $v || $this->isNew()) { $this->partner_id = $v; $this->modifiedColumns[] = entryPeer::PARTNER_ID; } return $this; } // setPartnerId() /** * Set the value of [display_in_search] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setDisplayInSearch($v) { if(!isset($this->oldColumnsValues[entryPeer::DISPLAY_IN_SEARCH])) $this->oldColumnsValues[entryPeer::DISPLAY_IN_SEARCH] = $this->display_in_search; if ($v !== null) { $v = (int) $v; } if ($this->display_in_search !== $v) { $this->display_in_search = $v; $this->modifiedColumns[] = entryPeer::DISPLAY_IN_SEARCH; } return $this; } // setDisplayInSearch() /** * Set the value of [subp_id] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setSubpId($v) { if(!isset($this->oldColumnsValues[entryPeer::SUBP_ID])) $this->oldColumnsValues[entryPeer::SUBP_ID] = $this->subp_id; if ($v !== null) { $v = (int) $v; } if ($this->subp_id !== $v || $this->isNew()) { $this->subp_id = $v; $this->modifiedColumns[] = entryPeer::SUBP_ID; } return $this; } // setSubpId() /** * Set the value of [custom_data] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setCustomData($v) { if ($v !== null) { $v = (string) $v; } if ($this->custom_data !== $v) { $this->custom_data = $v; $this->modifiedColumns[] = entryPeer::CUSTOM_DATA; } return $this; } // setCustomData() /** * Set the value of [screen_name] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setScreenName($v) { if(!isset($this->oldColumnsValues[entryPeer::SCREEN_NAME])) $this->oldColumnsValues[entryPeer::SCREEN_NAME] = $this->screen_name; if ($v !== null) { $v = (string) $v; } if ($this->screen_name !== $v) { $this->screen_name = $v; $this->modifiedColumns[] = entryPeer::SCREEN_NAME; } return $this; } // setScreenName() /** * Set the value of [site_url] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setSiteUrl($v) { if(!isset($this->oldColumnsValues[entryPeer::SITE_URL])) $this->oldColumnsValues[entryPeer::SITE_URL] = $this->site_url; if ($v !== null) { $v = (string) $v; } if ($this->site_url !== $v) { $this->site_url = $v; $this->modifiedColumns[] = entryPeer::SITE_URL; } return $this; } // setSiteUrl() /** * Set the value of [permissions] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setPermissions($v) { if(!isset($this->oldColumnsValues[entryPeer::PERMISSIONS])) $this->oldColumnsValues[entryPeer::PERMISSIONS] = $this->permissions; if ($v !== null) { $v = (int) $v; } if ($this->permissions !== $v || $this->isNew()) { $this->permissions = $v; $this->modifiedColumns[] = entryPeer::PERMISSIONS; } return $this; } // setPermissions() /** * Set the value of [group_id] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setGroupId($v) { if(!isset($this->oldColumnsValues[entryPeer::GROUP_ID])) $this->oldColumnsValues[entryPeer::GROUP_ID] = $this->group_id; if ($v !== null) { $v = (string) $v; } if ($this->group_id !== $v) { $this->group_id = $v; $this->modifiedColumns[] = entryPeer::GROUP_ID; } return $this; } // setGroupId() /** * Set the value of [plays] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setPlays($v) { if(!isset($this->oldColumnsValues[entryPeer::PLAYS])) $this->oldColumnsValues[entryPeer::PLAYS] = $this->plays; if ($v !== null) { $v = (int) $v; } if ($this->plays !== $v || $this->isNew()) { $this->plays = $v; $this->modifiedColumns[] = entryPeer::PLAYS; } return $this; } // setPlays() /** * Set the value of [partner_data] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setPartnerData($v) { if(!isset($this->oldColumnsValues[entryPeer::PARTNER_DATA])) $this->oldColumnsValues[entryPeer::PARTNER_DATA] = $this->partner_data; if ($v !== null) { $v = (string) $v; } if ($this->partner_data !== $v) { $this->partner_data = $v; $this->modifiedColumns[] = entryPeer::PARTNER_DATA; } return $this; } // setPartnerData() /** * Set the value of [int_id] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setIntId($v) { if(!isset($this->oldColumnsValues[entryPeer::INT_ID])) $this->oldColumnsValues[entryPeer::INT_ID] = $this->int_id; if ($v !== null) { $v = (int) $v; } if ($this->int_id !== $v) { $this->int_id = $v; $this->modifiedColumns[] = entryPeer::INT_ID; } return $this; } // setIntId() /** * Set the value of [indexed_custom_data_1] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setIndexedCustomData1($v) { if(!isset($this->oldColumnsValues[entryPeer::INDEXED_CUSTOM_DATA_1])) $this->oldColumnsValues[entryPeer::INDEXED_CUSTOM_DATA_1] = $this->indexed_custom_data_1; if ($v !== null) { $v = (int) $v; } if ($this->indexed_custom_data_1 !== $v) { $this->indexed_custom_data_1 = $v; $this->modifiedColumns[] = entryPeer::INDEXED_CUSTOM_DATA_1; } return $this; } // setIndexedCustomData1() /** * Set the value of [description] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setDescription($v) { if(!isset($this->oldColumnsValues[entryPeer::DESCRIPTION])) $this->oldColumnsValues[entryPeer::DESCRIPTION] = $this->description; if ($v !== null) { $v = (string) $v; } if ($this->description !== $v) { $this->description = $v; $this->modifiedColumns[] = entryPeer::DESCRIPTION; } return $this; } // setDescription() /** * Sets the value of [media_date] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setMediaDate($v) { if(!isset($this->oldColumnsValues[entryPeer::MEDIA_DATE])) $this->oldColumnsValues[entryPeer::MEDIA_DATE] = $this->media_date; // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->media_date !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->media_date !== null && $tmpDt = new DateTime($this->media_date)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->media_date = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::MEDIA_DATE; } } // if either are not null return $this; } // setMediaDate() /** * Set the value of [admin_tags] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setAdminTags($v) { if(!isset($this->oldColumnsValues[entryPeer::ADMIN_TAGS])) $this->oldColumnsValues[entryPeer::ADMIN_TAGS] = $this->admin_tags; if ($v !== null) { $v = (string) $v; } if ($this->admin_tags !== $v) { $this->admin_tags = $v; $this->modifiedColumns[] = entryPeer::ADMIN_TAGS; } return $this; } // setAdminTags() /** * Set the value of [moderation_status] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setModerationStatus($v) { if(!isset($this->oldColumnsValues[entryPeer::MODERATION_STATUS])) $this->oldColumnsValues[entryPeer::MODERATION_STATUS] = $this->moderation_status; if ($v !== null) { $v = (int) $v; } if ($this->moderation_status !== $v) { $this->moderation_status = $v; $this->modifiedColumns[] = entryPeer::MODERATION_STATUS; } return $this; } // setModerationStatus() /** * Set the value of [moderation_count] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setModerationCount($v) { if(!isset($this->oldColumnsValues[entryPeer::MODERATION_COUNT])) $this->oldColumnsValues[entryPeer::MODERATION_COUNT] = $this->moderation_count; if ($v !== null) { $v = (int) $v; } if ($this->moderation_count !== $v) { $this->moderation_count = $v; $this->modifiedColumns[] = entryPeer::MODERATION_COUNT; } return $this; } // setModerationCount() /** * Sets the value of [modified_at] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setModifiedAt($v) { if(!isset($this->oldColumnsValues[entryPeer::MODIFIED_AT])) $this->oldColumnsValues[entryPeer::MODIFIED_AT] = $this->modified_at; // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->modified_at !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->modified_at !== null && $tmpDt = new DateTime($this->modified_at)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->modified_at = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::MODIFIED_AT; } } // if either are not null return $this; } // setModifiedAt() /** * Set the value of [puser_id] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setPuserId($v) { if(!isset($this->oldColumnsValues[entryPeer::PUSER_ID])) $this->oldColumnsValues[entryPeer::PUSER_ID] = $this->puser_id; if ($v !== null) { $v = (string) $v; } if ($this->puser_id !== $v) { $this->puser_id = $v; $this->modifiedColumns[] = entryPeer::PUSER_ID; } return $this; } // setPuserId() /** * Set the value of [access_control_id] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setAccessControlId($v) { if(!isset($this->oldColumnsValues[entryPeer::ACCESS_CONTROL_ID])) $this->oldColumnsValues[entryPeer::ACCESS_CONTROL_ID] = $this->access_control_id; if ($v !== null) { $v = (int) $v; } if ($this->access_control_id !== $v) { $this->access_control_id = $v; $this->modifiedColumns[] = entryPeer::ACCESS_CONTROL_ID; } if ($this->aaccessControl !== null && $this->aaccessControl->getId() !== $v) { $this->aaccessControl = null; } return $this; } // setAccessControlId() /** * Set the value of [conversion_profile_id] column. * * @param int $v new value * @return entry The current object (for fluent API support) */ public function setConversionProfileId($v) { if(!isset($this->oldColumnsValues[entryPeer::CONVERSION_PROFILE_ID])) $this->oldColumnsValues[entryPeer::CONVERSION_PROFILE_ID] = $this->conversion_profile_id; if ($v !== null) { $v = (int) $v; } if ($this->conversion_profile_id !== $v) { $this->conversion_profile_id = $v; $this->modifiedColumns[] = entryPeer::CONVERSION_PROFILE_ID; } if ($this->aconversionProfile2 !== null && $this->aconversionProfile2->getId() !== $v) { $this->aconversionProfile2 = null; } return $this; } // setConversionProfileId() /** * Set the value of [categories] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setCategories($v) { if(!isset($this->oldColumnsValues[entryPeer::CATEGORIES])) $this->oldColumnsValues[entryPeer::CATEGORIES] = $this->categories; if ($v !== null) { $v = (string) $v; } if ($this->categories !== $v) { $this->categories = $v; $this->modifiedColumns[] = entryPeer::CATEGORIES; } return $this; } // setCategories() /** * Set the value of [categories_ids] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setCategoriesIds($v) { if(!isset($this->oldColumnsValues[entryPeer::CATEGORIES_IDS])) $this->oldColumnsValues[entryPeer::CATEGORIES_IDS] = $this->categories_ids; if ($v !== null) { $v = (string) $v; } if ($this->categories_ids !== $v) { $this->categories_ids = $v; $this->modifiedColumns[] = entryPeer::CATEGORIES_IDS; } return $this; } // setCategoriesIds() /** * Sets the value of [start_date] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setStartDate($v) { if(!isset($this->oldColumnsValues[entryPeer::START_DATE])) $this->oldColumnsValues[entryPeer::START_DATE] = $this->start_date; // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->start_date !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->start_date !== null && $tmpDt = new DateTime($this->start_date)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->start_date = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::START_DATE; } } // if either are not null return $this; } // setStartDate() /** * Sets the value of [end_date] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setEndDate($v) { if(!isset($this->oldColumnsValues[entryPeer::END_DATE])) $this->oldColumnsValues[entryPeer::END_DATE] = $this->end_date; // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->end_date !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->end_date !== null && $tmpDt = new DateTime($this->end_date)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->end_date = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::END_DATE; } } // if either are not null return $this; } // setEndDate() /** * Set the value of [flavor_params_ids] column. * * @param string $v new value * @return entry The current object (for fluent API support) */ public function setFlavorParamsIds($v) { if(!isset($this->oldColumnsValues[entryPeer::FLAVOR_PARAMS_IDS])) $this->oldColumnsValues[entryPeer::FLAVOR_PARAMS_IDS] = $this->flavor_params_ids; if ($v !== null) { $v = (string) $v; } if ($this->flavor_params_ids !== $v) { $this->flavor_params_ids = $v; $this->modifiedColumns[] = entryPeer::FLAVOR_PARAMS_IDS; } return $this; } // setFlavorParamsIds() /** * Sets the value of [available_from] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setAvailableFrom($v) { if(!isset($this->oldColumnsValues[entryPeer::AVAILABLE_FROM])) $this->oldColumnsValues[entryPeer::AVAILABLE_FROM] = $this->available_from; // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->available_from !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->available_from !== null && $tmpDt = new DateTime($this->available_from)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->available_from = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::AVAILABLE_FROM; } } // if either are not null return $this; } // setAvailableFrom() /** * Sets the value of [last_played_at] column to a normalized version of the date/time value specified. * * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will * be treated as NULL for temporal objects. * @return entry The current object (for fluent API support) */ public function setLastPlayedAt($v) { if(!isset($this->oldColumnsValues[entryPeer::LAST_PLAYED_AT])) $this->oldColumnsValues[entryPeer::LAST_PLAYED_AT] = $this->last_played_at; // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') // -- which is unexpected, to say the least. if ($v === null || $v === '') { $dt = null; } elseif ($v instanceof DateTime) { $dt = $v; } else { // some string/numeric value passed; we normalize that so that we can // validate it. try { if (is_numeric($v)) { // if it's a unix timestamp $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); // We have to explicitly specify and then change the time zone because of a // DateTime bug: http://bugs.php.net/bug.php?id=43003 $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); } else { $dt = new DateTime($v); } } catch (Exception $x) { throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); } } if ( $this->last_played_at !== null || $dt !== null ) { // (nested ifs are a little easier to read in this case) $currNorm = ($this->last_played_at !== null && $tmpDt = new DateTime($this->last_played_at)) ? $tmpDt->format('Y-m-d H:i:s') : null; $newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null; if ( ($currNorm !== $newNorm) // normalized values don't match ) { $this->last_played_at = ($dt ? $dt->format('Y-m-d H:i:s') : null); $this->modifiedColumns[] = entryPeer::LAST_PLAYED_AT; } } // if either are not null return $this; } // setLastPlayedAt() /** * Indicates whether the columns in this object are only set to default values. * * This method can be used in conjunction with isModified() to indicate whether an object is both * modified _and_ has some values set which are non-default. * * @return boolean Whether the columns in this object are only been set with default values. */ public function hasOnlyDefaultValues() { if ($this->views !== 0) { return false; } if ($this->votes !== 0) { return false; } if ($this->comments !== 0) { return false; } if ($this->favorites !== 0) { return false; } if ($this->total_rank !== 0) { return false; } if ($this->rank !== 0) { return false; } if ($this->length_in_msecs !== 0) { return false; } if ($this->partner_id !== 0) { return false; } if ($this->subp_id !== 0) { return false; } if ($this->permissions !== 1) { return false; } if ($this->plays !== 0) { return false; } // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() /** * Hydrates (populates) the object variables with values from the database resultset. * * An offset (0-based "start column") is specified so that objects can be hydrated * with a subset of the columns in the resultset rows. This is needed, for example, * for results of JOIN queries where the resultset row includes columns from two or * more tables. * * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) * @param int $startcol 0-based offset column which indicates which restultset column to start with. * @param boolean $rehydrate Whether this object is being re-hydrated from the database. * @return int next starting column * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. */ public function hydrate($row, $startcol = 0, $rehydrate = false) { try { $this->id = ($row[$startcol + 0] !== null) ? (string) $row[$startcol + 0] : null; $this->kshow_id = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; $this->kuser_id = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; $this->name = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; $this->type = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null; $this->media_type = ($row[$startcol + 5] !== null) ? (int) $row[$startcol + 5] : null; $this->data = ($row[$startcol + 6] !== null) ? (string) $row[$startcol + 6] : null; $this->thumbnail = ($row[$startcol + 7] !== null) ? (string) $row[$startcol + 7] : null; $this->views = ($row[$startcol + 8] !== null) ? (int) $row[$startcol + 8] : null; $this->votes = ($row[$startcol + 9] !== null) ? (int) $row[$startcol + 9] : null; $this->comments = ($row[$startcol + 10] !== null) ? (int) $row[$startcol + 10] : null; $this->favorites = ($row[$startcol + 11] !== null) ? (int) $row[$startcol + 11] : null; $this->total_rank = ($row[$startcol + 12] !== null) ? (int) $row[$startcol + 12] : null; $this->rank = ($row[$startcol + 13] !== null) ? (int) $row[$startcol + 13] : null; $this->tags = ($row[$startcol + 14] !== null) ? (string) $row[$startcol + 14] : null; $this->anonymous = ($row[$startcol + 15] !== null) ? (int) $row[$startcol + 15] : null; $this->status = ($row[$startcol + 16] !== null) ? (int) $row[$startcol + 16] : null; $this->source = ($row[$startcol + 17] !== null) ? (int) $row[$startcol + 17] : null; $this->source_id = ($row[$startcol + 18] !== null) ? (string) $row[$startcol + 18] : null; $this->source_link = ($row[$startcol + 19] !== null) ? (string) $row[$startcol + 19] : null; $this->license_type = ($row[$startcol + 20] !== null) ? (int) $row[$startcol + 20] : null; $this->credit = ($row[$startcol + 21] !== null) ? (string) $row[$startcol + 21] : null; $this->length_in_msecs = ($row[$startcol + 22] !== null) ? (int) $row[$startcol + 22] : null; $this->created_at = ($row[$startcol + 23] !== null) ? (string) $row[$startcol + 23] : null; $this->updated_at = ($row[$startcol + 24] !== null) ? (string) $row[$startcol + 24] : null; $this->partner_id = ($row[$startcol + 25] !== null) ? (int) $row[$startcol + 25] : null; $this->display_in_search = ($row[$startcol + 26] !== null) ? (int) $row[$startcol + 26] : null; $this->subp_id = ($row[$startcol + 27] !== null) ? (int) $row[$startcol + 27] : null; $this->custom_data = ($row[$startcol + 28] !== null) ? (string) $row[$startcol + 28] : null; $this->screen_name = ($row[$startcol + 29] !== null) ? (string) $row[$startcol + 29] : null; $this->site_url = ($row[$startcol + 30] !== null) ? (string) $row[$startcol + 30] : null; $this->permissions = ($row[$startcol + 31] !== null) ? (int) $row[$startcol + 31] : null; $this->group_id = ($row[$startcol + 32] !== null) ? (string) $row[$startcol + 32] : null; $this->plays = ($row[$startcol + 33] !== null) ? (int) $row[$startcol + 33] : null; $this->partner_data = ($row[$startcol + 34] !== null) ? (string) $row[$startcol + 34] : null; $this->int_id = ($row[$startcol + 35] !== null) ? (int) $row[$startcol + 35] : null; $this->indexed_custom_data_1 = ($row[$startcol + 36] !== null) ? (int) $row[$startcol + 36] : null; $this->description = ($row[$startcol + 37] !== null) ? (string) $row[$startcol + 37] : null; $this->media_date = ($row[$startcol + 38] !== null) ? (string) $row[$startcol + 38] : null; $this->admin_tags = ($row[$startcol + 39] !== null) ? (string) $row[$startcol + 39] : null; $this->moderation_status = ($row[$startcol + 40] !== null) ? (int) $row[$startcol + 40] : null; $this->moderation_count = ($row[$startcol + 41] !== null) ? (int) $row[$startcol + 41] : null; $this->modified_at = ($row[$startcol + 42] !== null) ? (string) $row[$startcol + 42] : null; $this->puser_id = ($row[$startcol + 43] !== null) ? (string) $row[$startcol + 43] : null; $this->access_control_id = ($row[$startcol + 44] !== null) ? (int) $row[$startcol + 44] : null; $this->conversion_profile_id = ($row[$startcol + 45] !== null) ? (int) $row[$startcol + 45] : null; $this->categories = ($row[$startcol + 46] !== null) ? (string) $row[$startcol + 46] : null; $this->categories_ids = ($row[$startcol + 47] !== null) ? (string) $row[$startcol + 47] : null; $this->start_date = ($row[$startcol + 48] !== null) ? (string) $row[$startcol + 48] : null; $this->end_date = ($row[$startcol + 49] !== null) ? (string) $row[$startcol + 49] : null; $this->flavor_params_ids = ($row[$startcol + 50] !== null) ? (string) $row[$startcol + 50] : null; $this->available_from = ($row[$startcol + 51] !== null) ? (string) $row[$startcol + 51] : null; $this->last_played_at = ($row[$startcol + 52] !== null) ? (string) $row[$startcol + 52] : null; $this->resetModified(); $this->setNew(false); if ($rehydrate) { $this->ensureConsistency(); } // FIXME - using NUM_COLUMNS may be clearer. return $startcol + 53; // 53 = entryPeer::NUM_COLUMNS - entryPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating entry object", $e); } } /** * Checks and repairs the internal consistency of the object. * * This method is executed after an already-instantiated object is re-hydrated * from the database. It exists to check any foreign keys to make sure that * the objects related to the current object are correct based on foreign key. * * You can override this method in the stub class, but you should always invoke * the base method from the overridden method (i.e. parent::ensureConsistency()), * in case your model changes. * * @throws PropelException */ public function ensureConsistency() { if ($this->akshow !== null && $this->kshow_id !== $this->akshow->getId()) { $this->akshow = null; } if ($this->akuser !== null && $this->kuser_id !== $this->akuser->getId()) { $this->akuser = null; } if ($this->aaccessControl !== null && $this->access_control_id !== $this->aaccessControl->getId()) { $this->aaccessControl = null; } if ($this->aconversionProfile2 !== null && $this->conversion_profile_id !== $this->aconversionProfile2->getId()) { $this->aconversionProfile2 = null; } } // ensureConsistency /** * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. * * This will only work if the object has been saved and has a valid primary key set. * * @param boolean $deep (optional) Whether to also de-associated any related objects. * @param PropelPDO $con (optional) The PropelPDO connection to use. * @return void * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db */ public function reload($deep = false, PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("Cannot reload a deleted object."); } if ($this->isNew()) { throw new PropelException("Cannot reload an unsaved object."); } if ($con === null) { $con = Propel::getConnection(entryPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // We don't need to alter the object instance pool; we're just modifying this instance // already in the pool. entryPeer::setUseCriteriaFilter(false); $criteria = $this->buildPkeyCriteria(); entryPeer::addSelectColumns($criteria); $stmt = BasePeer::doSelect($criteria, $con); entryPeer::setUseCriteriaFilter(true); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { throw new PropelException('Cannot find matching row in the database to reload object values.'); } $this->hydrate($row, 0, true); // rehydrate if ($deep) { // also de-associate any related objects? $this->akshow = null; $this->akuser = null; $this->aaccessControl = null; $this->aconversionProfile2 = null; $this->collLiveChannelSegmentsRelatedByChannelId = null; $this->lastLiveChannelSegmentRelatedByChannelIdCriteria = null; $this->collLiveChannelSegmentsRelatedByEntryId = null; $this->lastLiveChannelSegmentRelatedByEntryIdCriteria = null; $this->collkvotes = null; $this->lastkvoteCriteria = null; $this->collconversions = null; $this->lastconversionCriteria = null; $this->collWidgetLogs = null; $this->lastWidgetLogCriteria = null; $this->collmoderationFlags = null; $this->lastmoderationFlagCriteria = null; $this->collroughcutEntrysRelatedByRoughcutId = null; $this->lastroughcutEntryRelatedByRoughcutIdCriteria = null; $this->collroughcutEntrysRelatedByEntryId = null; $this->lastroughcutEntryRelatedByEntryIdCriteria = null; $this->collwidgets = null; $this->lastwidgetCriteria = null; $this->collassetParamsOutputs = null; $this->lastassetParamsOutputCriteria = null; $this->collassets = null; $this->lastassetCriteria = null; } // if (deep) } /** * Removes this object from datastore and sets delete attribute. * * @param PropelPDO $con * @return void * @throws PropelException * @see BaseObject::setDeleted() * @see BaseObject::isDeleted() */ public function delete(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getConnection(entryPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); if ($ret) { entryPeer::doDelete($this, $con); $this->postDelete($con); $this->setDeleted(true); $con->commit(); } else { $con->commit(); } } catch (PropelException $e) { $con->rollBack(); throw $e; } } /** * Persists this object to the database. * * If the object is new, it inserts it; otherwise an update is performed. * All modified related objects will also be persisted in the doSave() * method. This method wraps all precipitate database operations in a * single transaction. * * Since this table was configured to reload rows on insert, the object will * be reloaded from the database if an INSERT operation is performed (unless * the $skipReload parameter is TRUE). * * @param PropelPDO $con * @param boolean $skipReload Whether to skip the reload for this object from database. * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see doSave() */ public function save(PropelPDO $con = null, $skipReload = false) { if ($this->isDeleted()) { throw new PropelException("You cannot save an object that has been deleted."); } if ($con === null) { $con = Propel::getConnection(entryPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); $isInsert = $this->isNew(); try { $ret = $this->preSave($con); if ($isInsert) { $ret = $ret && $this->preInsert($con); } else { $ret = $ret && $this->preUpdate($con); } if (!$ret || !$this->isModified()) { $con->commit(); return 0; } for ($retries = 1; $retries < KalturaPDO::SAVE_MAX_RETRIES; $retries++) { $affectedRows = $this->doSave($con); if ($affectedRows || !$this->isColumnModified(entryPeer::CUSTOM_DATA)) //ask if custom_data wasn't modified to avoid retry with atomic column break; KalturaLog::debug("was unable to save! retrying for the $retries time"); $criteria = $this->buildPkeyCriteria(); $criteria->addSelectColumn(entryPeer::CUSTOM_DATA); $stmt = BasePeer::doSelect($criteria, $con); $cutsomDataArr = $stmt->fetchAll(PDO::FETCH_COLUMN); $newCustomData = $cutsomDataArr[0]; $this->custom_data_md5 = md5($newCustomData); $valuesToChangeTo = $this->m_custom_data->toArray(); $this->m_custom_data = myCustomData::fromString($newCustomData); //set custom data column values we wanted to change to foreach ($this->oldCustomDataValues as $namespace => $namespaceValues){ foreach($namespaceValues as $name => $oldValue) { $newValue = null; if ($namespace) { if (isset ($valuesToChangeTo[$namespace][$name])) $newValue = $valuesToChangeTo[$namespace][$name]; } else { $newValue = $valuesToChangeTo[$name]; } if (!is_null($newValue)) $this->putInCustomData($name, $newValue, $namespace); } } $this->setCustomData($this->m_custom_data->toString()); } if ($isInsert) { $this->postInsert($con); } else { $this->postUpdate($con); } $this->postSave($con); entryPeer::addInstanceToPool($this); $con->commit(); return $affectedRows; } catch (PropelException $e) { $con->rollBack(); throw $e; } } public function wasObjectSaved() { return $this->objectSaved; } /** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @param boolean $skipReload Whether to skip the reload for this object from database. * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con, $skipReload = false) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; $reloadObject = false; // We call the save method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->akshow !== null) { if ($this->akshow->isModified() || $this->akshow->isNew()) { $affectedRows += $this->akshow->save($con); } $this->setkshow($this->akshow); } if ($this->akuser !== null) { if ($this->akuser->isModified() || $this->akuser->isNew()) { $affectedRows += $this->akuser->save($con); } $this->setkuser($this->akuser); } if ($this->aaccessControl !== null) { if ($this->aaccessControl->isModified() || $this->aaccessControl->isNew()) { $affectedRows += $this->aaccessControl->save($con); } $this->setaccessControl($this->aaccessControl); } if ($this->aconversionProfile2 !== null) { if ($this->aconversionProfile2->isModified() || $this->aconversionProfile2->isNew()) { $affectedRows += $this->aconversionProfile2->save($con); } $this->setconversionProfile2($this->aconversionProfile2); } // If this object has been modified, then save it to the database. $this->objectSaved = false; if ($this->isModified()) { if ($this->isNew()) { $pk = entryPeer::doInsert($this, $con); if (!$skipReload) { $reloadObject = true; } $affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which // should always be true here (even though technically // BasePeer::doInsert() can insert multiple rows). $this->setNew(false); $this->objectSaved = true; } else { $affectedObjects = entryPeer::doUpdate($this, $con); if($affectedObjects) $this->objectSaved = true; $affectedRows += $affectedObjects; } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } if ($this->collLiveChannelSegmentsRelatedByChannelId !== null) { foreach ($this->collLiveChannelSegmentsRelatedByChannelId as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collLiveChannelSegmentsRelatedByEntryId !== null) { foreach ($this->collLiveChannelSegmentsRelatedByEntryId as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collkvotes !== null) { foreach ($this->collkvotes as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collconversions !== null) { foreach ($this->collconversions as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collWidgetLogs !== null) { foreach ($this->collWidgetLogs as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collmoderationFlags !== null) { foreach ($this->collmoderationFlags as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collroughcutEntrysRelatedByRoughcutId !== null) { foreach ($this->collroughcutEntrysRelatedByRoughcutId as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collroughcutEntrysRelatedByEntryId !== null) { foreach ($this->collroughcutEntrysRelatedByEntryId as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collwidgets !== null) { foreach ($this->collwidgets as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collassetParamsOutputs !== null) { foreach ($this->collassetParamsOutputs as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } if ($this->collassets !== null) { foreach ($this->collassets as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } $this->alreadyInSave = false; if ($reloadObject) { $this->reload($con); } } return $affectedRows; } // doSave() /** * Override in order to use the query cache. * Cache invalidation keys are used to determine when cached queries are valid. * Before returning a query result from the cache, the time of the cached query * is compared to the time saved in the invalidation key. * A cached query will only be used if it's newer than the matching invalidation key. * * @return array Array of keys that will should be updated when this object is modified. */ public function getCacheInvalidationKeys() { return array(); } /** * Code to be run before persisting the object * @param PropelPDO $con * @return boolean */ public function preSave(PropelPDO $con = null) { $this->setCustomDataObj(); return parent::preSave($con); } /** * Code to be run after persisting the object * @param PropelPDO $con */ public function postSave(PropelPDO $con = null) { kEventsManager::raiseEvent(new kObjectSavedEvent($this)); $this->oldColumnsValues = array(); $this->oldCustomDataValues = array(); parent::postSave($con); } /** * Code to be run before inserting to database * @param PropelPDO $con * @return boolean */ public function preInsert(PropelPDO $con = null) { $this->setCreatedAt(time()); $this->setUpdatedAt(time()); return parent::preInsert($con); } /** * Code to be run after inserting to database * @param PropelPDO $con */ public function postInsert(PropelPDO $con = null) { kQueryCache::invalidateQueryCache($this); kEventsManager::raiseEvent(new kObjectCreatedEvent($this)); if($this->copiedFrom) kEventsManager::raiseEvent(new kObjectCopiedEvent($this->copiedFrom, $this)); parent::postInsert($con); } /** * Code to be run after updating the object in database * @param PropelPDO $con */ public function postUpdate(PropelPDO $con = null) { if ($this->alreadyInSave) { return; } if($this->isModified()) { kQueryCache::invalidateQueryCache($this); kEventsManager::raiseEvent(new kObjectChangedEvent($this, $this->tempModifiedColumns)); } $this->tempModifiedColumns = array(); parent::postUpdate($con); } /** * Saves the modified columns temporarily while saving * @var array */ private $tempModifiedColumns = array(); /** * Returns whether the object has been modified. * * @return boolean True if the object has been modified. */ public function isModified() { if(!empty($this->tempModifiedColumns)) return true; return !empty($this->modifiedColumns); } /** * Has specified column been modified? * * @param string $col * @return boolean True if $col has been modified. */ public function isColumnModified($col) { if(in_array($col, $this->tempModifiedColumns)) return true; return in_array($col, $this->modifiedColumns); } /** * Code to be run before updating the object in database * @param PropelPDO $con * @return boolean */ public function preUpdate(PropelPDO $con = null) { if ($this->alreadyInSave) { return true; } if($this->isModified()) $this->setUpdatedAt(time()); $this->tempModifiedColumns = $this->modifiedColumns; return parent::preUpdate($con); } /** * Array of ValidationFailed objects. * @var array ValidationFailed[] */ protected $validationFailures = array(); /** * Gets any ValidationFailed objects that resulted from last call to validate(). * * * @return array ValidationFailed[] * @see validate() */ public function getValidationFailures() { return $this->validationFailures; } /** * Validates the objects modified field values and all objects related to this table. * * If $columns is either a column name or an array of column names * only those columns are validated. * * @param mixed $columns Column name or an array of column names. * @return boolean Whether all columns pass validation. * @see doValidate() * @see getValidationFailures() */ public function validate($columns = null) { $res = $this->doValidate($columns); if ($res === true) { $this->validationFailures = array(); return true; } else { $this->validationFailures = $res; return false; } } /** * This function performs the validation work for complex object models. * * In addition to checking the current object, all related objects will * also be validated. If all pass then <code>true</code> is returned; otherwise * an aggreagated array of ValidationFailed objects will be returned. * * @param array $columns Array of column names to validate. * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise. */ protected function doValidate($columns = null) { if (!$this->alreadyInValidation) { $this->alreadyInValidation = true; $retval = null; $failureMap = array(); // We call the validate method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->akshow !== null) { if (!$this->akshow->validate($columns)) { $failureMap = array_merge($failureMap, $this->akshow->getValidationFailures()); } } if ($this->akuser !== null) { if (!$this->akuser->validate($columns)) { $failureMap = array_merge($failureMap, $this->akuser->getValidationFailures()); } } if ($this->aaccessControl !== null) { if (!$this->aaccessControl->validate($columns)) { $failureMap = array_merge($failureMap, $this->aaccessControl->getValidationFailures()); } } if ($this->aconversionProfile2 !== null) { if (!$this->aconversionProfile2->validate($columns)) { $failureMap = array_merge($failureMap, $this->aconversionProfile2->getValidationFailures()); } } if (($retval = entryPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } if ($this->collLiveChannelSegmentsRelatedByChannelId !== null) { foreach ($this->collLiveChannelSegmentsRelatedByChannelId as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collLiveChannelSegmentsRelatedByEntryId !== null) { foreach ($this->collLiveChannelSegmentsRelatedByEntryId as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collkvotes !== null) { foreach ($this->collkvotes as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collconversions !== null) { foreach ($this->collconversions as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collWidgetLogs !== null) { foreach ($this->collWidgetLogs as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collmoderationFlags !== null) { foreach ($this->collmoderationFlags as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collroughcutEntrysRelatedByRoughcutId !== null) { foreach ($this->collroughcutEntrysRelatedByRoughcutId as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collroughcutEntrysRelatedByEntryId !== null) { foreach ($this->collroughcutEntrysRelatedByEntryId as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collwidgets !== null) { foreach ($this->collwidgets as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collassetParamsOutputs !== null) { foreach ($this->collassetParamsOutputs as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } if ($this->collassets !== null) { foreach ($this->collassets as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } $this->alreadyInValidation = false; } return (!empty($failureMap) ? $failureMap : true); } /** * Retrieves a field from the object by name passed in as a string. * * @param string $name name * @param string $type The type of fieldname the $name is of: * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM * @return mixed Value of field. */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { $pos = entryPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } /** * Retrieves a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @return mixed Value of field at $pos */ public function getByPosition($pos) { switch($pos) { case 0: return $this->getId(); break; case 1: return $this->getKshowId(); break; case 2: return $this->getKuserId(); break; case 3: return $this->getName(); break; case 4: return $this->getType(); break; case 5: return $this->getMediaType(); break; case 6: return $this->getData(); break; case 7: return $this->getThumbnail(); break; case 8: return $this->getViews(); break; case 9: return $this->getVotes(); break; case 10: return $this->getComments(); break; case 11: return $this->getFavorites(); break; case 12: return $this->getTotalRank(); break; case 13: return $this->getRank(); break; case 14: return $this->getTags(); break; case 15: return $this->getAnonymous(); break; case 16: return $this->getStatus(); break; case 17: return $this->getSource(); break; case 18: return $this->getSourceId(); break; case 19: return $this->getSourceLink(); break; case 20: return $this->getLicenseType(); break; case 21: return $this->getCredit(); break; case 22: return $this->getLengthInMsecs(); break; case 23: return $this->getCreatedAt(); break; case 24: return $this->getUpdatedAt(); break; case 25: return $this->getPartnerId(); break; case 26: return $this->getDisplayInSearch(); break; case 27: return $this->getSubpId(); break; case 28: return $this->getCustomData(); break; case 29: return $this->getScreenName(); break; case 30: return $this->getSiteUrl(); break; case 31: return $this->getPermissions(); break; case 32: return $this->getGroupId(); break; case 33: return $this->getPlays(); break; case 34: return $this->getPartnerData(); break; case 35: return $this->getIntId(); break; case 36: return $this->getIndexedCustomData1(); break; case 37: return $this->getDescription(); break; case 38: return $this->getMediaDate(); break; case 39: return $this->getAdminTags(); break; case 40: return $this->getModerationStatus(); break; case 41: return $this->getModerationCount(); break; case 42: return $this->getModifiedAt(); break; case 43: return $this->getPuserId(); break; case 44: return $this->getAccessControlId(); break; case 45: return $this->getConversionProfileId(); break; case 46: return $this->getCategories(); break; case 47: return $this->getCategoriesIds(); break; case 48: return $this->getStartDate(); break; case 49: return $this->getEndDate(); break; case 50: return $this->getFlavorParamsIds(); break; case 51: return $this->getAvailableFrom(); break; case 52: return $this->getLastPlayedAt(); break; default: return null; break; } // switch() } /** * Exports the object as an array. * * You can specify the key type of the array by passing one of the class * type constants. * * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. Defaults to BasePeer::TYPE_PHPNAME. * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. * @return an associative array containing the field names (as keys) and field values */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true) { $keys = entryPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getId(), $keys[1] => $this->getKshowId(), $keys[2] => $this->getKuserId(), $keys[3] => $this->getName(), $keys[4] => $this->getType(), $keys[5] => $this->getMediaType(), $keys[6] => $this->getData(), $keys[7] => $this->getThumbnail(), $keys[8] => $this->getViews(), $keys[9] => $this->getVotes(), $keys[10] => $this->getComments(), $keys[11] => $this->getFavorites(), $keys[12] => $this->getTotalRank(), $keys[13] => $this->getRank(), $keys[14] => $this->getTags(), $keys[15] => $this->getAnonymous(), $keys[16] => $this->getStatus(), $keys[17] => $this->getSource(), $keys[18] => $this->getSourceId(), $keys[19] => $this->getSourceLink(), $keys[20] => $this->getLicenseType(), $keys[21] => $this->getCredit(), $keys[22] => $this->getLengthInMsecs(), $keys[23] => $this->getCreatedAt(), $keys[24] => $this->getUpdatedAt(), $keys[25] => $this->getPartnerId(), $keys[26] => $this->getDisplayInSearch(), $keys[27] => $this->getSubpId(), $keys[28] => $this->getCustomData(), $keys[29] => $this->getScreenName(), $keys[30] => $this->getSiteUrl(), $keys[31] => $this->getPermissions(), $keys[32] => $this->getGroupId(), $keys[33] => $this->getPlays(), $keys[34] => $this->getPartnerData(), $keys[35] => $this->getIntId(), $keys[36] => $this->getIndexedCustomData1(), $keys[37] => $this->getDescription(), $keys[38] => $this->getMediaDate(), $keys[39] => $this->getAdminTags(), $keys[40] => $this->getModerationStatus(), $keys[41] => $this->getModerationCount(), $keys[42] => $this->getModifiedAt(), $keys[43] => $this->getPuserId(), $keys[44] => $this->getAccessControlId(), $keys[45] => $this->getConversionProfileId(), $keys[46] => $this->getCategories(), $keys[47] => $this->getCategoriesIds(), $keys[48] => $this->getStartDate(), $keys[49] => $this->getEndDate(), $keys[50] => $this->getFlavorParamsIds(), $keys[51] => $this->getAvailableFrom(), $keys[52] => $this->getLastPlayedAt(), ); return $result; } /** * Sets a field from the object by name passed in as a string. * * @param string $name peer name * @param mixed $value field value * @param string $type The type of fieldname the $name is of: * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM * @return void */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { $pos = entryPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } /** * Sets a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @param mixed $value field value * @return void */ public function setByPosition($pos, $value) { switch($pos) { case 0: $this->setId($value); break; case 1: $this->setKshowId($value); break; case 2: $this->setKuserId($value); break; case 3: $this->setName($value); break; case 4: $this->setType($value); break; case 5: $this->setMediaType($value); break; case 6: $this->setData($value); break; case 7: $this->setThumbnail($value); break; case 8: $this->setViews($value); break; case 9: $this->setVotes($value); break; case 10: $this->setComments($value); break; case 11: $this->setFavorites($value); break; case 12: $this->setTotalRank($value); break; case 13: $this->setRank($value); break; case 14: $this->setTags($value); break; case 15: $this->setAnonymous($value); break; case 16: $this->setStatus($value); break; case 17: $this->setSource($value); break; case 18: $this->setSourceId($value); break; case 19: $this->setSourceLink($value); break; case 20: $this->setLicenseType($value); break; case 21: $this->setCredit($value); break; case 22: $this->setLengthInMsecs($value); break; case 23: $this->setCreatedAt($value); break; case 24: $this->setUpdatedAt($value); break; case 25: $this->setPartnerId($value); break; case 26: $this->setDisplayInSearch($value); break; case 27: $this->setSubpId($value); break; case 28: $this->setCustomData($value); break; case 29: $this->setScreenName($value); break; case 30: $this->setSiteUrl($value); break; case 31: $this->setPermissions($value); break; case 32: $this->setGroupId($value); break; case 33: $this->setPlays($value); break; case 34: $this->setPartnerData($value); break; case 35: $this->setIntId($value); break; case 36: $this->setIndexedCustomData1($value); break; case 37: $this->setDescription($value); break; case 38: $this->setMediaDate($value); break; case 39: $this->setAdminTags($value); break; case 40: $this->setModerationStatus($value); break; case 41: $this->setModerationCount($value); break; case 42: $this->setModifiedAt($value); break; case 43: $this->setPuserId($value); break; case 44: $this->setAccessControlId($value); break; case 45: $this->setConversionProfileId($value); break; case 46: $this->setCategories($value); break; case 47: $this->setCategoriesIds($value); break; case 48: $this->setStartDate($value); break; case 49: $this->setEndDate($value); break; case 50: $this->setFlavorParamsIds($value); break; case 51: $this->setAvailableFrom($value); break; case 52: $this->setLastPlayedAt($value); break; } // switch() } /** * Populates the object using an array. * * This is particularly useful when populating an object from one of the * request arrays (e.g. $_POST). This method goes through the column * names, checking to see whether a matching key exists in populated * array. If so the setByName() method is called for that column. * * You can specify the key type of the array by additionally passing one * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. * The default key type is the column's phpname (e.g. 'AuthorId') * * @param array $arr An array to populate the object from. * @param string $keyType The type of keys the array uses. * @return void */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { $keys = entryPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setKshowId($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setKuserId($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setName($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setType($arr[$keys[4]]); if (array_key_exists($keys[5], $arr)) $this->setMediaType($arr[$keys[5]]); if (array_key_exists($keys[6], $arr)) $this->setData($arr[$keys[6]]); if (array_key_exists($keys[7], $arr)) $this->setThumbnail($arr[$keys[7]]); if (array_key_exists($keys[8], $arr)) $this->setViews($arr[$keys[8]]); if (array_key_exists($keys[9], $arr)) $this->setVotes($arr[$keys[9]]); if (array_key_exists($keys[10], $arr)) $this->setComments($arr[$keys[10]]); if (array_key_exists($keys[11], $arr)) $this->setFavorites($arr[$keys[11]]); if (array_key_exists($keys[12], $arr)) $this->setTotalRank($arr[$keys[12]]); if (array_key_exists($keys[13], $arr)) $this->setRank($arr[$keys[13]]); if (array_key_exists($keys[14], $arr)) $this->setTags($arr[$keys[14]]); if (array_key_exists($keys[15], $arr)) $this->setAnonymous($arr[$keys[15]]); if (array_key_exists($keys[16], $arr)) $this->setStatus($arr[$keys[16]]); if (array_key_exists($keys[17], $arr)) $this->setSource($arr[$keys[17]]); if (array_key_exists($keys[18], $arr)) $this->setSourceId($arr[$keys[18]]); if (array_key_exists($keys[19], $arr)) $this->setSourceLink($arr[$keys[19]]); if (array_key_exists($keys[20], $arr)) $this->setLicenseType($arr[$keys[20]]); if (array_key_exists($keys[21], $arr)) $this->setCredit($arr[$keys[21]]); if (array_key_exists($keys[22], $arr)) $this->setLengthInMsecs($arr[$keys[22]]); if (array_key_exists($keys[23], $arr)) $this->setCreatedAt($arr[$keys[23]]); if (array_key_exists($keys[24], $arr)) $this->setUpdatedAt($arr[$keys[24]]); if (array_key_exists($keys[25], $arr)) $this->setPartnerId($arr[$keys[25]]); if (array_key_exists($keys[26], $arr)) $this->setDisplayInSearch($arr[$keys[26]]); if (array_key_exists($keys[27], $arr)) $this->setSubpId($arr[$keys[27]]); if (array_key_exists($keys[28], $arr)) $this->setCustomData($arr[$keys[28]]); if (array_key_exists($keys[29], $arr)) $this->setScreenName($arr[$keys[29]]); if (array_key_exists($keys[30], $arr)) $this->setSiteUrl($arr[$keys[30]]); if (array_key_exists($keys[31], $arr)) $this->setPermissions($arr[$keys[31]]); if (array_key_exists($keys[32], $arr)) $this->setGroupId($arr[$keys[32]]); if (array_key_exists($keys[33], $arr)) $this->setPlays($arr[$keys[33]]); if (array_key_exists($keys[34], $arr)) $this->setPartnerData($arr[$keys[34]]); if (array_key_exists($keys[35], $arr)) $this->setIntId($arr[$keys[35]]); if (array_key_exists($keys[36], $arr)) $this->setIndexedCustomData1($arr[$keys[36]]); if (array_key_exists($keys[37], $arr)) $this->setDescription($arr[$keys[37]]); if (array_key_exists($keys[38], $arr)) $this->setMediaDate($arr[$keys[38]]); if (array_key_exists($keys[39], $arr)) $this->setAdminTags($arr[$keys[39]]); if (array_key_exists($keys[40], $arr)) $this->setModerationStatus($arr[$keys[40]]); if (array_key_exists($keys[41], $arr)) $this->setModerationCount($arr[$keys[41]]); if (array_key_exists($keys[42], $arr)) $this->setModifiedAt($arr[$keys[42]]); if (array_key_exists($keys[43], $arr)) $this->setPuserId($arr[$keys[43]]); if (array_key_exists($keys[44], $arr)) $this->setAccessControlId($arr[$keys[44]]); if (array_key_exists($keys[45], $arr)) $this->setConversionProfileId($arr[$keys[45]]); if (array_key_exists($keys[46], $arr)) $this->setCategories($arr[$keys[46]]); if (array_key_exists($keys[47], $arr)) $this->setCategoriesIds($arr[$keys[47]]); if (array_key_exists($keys[48], $arr)) $this->setStartDate($arr[$keys[48]]); if (array_key_exists($keys[49], $arr)) $this->setEndDate($arr[$keys[49]]); if (array_key_exists($keys[50], $arr)) $this->setFlavorParamsIds($arr[$keys[50]]); if (array_key_exists($keys[51], $arr)) $this->setAvailableFrom($arr[$keys[51]]); if (array_key_exists($keys[52], $arr)) $this->setLastPlayedAt($arr[$keys[52]]); } /** * Build a Criteria object containing the values of all modified columns in this object. * * @return Criteria The Criteria object containing all modified values. */ public function buildCriteria() { $criteria = new Criteria(entryPeer::DATABASE_NAME); if ($this->isColumnModified(entryPeer::ID)) $criteria->add(entryPeer::ID, $this->id); if ($this->isColumnModified(entryPeer::KSHOW_ID)) $criteria->add(entryPeer::KSHOW_ID, $this->kshow_id); if ($this->isColumnModified(entryPeer::KUSER_ID)) $criteria->add(entryPeer::KUSER_ID, $this->kuser_id); if ($this->isColumnModified(entryPeer::NAME)) $criteria->add(entryPeer::NAME, $this->name); if ($this->isColumnModified(entryPeer::TYPE)) $criteria->add(entryPeer::TYPE, $this->type); if ($this->isColumnModified(entryPeer::MEDIA_TYPE)) $criteria->add(entryPeer::MEDIA_TYPE, $this->media_type); if ($this->isColumnModified(entryPeer::DATA)) $criteria->add(entryPeer::DATA, $this->data); if ($this->isColumnModified(entryPeer::THUMBNAIL)) $criteria->add(entryPeer::THUMBNAIL, $this->thumbnail); if ($this->isColumnModified(entryPeer::VIEWS)) $criteria->add(entryPeer::VIEWS, $this->views); if ($this->isColumnModified(entryPeer::VOTES)) $criteria->add(entryPeer::VOTES, $this->votes); if ($this->isColumnModified(entryPeer::COMMENTS)) $criteria->add(entryPeer::COMMENTS, $this->comments); if ($this->isColumnModified(entryPeer::FAVORITES)) $criteria->add(entryPeer::FAVORITES, $this->favorites); if ($this->isColumnModified(entryPeer::TOTAL_RANK)) $criteria->add(entryPeer::TOTAL_RANK, $this->total_rank); if ($this->isColumnModified(entryPeer::RANK)) $criteria->add(entryPeer::RANK, $this->rank); if ($this->isColumnModified(entryPeer::TAGS)) $criteria->add(entryPeer::TAGS, $this->tags); if ($this->isColumnModified(entryPeer::ANONYMOUS)) $criteria->add(entryPeer::ANONYMOUS, $this->anonymous); if ($this->isColumnModified(entryPeer::STATUS)) $criteria->add(entryPeer::STATUS, $this->status); if ($this->isColumnModified(entryPeer::SOURCE)) $criteria->add(entryPeer::SOURCE, $this->source); if ($this->isColumnModified(entryPeer::SOURCE_ID)) $criteria->add(entryPeer::SOURCE_ID, $this->source_id); if ($this->isColumnModified(entryPeer::SOURCE_LINK)) $criteria->add(entryPeer::SOURCE_LINK, $this->source_link); if ($this->isColumnModified(entryPeer::LICENSE_TYPE)) $criteria->add(entryPeer::LICENSE_TYPE, $this->license_type); if ($this->isColumnModified(entryPeer::CREDIT)) $criteria->add(entryPeer::CREDIT, $this->credit); if ($this->isColumnModified(entryPeer::LENGTH_IN_MSECS)) $criteria->add(entryPeer::LENGTH_IN_MSECS, $this->length_in_msecs); if ($this->isColumnModified(entryPeer::CREATED_AT)) $criteria->add(entryPeer::CREATED_AT, $this->created_at); if ($this->isColumnModified(entryPeer::UPDATED_AT)) $criteria->add(entryPeer::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(entryPeer::PARTNER_ID)) $criteria->add(entryPeer::PARTNER_ID, $this->partner_id); if ($this->isColumnModified(entryPeer::DISPLAY_IN_SEARCH)) $criteria->add(entryPeer::DISPLAY_IN_SEARCH, $this->display_in_search); if ($this->isColumnModified(entryPeer::SUBP_ID)) $criteria->add(entryPeer::SUBP_ID, $this->subp_id); if ($this->isColumnModified(entryPeer::CUSTOM_DATA)) $criteria->add(entryPeer::CUSTOM_DATA, $this->custom_data); if ($this->isColumnModified(entryPeer::SCREEN_NAME)) $criteria->add(entryPeer::SCREEN_NAME, $this->screen_name); if ($this->isColumnModified(entryPeer::SITE_URL)) $criteria->add(entryPeer::SITE_URL, $this->site_url); if ($this->isColumnModified(entryPeer::PERMISSIONS)) $criteria->add(entryPeer::PERMISSIONS, $this->permissions); if ($this->isColumnModified(entryPeer::GROUP_ID)) $criteria->add(entryPeer::GROUP_ID, $this->group_id); if ($this->isColumnModified(entryPeer::PLAYS)) $criteria->add(entryPeer::PLAYS, $this->plays); if ($this->isColumnModified(entryPeer::PARTNER_DATA)) $criteria->add(entryPeer::PARTNER_DATA, $this->partner_data); if ($this->isColumnModified(entryPeer::INT_ID)) $criteria->add(entryPeer::INT_ID, $this->int_id); if ($this->isColumnModified(entryPeer::INDEXED_CUSTOM_DATA_1)) $criteria->add(entryPeer::INDEXED_CUSTOM_DATA_1, $this->indexed_custom_data_1); if ($this->isColumnModified(entryPeer::DESCRIPTION)) $criteria->add(entryPeer::DESCRIPTION, $this->description); if ($this->isColumnModified(entryPeer::MEDIA_DATE)) $criteria->add(entryPeer::MEDIA_DATE, $this->media_date); if ($this->isColumnModified(entryPeer::ADMIN_TAGS)) $criteria->add(entryPeer::ADMIN_TAGS, $this->admin_tags); if ($this->isColumnModified(entryPeer::MODERATION_STATUS)) $criteria->add(entryPeer::MODERATION_STATUS, $this->moderation_status); if ($this->isColumnModified(entryPeer::MODERATION_COUNT)) $criteria->add(entryPeer::MODERATION_COUNT, $this->moderation_count); if ($this->isColumnModified(entryPeer::MODIFIED_AT)) $criteria->add(entryPeer::MODIFIED_AT, $this->modified_at); if ($this->isColumnModified(entryPeer::PUSER_ID)) $criteria->add(entryPeer::PUSER_ID, $this->puser_id); if ($this->isColumnModified(entryPeer::ACCESS_CONTROL_ID)) $criteria->add(entryPeer::ACCESS_CONTROL_ID, $this->access_control_id); if ($this->isColumnModified(entryPeer::CONVERSION_PROFILE_ID)) $criteria->add(entryPeer::CONVERSION_PROFILE_ID, $this->conversion_profile_id); if ($this->isColumnModified(entryPeer::CATEGORIES)) $criteria->add(entryPeer::CATEGORIES, $this->categories); if ($this->isColumnModified(entryPeer::CATEGORIES_IDS)) $criteria->add(entryPeer::CATEGORIES_IDS, $this->categories_ids); if ($this->isColumnModified(entryPeer::START_DATE)) $criteria->add(entryPeer::START_DATE, $this->start_date); if ($this->isColumnModified(entryPeer::END_DATE)) $criteria->add(entryPeer::END_DATE, $this->end_date); if ($this->isColumnModified(entryPeer::FLAVOR_PARAMS_IDS)) $criteria->add(entryPeer::FLAVOR_PARAMS_IDS, $this->flavor_params_ids); if ($this->isColumnModified(entryPeer::AVAILABLE_FROM)) $criteria->add(entryPeer::AVAILABLE_FROM, $this->available_from); if ($this->isColumnModified(entryPeer::LAST_PLAYED_AT)) $criteria->add(entryPeer::LAST_PLAYED_AT, $this->last_played_at); return $criteria; } /** * Builds a Criteria object containing the primary key for this object. * * Unlike buildCriteria() this method includes the primary key values regardless * of whether or not they have been modified. * * @return Criteria The Criteria object containing value(s) for primary key(s). */ public function buildPkeyCriteria() { $criteria = new Criteria(entryPeer::DATABASE_NAME); $criteria->add(entryPeer::ID, $this->id); if($this->alreadyInSave) { if ($this->isColumnModified(entryPeer::CUSTOM_DATA)) { if (!is_null($this->custom_data_md5)) $criteria->add(entryPeer::CUSTOM_DATA, "MD5(cast(" . entryPeer::CUSTOM_DATA . " as char character set latin1)) = '$this->custom_data_md5'", Criteria::CUSTOM); //casting to latin char set to avoid mysql and php md5 difference else $criteria->add(entryPeer::CUSTOM_DATA, NULL, Criteria::ISNULL); } if (count($this->modifiedColumns) == 2 && $this->isColumnModified(entryPeer::UPDATED_AT)) { $theModifiedColumn = null; foreach($this->modifiedColumns as $modifiedColumn) if($modifiedColumn != entryPeer::UPDATED_AT) $theModifiedColumn = $modifiedColumn; $atomicColumns = entryPeer::getAtomicColumns(); if(in_array($theModifiedColumn, $atomicColumns)) $criteria->add($theModifiedColumn, $this->getByName($theModifiedColumn, BasePeer::TYPE_COLNAME), Criteria::NOT_EQUAL); } } return $criteria; } /** * Returns the primary key for this object (row). * @return string */ public function getPrimaryKey() { return $this->getId(); } /** * Generic method to set the primary key (id column). * * @param string $key Primary key. * @return void */ public function setPrimaryKey($key) { $this->setId($key); } /** * Sets contents of passed object to values from current object. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param object $copyObj An object of entry (or compatible) type. * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @throws PropelException */ public function copyInto($copyObj, $deepCopy = false) { $copyObj->setId($this->id); $copyObj->setKshowId($this->kshow_id); $copyObj->setKuserId($this->kuser_id); $copyObj->setName($this->name); $copyObj->setType($this->type); $copyObj->setMediaType($this->media_type); $copyObj->setData($this->data); $copyObj->setThumbnail($this->thumbnail); $copyObj->setViews($this->views); $copyObj->setVotes($this->votes); $copyObj->setComments($this->comments); $copyObj->setFavorites($this->favorites); $copyObj->setTotalRank($this->total_rank); $copyObj->setRank($this->rank); $copyObj->setTags($this->tags); $copyObj->setAnonymous($this->anonymous); $copyObj->setStatus($this->status); $copyObj->setSource($this->source); $copyObj->setSourceId($this->source_id); $copyObj->setSourceLink($this->source_link); $copyObj->setLicenseType($this->license_type); $copyObj->setCredit($this->credit); $copyObj->setLengthInMsecs($this->length_in_msecs); $copyObj->setCreatedAt($this->created_at); $copyObj->setUpdatedAt($this->updated_at); $copyObj->setPartnerId($this->partner_id); $copyObj->setDisplayInSearch($this->display_in_search); $copyObj->setSubpId($this->subp_id); $copyObj->setCustomData($this->custom_data); $copyObj->setScreenName($this->screen_name); $copyObj->setSiteUrl($this->site_url); $copyObj->setPermissions($this->permissions); $copyObj->setGroupId($this->group_id); $copyObj->setPlays($this->plays); $copyObj->setPartnerData($this->partner_data); $copyObj->setIndexedCustomData1($this->indexed_custom_data_1); $copyObj->setDescription($this->description); $copyObj->setMediaDate($this->media_date); $copyObj->setAdminTags($this->admin_tags); $copyObj->setModerationStatus($this->moderation_status); $copyObj->setModerationCount($this->moderation_count); $copyObj->setModifiedAt($this->modified_at); $copyObj->setPuserId($this->puser_id); $copyObj->setAccessControlId($this->access_control_id); $copyObj->setConversionProfileId($this->conversion_profile_id); $copyObj->setCategories($this->categories); $copyObj->setCategoriesIds($this->categories_ids); $copyObj->setStartDate($this->start_date); $copyObj->setEndDate($this->end_date); $copyObj->setFlavorParamsIds($this->flavor_params_ids); $copyObj->setAvailableFrom($this->available_from); $copyObj->setLastPlayedAt($this->last_played_at); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of // the getter/setter methods for fkey referrer objects. $copyObj->setNew(false); foreach ($this->getLiveChannelSegmentsRelatedByChannelId() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addLiveChannelSegmentRelatedByChannelId($relObj->copy($deepCopy)); } } foreach ($this->getLiveChannelSegmentsRelatedByEntryId() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addLiveChannelSegmentRelatedByEntryId($relObj->copy($deepCopy)); } } foreach ($this->getkvotes() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addkvote($relObj->copy($deepCopy)); } } foreach ($this->getconversions() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addconversion($relObj->copy($deepCopy)); } } foreach ($this->getWidgetLogs() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addWidgetLog($relObj->copy($deepCopy)); } } foreach ($this->getmoderationFlags() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addmoderationFlag($relObj->copy($deepCopy)); } } foreach ($this->getroughcutEntrysRelatedByRoughcutId() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addroughcutEntryRelatedByRoughcutId($relObj->copy($deepCopy)); } } foreach ($this->getroughcutEntrysRelatedByEntryId() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addroughcutEntryRelatedByEntryId($relObj->copy($deepCopy)); } } foreach ($this->getwidgets() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addwidget($relObj->copy($deepCopy)); } } foreach ($this->getassetParamsOutputs() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addassetParamsOutput($relObj->copy($deepCopy)); } } foreach ($this->getassets() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addasset($relObj->copy($deepCopy)); } } } // if ($deepCopy) $copyObj->setNew(true); $copyObj->setIntId(NULL); // this is a auto-increment column, so set to default value } /** * Makes a copy of this object that will be inserted as a new row in table when saved. * It creates a new object filling in the simple attributes, but skipping any primary * keys that are defined for the table. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @return entry Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) { // we use get_class(), because this might be a subclass $clazz = get_class($this); $copyObj = new $clazz(); $this->copyInto($copyObj, $deepCopy); $copyObj->setCopiedFrom($this); return $copyObj; } /** * Stores the source object that this object copied from * * @var entry Clone of current object. */ protected $copiedFrom = null; /** * Stores the source object that this object copied from * * @param entry $copiedFrom Clone of current object. */ public function setCopiedFrom(entry $copiedFrom) { $this->copiedFrom = $copiedFrom; } /** * Returns a peer instance associated with this om. * * Since Peer classes are not to have any instance attributes, this method returns the * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * * @return entryPeer */ public function getPeer() { if (self::$peer === null) { self::$peer = new entryPeer(); } return self::$peer; } /** * Declares an association between this object and a kshow object. * * @param kshow $v * @return entry The current object (for fluent API support) * @throws PropelException */ public function setkshow(kshow $v = null) { if ($v === null) { $this->setKshowId(NULL); } else { $this->setKshowId($v->getId()); } $this->akshow = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the kshow object, it will not be re-added. if ($v !== null) { $v->addentry($this); } return $this; } /** * Get the associated kshow object * * @param PropelPDO Optional Connection object. * @return kshow The associated kshow object. * @throws PropelException */ public function getkshow(PropelPDO $con = null) { if ($this->akshow === null && (($this->kshow_id !== "" && $this->kshow_id !== null))) { $this->akshow = kshowPeer::retrieveByPk($this->kshow_id); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->akshow->addentrys($this); */ } return $this->akshow; } /** * Declares an association between this object and a kuser object. * * @param kuser $v * @return entry The current object (for fluent API support) * @throws PropelException */ public function setkuser(kuser $v = null) { if ($v === null) { $this->setKuserId(NULL); } else { $this->setKuserId($v->getId()); } $this->akuser = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the kuser object, it will not be re-added. if ($v !== null) { $v->addentry($this); } return $this; } /** * Get the associated kuser object * * @param PropelPDO Optional Connection object. * @return kuser The associated kuser object. * @throws PropelException */ public function getkuser(PropelPDO $con = null) { if ($this->akuser === null && ($this->kuser_id !== null)) { $this->akuser = kuserPeer::retrieveByPk($this->kuser_id); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->akuser->addentrys($this); */ } return $this->akuser; } /** * Declares an association between this object and a accessControl object. * * @param accessControl $v * @return entry The current object (for fluent API support) * @throws PropelException */ public function setaccessControl(accessControl $v = null) { if ($v === null) { $this->setAccessControlId(NULL); } else { $this->setAccessControlId($v->getId()); } $this->aaccessControl = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the accessControl object, it will not be re-added. if ($v !== null) { $v->addentry($this); } return $this; } /** * Get the associated accessControl object * * @param PropelPDO Optional Connection object. * @return accessControl The associated accessControl object. * @throws PropelException */ public function getaccessControl(PropelPDO $con = null) { if ($this->aaccessControl === null && ($this->access_control_id !== null)) { $this->aaccessControl = accessControlPeer::retrieveByPk($this->access_control_id); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aaccessControl->addentrys($this); */ } return $this->aaccessControl; } /** * Declares an association between this object and a conversionProfile2 object. * * @param conversionProfile2 $v * @return entry The current object (for fluent API support) * @throws PropelException */ public function setconversionProfile2(conversionProfile2 $v = null) { if ($v === null) { $this->setConversionProfileId(NULL); } else { $this->setConversionProfileId($v->getId()); } $this->aconversionProfile2 = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the conversionProfile2 object, it will not be re-added. if ($v !== null) { $v->addentry($this); } return $this; } /** * Get the associated conversionProfile2 object * * @param PropelPDO Optional Connection object. * @return conversionProfile2 The associated conversionProfile2 object. * @throws PropelException */ public function getconversionProfile2(PropelPDO $con = null) { if ($this->aconversionProfile2 === null && ($this->conversion_profile_id !== null)) { $this->aconversionProfile2 = conversionProfile2Peer::retrieveByPk($this->conversion_profile_id); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aconversionProfile2->addentrys($this); */ } return $this->aconversionProfile2; } /** * Clears out the collLiveChannelSegmentsRelatedByChannelId collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addLiveChannelSegmentsRelatedByChannelId() */ public function clearLiveChannelSegmentsRelatedByChannelId() { $this->collLiveChannelSegmentsRelatedByChannelId = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collLiveChannelSegmentsRelatedByChannelId collection (array). * * By default this just sets the collLiveChannelSegmentsRelatedByChannelId collection to an empty array (like clearcollLiveChannelSegmentsRelatedByChannelId()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initLiveChannelSegmentsRelatedByChannelId() { $this->collLiveChannelSegmentsRelatedByChannelId = array(); } /** * Gets an array of LiveChannelSegment objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related LiveChannelSegmentsRelatedByChannelId from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array LiveChannelSegment[] * @throws PropelException */ public function getLiveChannelSegmentsRelatedByChannelId($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collLiveChannelSegmentsRelatedByChannelId === null) { if ($this->isNew()) { $this->collLiveChannelSegmentsRelatedByChannelId = array(); } else { $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); LiveChannelSegmentPeer::addSelectColumns($criteria); $this->collLiveChannelSegmentsRelatedByChannelId = LiveChannelSegmentPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); LiveChannelSegmentPeer::addSelectColumns($criteria); if (!isset($this->lastLiveChannelSegmentRelatedByChannelIdCriteria) || !$this->lastLiveChannelSegmentRelatedByChannelIdCriteria->equals($criteria)) { $this->collLiveChannelSegmentsRelatedByChannelId = LiveChannelSegmentPeer::doSelect($criteria, $con); } } } $this->lastLiveChannelSegmentRelatedByChannelIdCriteria = $criteria; return $this->collLiveChannelSegmentsRelatedByChannelId; } /** * Returns the number of related LiveChannelSegment objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related LiveChannelSegment objects. * @throws PropelException */ public function countLiveChannelSegmentsRelatedByChannelId(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collLiveChannelSegmentsRelatedByChannelId === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); $count = LiveChannelSegmentPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); if (!isset($this->lastLiveChannelSegmentRelatedByChannelIdCriteria) || !$this->lastLiveChannelSegmentRelatedByChannelIdCriteria->equals($criteria)) { $count = LiveChannelSegmentPeer::doCount($criteria, false, $con); } else { $count = count($this->collLiveChannelSegmentsRelatedByChannelId); } } else { $count = count($this->collLiveChannelSegmentsRelatedByChannelId); } } return $count; } /** * Method called to associate a LiveChannelSegment object to this object * through the LiveChannelSegment foreign key attribute. * * @param LiveChannelSegment $l LiveChannelSegment * @return void * @throws PropelException */ public function addLiveChannelSegmentRelatedByChannelId(LiveChannelSegment $l) { if ($this->collLiveChannelSegmentsRelatedByChannelId === null) { $this->initLiveChannelSegmentsRelatedByChannelId(); } if (!in_array($l, $this->collLiveChannelSegmentsRelatedByChannelId, true)) { // only add it if the **same** object is not already associated array_push($this->collLiveChannelSegmentsRelatedByChannelId, $l); $l->setentryRelatedByChannelId($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related LiveChannelSegmentsRelatedByChannelId from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getLiveChannelSegmentsRelatedByChannelIdJoinLiveChannelSegmentRelatedByTriggerSegmentId($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collLiveChannelSegmentsRelatedByChannelId === null) { if ($this->isNew()) { $this->collLiveChannelSegmentsRelatedByChannelId = array(); } else { $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); $this->collLiveChannelSegmentsRelatedByChannelId = LiveChannelSegmentPeer::doSelectJoinLiveChannelSegmentRelatedByTriggerSegmentId($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); if (!isset($this->lastLiveChannelSegmentRelatedByChannelIdCriteria) || !$this->lastLiveChannelSegmentRelatedByChannelIdCriteria->equals($criteria)) { $this->collLiveChannelSegmentsRelatedByChannelId = LiveChannelSegmentPeer::doSelectJoinLiveChannelSegmentRelatedByTriggerSegmentId($criteria, $con, $join_behavior); } } $this->lastLiveChannelSegmentRelatedByChannelIdCriteria = $criteria; return $this->collLiveChannelSegmentsRelatedByChannelId; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related LiveChannelSegmentsRelatedByChannelId from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getLiveChannelSegmentsRelatedByChannelIdJoinPartner($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collLiveChannelSegmentsRelatedByChannelId === null) { if ($this->isNew()) { $this->collLiveChannelSegmentsRelatedByChannelId = array(); } else { $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); $this->collLiveChannelSegmentsRelatedByChannelId = LiveChannelSegmentPeer::doSelectJoinPartner($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(LiveChannelSegmentPeer::CHANNEL_ID, $this->id); if (!isset($this->lastLiveChannelSegmentRelatedByChannelIdCriteria) || !$this->lastLiveChannelSegmentRelatedByChannelIdCriteria->equals($criteria)) { $this->collLiveChannelSegmentsRelatedByChannelId = LiveChannelSegmentPeer::doSelectJoinPartner($criteria, $con, $join_behavior); } } $this->lastLiveChannelSegmentRelatedByChannelIdCriteria = $criteria; return $this->collLiveChannelSegmentsRelatedByChannelId; } /** * Clears out the collLiveChannelSegmentsRelatedByEntryId collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addLiveChannelSegmentsRelatedByEntryId() */ public function clearLiveChannelSegmentsRelatedByEntryId() { $this->collLiveChannelSegmentsRelatedByEntryId = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collLiveChannelSegmentsRelatedByEntryId collection (array). * * By default this just sets the collLiveChannelSegmentsRelatedByEntryId collection to an empty array (like clearcollLiveChannelSegmentsRelatedByEntryId()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initLiveChannelSegmentsRelatedByEntryId() { $this->collLiveChannelSegmentsRelatedByEntryId = array(); } /** * Gets an array of LiveChannelSegment objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related LiveChannelSegmentsRelatedByEntryId from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array LiveChannelSegment[] * @throws PropelException */ public function getLiveChannelSegmentsRelatedByEntryId($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collLiveChannelSegmentsRelatedByEntryId === null) { if ($this->isNew()) { $this->collLiveChannelSegmentsRelatedByEntryId = array(); } else { $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); LiveChannelSegmentPeer::addSelectColumns($criteria); $this->collLiveChannelSegmentsRelatedByEntryId = LiveChannelSegmentPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); LiveChannelSegmentPeer::addSelectColumns($criteria); if (!isset($this->lastLiveChannelSegmentRelatedByEntryIdCriteria) || !$this->lastLiveChannelSegmentRelatedByEntryIdCriteria->equals($criteria)) { $this->collLiveChannelSegmentsRelatedByEntryId = LiveChannelSegmentPeer::doSelect($criteria, $con); } } } $this->lastLiveChannelSegmentRelatedByEntryIdCriteria = $criteria; return $this->collLiveChannelSegmentsRelatedByEntryId; } /** * Returns the number of related LiveChannelSegment objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related LiveChannelSegment objects. * @throws PropelException */ public function countLiveChannelSegmentsRelatedByEntryId(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collLiveChannelSegmentsRelatedByEntryId === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); $count = LiveChannelSegmentPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); if (!isset($this->lastLiveChannelSegmentRelatedByEntryIdCriteria) || !$this->lastLiveChannelSegmentRelatedByEntryIdCriteria->equals($criteria)) { $count = LiveChannelSegmentPeer::doCount($criteria, false, $con); } else { $count = count($this->collLiveChannelSegmentsRelatedByEntryId); } } else { $count = count($this->collLiveChannelSegmentsRelatedByEntryId); } } return $count; } /** * Method called to associate a LiveChannelSegment object to this object * through the LiveChannelSegment foreign key attribute. * * @param LiveChannelSegment $l LiveChannelSegment * @return void * @throws PropelException */ public function addLiveChannelSegmentRelatedByEntryId(LiveChannelSegment $l) { if ($this->collLiveChannelSegmentsRelatedByEntryId === null) { $this->initLiveChannelSegmentsRelatedByEntryId(); } if (!in_array($l, $this->collLiveChannelSegmentsRelatedByEntryId, true)) { // only add it if the **same** object is not already associated array_push($this->collLiveChannelSegmentsRelatedByEntryId, $l); $l->setentryRelatedByEntryId($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related LiveChannelSegmentsRelatedByEntryId from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getLiveChannelSegmentsRelatedByEntryIdJoinLiveChannelSegmentRelatedByTriggerSegmentId($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collLiveChannelSegmentsRelatedByEntryId === null) { if ($this->isNew()) { $this->collLiveChannelSegmentsRelatedByEntryId = array(); } else { $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); $this->collLiveChannelSegmentsRelatedByEntryId = LiveChannelSegmentPeer::doSelectJoinLiveChannelSegmentRelatedByTriggerSegmentId($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); if (!isset($this->lastLiveChannelSegmentRelatedByEntryIdCriteria) || !$this->lastLiveChannelSegmentRelatedByEntryIdCriteria->equals($criteria)) { $this->collLiveChannelSegmentsRelatedByEntryId = LiveChannelSegmentPeer::doSelectJoinLiveChannelSegmentRelatedByTriggerSegmentId($criteria, $con, $join_behavior); } } $this->lastLiveChannelSegmentRelatedByEntryIdCriteria = $criteria; return $this->collLiveChannelSegmentsRelatedByEntryId; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related LiveChannelSegmentsRelatedByEntryId from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getLiveChannelSegmentsRelatedByEntryIdJoinPartner($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collLiveChannelSegmentsRelatedByEntryId === null) { if ($this->isNew()) { $this->collLiveChannelSegmentsRelatedByEntryId = array(); } else { $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); $this->collLiveChannelSegmentsRelatedByEntryId = LiveChannelSegmentPeer::doSelectJoinPartner($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(LiveChannelSegmentPeer::ENTRY_ID, $this->id); if (!isset($this->lastLiveChannelSegmentRelatedByEntryIdCriteria) || !$this->lastLiveChannelSegmentRelatedByEntryIdCriteria->equals($criteria)) { $this->collLiveChannelSegmentsRelatedByEntryId = LiveChannelSegmentPeer::doSelectJoinPartner($criteria, $con, $join_behavior); } } $this->lastLiveChannelSegmentRelatedByEntryIdCriteria = $criteria; return $this->collLiveChannelSegmentsRelatedByEntryId; } /** * Clears out the collkvotes collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addkvotes() */ public function clearkvotes() { $this->collkvotes = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collkvotes collection (array). * * By default this just sets the collkvotes collection to an empty array (like clearcollkvotes()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initkvotes() { $this->collkvotes = array(); } /** * Gets an array of kvote objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related kvotes from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array kvote[] * @throws PropelException */ public function getkvotes($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collkvotes === null) { if ($this->isNew()) { $this->collkvotes = array(); } else { $criteria->add(kvotePeer::ENTRY_ID, $this->id); kvotePeer::addSelectColumns($criteria); $this->collkvotes = kvotePeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(kvotePeer::ENTRY_ID, $this->id); kvotePeer::addSelectColumns($criteria); if (!isset($this->lastkvoteCriteria) || !$this->lastkvoteCriteria->equals($criteria)) { $this->collkvotes = kvotePeer::doSelect($criteria, $con); } } } $this->lastkvoteCriteria = $criteria; return $this->collkvotes; } /** * Returns the number of related kvote objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related kvote objects. * @throws PropelException */ public function countkvotes(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collkvotes === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(kvotePeer::ENTRY_ID, $this->id); $count = kvotePeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(kvotePeer::ENTRY_ID, $this->id); if (!isset($this->lastkvoteCriteria) || !$this->lastkvoteCriteria->equals($criteria)) { $count = kvotePeer::doCount($criteria, false, $con); } else { $count = count($this->collkvotes); } } else { $count = count($this->collkvotes); } } return $count; } /** * Method called to associate a kvote object to this object * through the kvote foreign key attribute. * * @param kvote $l kvote * @return void * @throws PropelException */ public function addkvote(kvote $l) { if ($this->collkvotes === null) { $this->initkvotes(); } if (!in_array($l, $this->collkvotes, true)) { // only add it if the **same** object is not already associated array_push($this->collkvotes, $l); $l->setentry($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related kvotes from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getkvotesJoinkshowRelatedByKshowId($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collkvotes === null) { if ($this->isNew()) { $this->collkvotes = array(); } else { $criteria->add(kvotePeer::ENTRY_ID, $this->id); $this->collkvotes = kvotePeer::doSelectJoinkshowRelatedByKshowId($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(kvotePeer::ENTRY_ID, $this->id); if (!isset($this->lastkvoteCriteria) || !$this->lastkvoteCriteria->equals($criteria)) { $this->collkvotes = kvotePeer::doSelectJoinkshowRelatedByKshowId($criteria, $con, $join_behavior); } } $this->lastkvoteCriteria = $criteria; return $this->collkvotes; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related kvotes from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getkvotesJoinkshowRelatedByKuserId($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collkvotes === null) { if ($this->isNew()) { $this->collkvotes = array(); } else { $criteria->add(kvotePeer::ENTRY_ID, $this->id); $this->collkvotes = kvotePeer::doSelectJoinkshowRelatedByKuserId($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(kvotePeer::ENTRY_ID, $this->id); if (!isset($this->lastkvoteCriteria) || !$this->lastkvoteCriteria->equals($criteria)) { $this->collkvotes = kvotePeer::doSelectJoinkshowRelatedByKuserId($criteria, $con, $join_behavior); } } $this->lastkvoteCriteria = $criteria; return $this->collkvotes; } /** * Clears out the collconversions collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addconversions() */ public function clearconversions() { $this->collconversions = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collconversions collection (array). * * By default this just sets the collconversions collection to an empty array (like clearcollconversions()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initconversions() { $this->collconversions = array(); } /** * Gets an array of conversion objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related conversions from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array conversion[] * @throws PropelException */ public function getconversions($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collconversions === null) { if ($this->isNew()) { $this->collconversions = array(); } else { $criteria->add(conversionPeer::ENTRY_ID, $this->id); conversionPeer::addSelectColumns($criteria); $this->collconversions = conversionPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(conversionPeer::ENTRY_ID, $this->id); conversionPeer::addSelectColumns($criteria); if (!isset($this->lastconversionCriteria) || !$this->lastconversionCriteria->equals($criteria)) { $this->collconversions = conversionPeer::doSelect($criteria, $con); } } } $this->lastconversionCriteria = $criteria; return $this->collconversions; } /** * Returns the number of related conversion objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related conversion objects. * @throws PropelException */ public function countconversions(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collconversions === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(conversionPeer::ENTRY_ID, $this->id); $count = conversionPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(conversionPeer::ENTRY_ID, $this->id); if (!isset($this->lastconversionCriteria) || !$this->lastconversionCriteria->equals($criteria)) { $count = conversionPeer::doCount($criteria, false, $con); } else { $count = count($this->collconversions); } } else { $count = count($this->collconversions); } } return $count; } /** * Method called to associate a conversion object to this object * through the conversion foreign key attribute. * * @param conversion $l conversion * @return void * @throws PropelException */ public function addconversion(conversion $l) { if ($this->collconversions === null) { $this->initconversions(); } if (!in_array($l, $this->collconversions, true)) { // only add it if the **same** object is not already associated array_push($this->collconversions, $l); $l->setentry($this); } } /** * Clears out the collWidgetLogs collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addWidgetLogs() */ public function clearWidgetLogs() { $this->collWidgetLogs = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collWidgetLogs collection (array). * * By default this just sets the collWidgetLogs collection to an empty array (like clearcollWidgetLogs()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initWidgetLogs() { $this->collWidgetLogs = array(); } /** * Gets an array of WidgetLog objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related WidgetLogs from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array WidgetLog[] * @throws PropelException */ public function getWidgetLogs($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collWidgetLogs === null) { if ($this->isNew()) { $this->collWidgetLogs = array(); } else { $criteria->add(WidgetLogPeer::ENTRY_ID, $this->id); WidgetLogPeer::addSelectColumns($criteria); $this->collWidgetLogs = WidgetLogPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(WidgetLogPeer::ENTRY_ID, $this->id); WidgetLogPeer::addSelectColumns($criteria); if (!isset($this->lastWidgetLogCriteria) || !$this->lastWidgetLogCriteria->equals($criteria)) { $this->collWidgetLogs = WidgetLogPeer::doSelect($criteria, $con); } } } $this->lastWidgetLogCriteria = $criteria; return $this->collWidgetLogs; } /** * Returns the number of related WidgetLog objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related WidgetLog objects. * @throws PropelException */ public function countWidgetLogs(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collWidgetLogs === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(WidgetLogPeer::ENTRY_ID, $this->id); $count = WidgetLogPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(WidgetLogPeer::ENTRY_ID, $this->id); if (!isset($this->lastWidgetLogCriteria) || !$this->lastWidgetLogCriteria->equals($criteria)) { $count = WidgetLogPeer::doCount($criteria, false, $con); } else { $count = count($this->collWidgetLogs); } } else { $count = count($this->collWidgetLogs); } } return $count; } /** * Method called to associate a WidgetLog object to this object * through the WidgetLog foreign key attribute. * * @param WidgetLog $l WidgetLog * @return void * @throws PropelException */ public function addWidgetLog(WidgetLog $l) { if ($this->collWidgetLogs === null) { $this->initWidgetLogs(); } if (!in_array($l, $this->collWidgetLogs, true)) { // only add it if the **same** object is not already associated array_push($this->collWidgetLogs, $l); $l->setentry($this); } } /** * Clears out the collmoderationFlags collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addmoderationFlags() */ public function clearmoderationFlags() { $this->collmoderationFlags = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collmoderationFlags collection (array). * * By default this just sets the collmoderationFlags collection to an empty array (like clearcollmoderationFlags()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initmoderationFlags() { $this->collmoderationFlags = array(); } /** * Gets an array of moderationFlag objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related moderationFlags from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array moderationFlag[] * @throws PropelException */ public function getmoderationFlags($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collmoderationFlags === null) { if ($this->isNew()) { $this->collmoderationFlags = array(); } else { $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); moderationFlagPeer::addSelectColumns($criteria); $this->collmoderationFlags = moderationFlagPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); moderationFlagPeer::addSelectColumns($criteria); if (!isset($this->lastmoderationFlagCriteria) || !$this->lastmoderationFlagCriteria->equals($criteria)) { $this->collmoderationFlags = moderationFlagPeer::doSelect($criteria, $con); } } } $this->lastmoderationFlagCriteria = $criteria; return $this->collmoderationFlags; } /** * Returns the number of related moderationFlag objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related moderationFlag objects. * @throws PropelException */ public function countmoderationFlags(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collmoderationFlags === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); $count = moderationFlagPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); if (!isset($this->lastmoderationFlagCriteria) || !$this->lastmoderationFlagCriteria->equals($criteria)) { $count = moderationFlagPeer::doCount($criteria, false, $con); } else { $count = count($this->collmoderationFlags); } } else { $count = count($this->collmoderationFlags); } } return $count; } /** * Method called to associate a moderationFlag object to this object * through the moderationFlag foreign key attribute. * * @param moderationFlag $l moderationFlag * @return void * @throws PropelException */ public function addmoderationFlag(moderationFlag $l) { if ($this->collmoderationFlags === null) { $this->initmoderationFlags(); } if (!in_array($l, $this->collmoderationFlags, true)) { // only add it if the **same** object is not already associated array_push($this->collmoderationFlags, $l); $l->setentry($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related moderationFlags from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getmoderationFlagsJoinkuserRelatedByKuserId($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collmoderationFlags === null) { if ($this->isNew()) { $this->collmoderationFlags = array(); } else { $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); $this->collmoderationFlags = moderationFlagPeer::doSelectJoinkuserRelatedByKuserId($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); if (!isset($this->lastmoderationFlagCriteria) || !$this->lastmoderationFlagCriteria->equals($criteria)) { $this->collmoderationFlags = moderationFlagPeer::doSelectJoinkuserRelatedByKuserId($criteria, $con, $join_behavior); } } $this->lastmoderationFlagCriteria = $criteria; return $this->collmoderationFlags; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related moderationFlags from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getmoderationFlagsJoinkuserRelatedByFlaggedKuserId($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collmoderationFlags === null) { if ($this->isNew()) { $this->collmoderationFlags = array(); } else { $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); $this->collmoderationFlags = moderationFlagPeer::doSelectJoinkuserRelatedByFlaggedKuserId($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(moderationFlagPeer::FLAGGED_ENTRY_ID, $this->id); if (!isset($this->lastmoderationFlagCriteria) || !$this->lastmoderationFlagCriteria->equals($criteria)) { $this->collmoderationFlags = moderationFlagPeer::doSelectJoinkuserRelatedByFlaggedKuserId($criteria, $con, $join_behavior); } } $this->lastmoderationFlagCriteria = $criteria; return $this->collmoderationFlags; } /** * Clears out the collroughcutEntrysRelatedByRoughcutId collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addroughcutEntrysRelatedByRoughcutId() */ public function clearroughcutEntrysRelatedByRoughcutId() { $this->collroughcutEntrysRelatedByRoughcutId = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collroughcutEntrysRelatedByRoughcutId collection (array). * * By default this just sets the collroughcutEntrysRelatedByRoughcutId collection to an empty array (like clearcollroughcutEntrysRelatedByRoughcutId()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initroughcutEntrysRelatedByRoughcutId() { $this->collroughcutEntrysRelatedByRoughcutId = array(); } /** * Gets an array of roughcutEntry objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related roughcutEntrysRelatedByRoughcutId from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array roughcutEntry[] * @throws PropelException */ public function getroughcutEntrysRelatedByRoughcutId($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collroughcutEntrysRelatedByRoughcutId === null) { if ($this->isNew()) { $this->collroughcutEntrysRelatedByRoughcutId = array(); } else { $criteria->add(roughcutEntryPeer::ROUGHCUT_ID, $this->id); roughcutEntryPeer::addSelectColumns($criteria); $this->collroughcutEntrysRelatedByRoughcutId = roughcutEntryPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(roughcutEntryPeer::ROUGHCUT_ID, $this->id); roughcutEntryPeer::addSelectColumns($criteria); if (!isset($this->lastroughcutEntryRelatedByRoughcutIdCriteria) || !$this->lastroughcutEntryRelatedByRoughcutIdCriteria->equals($criteria)) { $this->collroughcutEntrysRelatedByRoughcutId = roughcutEntryPeer::doSelect($criteria, $con); } } } $this->lastroughcutEntryRelatedByRoughcutIdCriteria = $criteria; return $this->collroughcutEntrysRelatedByRoughcutId; } /** * Returns the number of related roughcutEntry objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related roughcutEntry objects. * @throws PropelException */ public function countroughcutEntrysRelatedByRoughcutId(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collroughcutEntrysRelatedByRoughcutId === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(roughcutEntryPeer::ROUGHCUT_ID, $this->id); $count = roughcutEntryPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(roughcutEntryPeer::ROUGHCUT_ID, $this->id); if (!isset($this->lastroughcutEntryRelatedByRoughcutIdCriteria) || !$this->lastroughcutEntryRelatedByRoughcutIdCriteria->equals($criteria)) { $count = roughcutEntryPeer::doCount($criteria, false, $con); } else { $count = count($this->collroughcutEntrysRelatedByRoughcutId); } } else { $count = count($this->collroughcutEntrysRelatedByRoughcutId); } } return $count; } /** * Method called to associate a roughcutEntry object to this object * through the roughcutEntry foreign key attribute. * * @param roughcutEntry $l roughcutEntry * @return void * @throws PropelException */ public function addroughcutEntryRelatedByRoughcutId(roughcutEntry $l) { if ($this->collroughcutEntrysRelatedByRoughcutId === null) { $this->initroughcutEntrysRelatedByRoughcutId(); } if (!in_array($l, $this->collroughcutEntrysRelatedByRoughcutId, true)) { // only add it if the **same** object is not already associated array_push($this->collroughcutEntrysRelatedByRoughcutId, $l); $l->setentryRelatedByRoughcutId($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related roughcutEntrysRelatedByRoughcutId from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getroughcutEntrysRelatedByRoughcutIdJoinkshow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collroughcutEntrysRelatedByRoughcutId === null) { if ($this->isNew()) { $this->collroughcutEntrysRelatedByRoughcutId = array(); } else { $criteria->add(roughcutEntryPeer::ROUGHCUT_ID, $this->id); $this->collroughcutEntrysRelatedByRoughcutId = roughcutEntryPeer::doSelectJoinkshow($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(roughcutEntryPeer::ROUGHCUT_ID, $this->id); if (!isset($this->lastroughcutEntryRelatedByRoughcutIdCriteria) || !$this->lastroughcutEntryRelatedByRoughcutIdCriteria->equals($criteria)) { $this->collroughcutEntrysRelatedByRoughcutId = roughcutEntryPeer::doSelectJoinkshow($criteria, $con, $join_behavior); } } $this->lastroughcutEntryRelatedByRoughcutIdCriteria = $criteria; return $this->collroughcutEntrysRelatedByRoughcutId; } /** * Clears out the collroughcutEntrysRelatedByEntryId collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addroughcutEntrysRelatedByEntryId() */ public function clearroughcutEntrysRelatedByEntryId() { $this->collroughcutEntrysRelatedByEntryId = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collroughcutEntrysRelatedByEntryId collection (array). * * By default this just sets the collroughcutEntrysRelatedByEntryId collection to an empty array (like clearcollroughcutEntrysRelatedByEntryId()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initroughcutEntrysRelatedByEntryId() { $this->collroughcutEntrysRelatedByEntryId = array(); } /** * Gets an array of roughcutEntry objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related roughcutEntrysRelatedByEntryId from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array roughcutEntry[] * @throws PropelException */ public function getroughcutEntrysRelatedByEntryId($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collroughcutEntrysRelatedByEntryId === null) { if ($this->isNew()) { $this->collroughcutEntrysRelatedByEntryId = array(); } else { $criteria->add(roughcutEntryPeer::ENTRY_ID, $this->id); roughcutEntryPeer::addSelectColumns($criteria); $this->collroughcutEntrysRelatedByEntryId = roughcutEntryPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(roughcutEntryPeer::ENTRY_ID, $this->id); roughcutEntryPeer::addSelectColumns($criteria); if (!isset($this->lastroughcutEntryRelatedByEntryIdCriteria) || !$this->lastroughcutEntryRelatedByEntryIdCriteria->equals($criteria)) { $this->collroughcutEntrysRelatedByEntryId = roughcutEntryPeer::doSelect($criteria, $con); } } } $this->lastroughcutEntryRelatedByEntryIdCriteria = $criteria; return $this->collroughcutEntrysRelatedByEntryId; } /** * Returns the number of related roughcutEntry objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related roughcutEntry objects. * @throws PropelException */ public function countroughcutEntrysRelatedByEntryId(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collroughcutEntrysRelatedByEntryId === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(roughcutEntryPeer::ENTRY_ID, $this->id); $count = roughcutEntryPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(roughcutEntryPeer::ENTRY_ID, $this->id); if (!isset($this->lastroughcutEntryRelatedByEntryIdCriteria) || !$this->lastroughcutEntryRelatedByEntryIdCriteria->equals($criteria)) { $count = roughcutEntryPeer::doCount($criteria, false, $con); } else { $count = count($this->collroughcutEntrysRelatedByEntryId); } } else { $count = count($this->collroughcutEntrysRelatedByEntryId); } } return $count; } /** * Method called to associate a roughcutEntry object to this object * through the roughcutEntry foreign key attribute. * * @param roughcutEntry $l roughcutEntry * @return void * @throws PropelException */ public function addroughcutEntryRelatedByEntryId(roughcutEntry $l) { if ($this->collroughcutEntrysRelatedByEntryId === null) { $this->initroughcutEntrysRelatedByEntryId(); } if (!in_array($l, $this->collroughcutEntrysRelatedByEntryId, true)) { // only add it if the **same** object is not already associated array_push($this->collroughcutEntrysRelatedByEntryId, $l); $l->setentryRelatedByEntryId($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related roughcutEntrysRelatedByEntryId from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getroughcutEntrysRelatedByEntryIdJoinkshow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collroughcutEntrysRelatedByEntryId === null) { if ($this->isNew()) { $this->collroughcutEntrysRelatedByEntryId = array(); } else { $criteria->add(roughcutEntryPeer::ENTRY_ID, $this->id); $this->collroughcutEntrysRelatedByEntryId = roughcutEntryPeer::doSelectJoinkshow($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(roughcutEntryPeer::ENTRY_ID, $this->id); if (!isset($this->lastroughcutEntryRelatedByEntryIdCriteria) || !$this->lastroughcutEntryRelatedByEntryIdCriteria->equals($criteria)) { $this->collroughcutEntrysRelatedByEntryId = roughcutEntryPeer::doSelectJoinkshow($criteria, $con, $join_behavior); } } $this->lastroughcutEntryRelatedByEntryIdCriteria = $criteria; return $this->collroughcutEntrysRelatedByEntryId; } /** * Clears out the collwidgets collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addwidgets() */ public function clearwidgets() { $this->collwidgets = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collwidgets collection (array). * * By default this just sets the collwidgets collection to an empty array (like clearcollwidgets()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initwidgets() { $this->collwidgets = array(); } /** * Gets an array of widget objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related widgets from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array widget[] * @throws PropelException */ public function getwidgets($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collwidgets === null) { if ($this->isNew()) { $this->collwidgets = array(); } else { $criteria->add(widgetPeer::ENTRY_ID, $this->id); widgetPeer::addSelectColumns($criteria); $this->collwidgets = widgetPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(widgetPeer::ENTRY_ID, $this->id); widgetPeer::addSelectColumns($criteria); if (!isset($this->lastwidgetCriteria) || !$this->lastwidgetCriteria->equals($criteria)) { $this->collwidgets = widgetPeer::doSelect($criteria, $con); } } } $this->lastwidgetCriteria = $criteria; return $this->collwidgets; } /** * Returns the number of related widget objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related widget objects. * @throws PropelException */ public function countwidgets(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collwidgets === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(widgetPeer::ENTRY_ID, $this->id); $count = widgetPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(widgetPeer::ENTRY_ID, $this->id); if (!isset($this->lastwidgetCriteria) || !$this->lastwidgetCriteria->equals($criteria)) { $count = widgetPeer::doCount($criteria, false, $con); } else { $count = count($this->collwidgets); } } else { $count = count($this->collwidgets); } } return $count; } /** * Method called to associate a widget object to this object * through the widget foreign key attribute. * * @param widget $l widget * @return void * @throws PropelException */ public function addwidget(widget $l) { if ($this->collwidgets === null) { $this->initwidgets(); } if (!in_array($l, $this->collwidgets, true)) { // only add it if the **same** object is not already associated array_push($this->collwidgets, $l); $l->setentry($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related widgets from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getwidgetsJoinkshow($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collwidgets === null) { if ($this->isNew()) { $this->collwidgets = array(); } else { $criteria->add(widgetPeer::ENTRY_ID, $this->id); $this->collwidgets = widgetPeer::doSelectJoinkshow($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(widgetPeer::ENTRY_ID, $this->id); if (!isset($this->lastwidgetCriteria) || !$this->lastwidgetCriteria->equals($criteria)) { $this->collwidgets = widgetPeer::doSelectJoinkshow($criteria, $con, $join_behavior); } } $this->lastwidgetCriteria = $criteria; return $this->collwidgets; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related widgets from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getwidgetsJoinuiConf($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collwidgets === null) { if ($this->isNew()) { $this->collwidgets = array(); } else { $criteria->add(widgetPeer::ENTRY_ID, $this->id); $this->collwidgets = widgetPeer::doSelectJoinuiConf($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(widgetPeer::ENTRY_ID, $this->id); if (!isset($this->lastwidgetCriteria) || !$this->lastwidgetCriteria->equals($criteria)) { $this->collwidgets = widgetPeer::doSelectJoinuiConf($criteria, $con, $join_behavior); } } $this->lastwidgetCriteria = $criteria; return $this->collwidgets; } /** * Clears out the collassetParamsOutputs collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addassetParamsOutputs() */ public function clearassetParamsOutputs() { $this->collassetParamsOutputs = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collassetParamsOutputs collection (array). * * By default this just sets the collassetParamsOutputs collection to an empty array (like clearcollassetParamsOutputs()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initassetParamsOutputs() { $this->collassetParamsOutputs = array(); } /** * Gets an array of assetParamsOutput objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related assetParamsOutputs from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array assetParamsOutput[] * @throws PropelException */ public function getassetParamsOutputs($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collassetParamsOutputs === null) { if ($this->isNew()) { $this->collassetParamsOutputs = array(); } else { $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); assetParamsOutputPeer::addSelectColumns($criteria); $this->collassetParamsOutputs = assetParamsOutputPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); assetParamsOutputPeer::addSelectColumns($criteria); if (!isset($this->lastassetParamsOutputCriteria) || !$this->lastassetParamsOutputCriteria->equals($criteria)) { $this->collassetParamsOutputs = assetParamsOutputPeer::doSelect($criteria, $con); } } } $this->lastassetParamsOutputCriteria = $criteria; return $this->collassetParamsOutputs; } /** * Returns the number of related assetParamsOutput objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related assetParamsOutput objects. * @throws PropelException */ public function countassetParamsOutputs(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collassetParamsOutputs === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); $count = assetParamsOutputPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); if (!isset($this->lastassetParamsOutputCriteria) || !$this->lastassetParamsOutputCriteria->equals($criteria)) { $count = assetParamsOutputPeer::doCount($criteria, false, $con); } else { $count = count($this->collassetParamsOutputs); } } else { $count = count($this->collassetParamsOutputs); } } return $count; } /** * Method called to associate a assetParamsOutput object to this object * through the assetParamsOutput foreign key attribute. * * @param assetParamsOutput $l assetParamsOutput * @return void * @throws PropelException */ public function addassetParamsOutput(assetParamsOutput $l) { if ($this->collassetParamsOutputs === null) { $this->initassetParamsOutputs(); } if (!in_array($l, $this->collassetParamsOutputs, true)) { // only add it if the **same** object is not already associated array_push($this->collassetParamsOutputs, $l); $l->setentry($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related assetParamsOutputs from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getassetParamsOutputsJoinassetParams($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collassetParamsOutputs === null) { if ($this->isNew()) { $this->collassetParamsOutputs = array(); } else { $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); $this->collassetParamsOutputs = assetParamsOutputPeer::doSelectJoinassetParams($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); if (!isset($this->lastassetParamsOutputCriteria) || !$this->lastassetParamsOutputCriteria->equals($criteria)) { $this->collassetParamsOutputs = assetParamsOutputPeer::doSelectJoinassetParams($criteria, $con, $join_behavior); } } $this->lastassetParamsOutputCriteria = $criteria; return $this->collassetParamsOutputs; } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related assetParamsOutputs from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getassetParamsOutputsJoinasset($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collassetParamsOutputs === null) { if ($this->isNew()) { $this->collassetParamsOutputs = array(); } else { $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); $this->collassetParamsOutputs = assetParamsOutputPeer::doSelectJoinasset($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(assetParamsOutputPeer::ENTRY_ID, $this->id); if (!isset($this->lastassetParamsOutputCriteria) || !$this->lastassetParamsOutputCriteria->equals($criteria)) { $this->collassetParamsOutputs = assetParamsOutputPeer::doSelectJoinasset($criteria, $con, $join_behavior); } } $this->lastassetParamsOutputCriteria = $criteria; return $this->collassetParamsOutputs; } /** * Clears out the collassets collection (array). * * This does not modify the database; however, it will remove any associated objects, causing * them to be refetched by subsequent calls to accessor method. * * @return void * @see addassets() */ public function clearassets() { $this->collassets = null; // important to set this to NULL since that means it is uninitialized } /** * Initializes the collassets collection (array). * * By default this just sets the collassets collection to an empty array (like clearcollassets()); * however, you may wish to override this method in your stub class to provide setting appropriate * to your application -- for example, setting the initial array to the values stored in database. * * @return void */ public function initassets() { $this->collassets = array(); } /** * Gets an array of asset objects which contain a foreign key that references this object. * * If this collection has already been initialized with an identical Criteria, it returns the collection. * Otherwise if this entry has previously been saved, it will retrieve * related assets from storage. If this entry is new, it will return * an empty collection or the current collection, the criteria is ignored on a new object. * * @param PropelPDO $con * @param Criteria $criteria * @return array asset[] * @throws PropelException */ public function getassets($criteria = null, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collassets === null) { if ($this->isNew()) { $this->collassets = array(); } else { $criteria->add(assetPeer::ENTRY_ID, $this->id); assetPeer::addSelectColumns($criteria); $this->collassets = assetPeer::doSelect($criteria, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(assetPeer::ENTRY_ID, $this->id); assetPeer::addSelectColumns($criteria); if (!isset($this->lastassetCriteria) || !$this->lastassetCriteria->equals($criteria)) { $this->collassets = assetPeer::doSelect($criteria, $con); } } } $this->lastassetCriteria = $criteria; return $this->collassets; } /** * Returns the number of related asset objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related asset objects. * @throws PropelException */ public function countassets(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } else { $criteria = clone $criteria; } if ($distinct) { $criteria->setDistinct(); } $count = null; if ($this->collassets === null) { if ($this->isNew()) { $count = 0; } else { $criteria->add(assetPeer::ENTRY_ID, $this->id); $count = assetPeer::doCount($criteria, false, $con); } } else { // criteria has no effect for a new object if (!$this->isNew()) { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return count of the collection. $criteria->add(assetPeer::ENTRY_ID, $this->id); if (!isset($this->lastassetCriteria) || !$this->lastassetCriteria->equals($criteria)) { $count = assetPeer::doCount($criteria, false, $con); } else { $count = count($this->collassets); } } else { $count = count($this->collassets); } } return $count; } /** * Method called to associate a asset object to this object * through the asset foreign key attribute. * * @param asset $l asset * @return void * @throws PropelException */ public function addasset(asset $l) { if ($this->collassets === null) { $this->initassets(); } if (!in_array($l, $this->collassets, true)) { // only add it if the **same** object is not already associated array_push($this->collassets, $l); $l->setentry($this); } } /** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this entry is new, it will return * an empty collection; or if this entry has previously * been saved, it will retrieve related assets from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in entry. */ public function getassetsJoinassetParams($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { if ($criteria === null) { $criteria = new Criteria(entryPeer::DATABASE_NAME); } elseif ($criteria instanceof Criteria) { $criteria = clone $criteria; } if ($this->collassets === null) { if ($this->isNew()) { $this->collassets = array(); } else { $criteria->add(assetPeer::ENTRY_ID, $this->id); $this->collassets = assetPeer::doSelectJoinassetParams($criteria, $con, $join_behavior); } } else { // the following code is to determine if a new query is // called for. If the criteria is the same as the last // one, just return the collection. $criteria->add(assetPeer::ENTRY_ID, $this->id); if (!isset($this->lastassetCriteria) || !$this->lastassetCriteria->equals($criteria)) { $this->collassets = assetPeer::doSelectJoinassetParams($criteria, $con, $join_behavior); } } $this->lastassetCriteria = $criteria; return $this->collassets; } /** * Resets all collections of referencing foreign keys. * * This method is a user-space workaround for PHP's inability to garbage collect objects * with circular references. This is currently necessary when using Propel in certain * daemon or large-volumne/high-memory operations. * * @param boolean $deep Whether to also clear the references on all associated objects. */ public function clearAllReferences($deep = false) { if ($deep) { if ($this->collLiveChannelSegmentsRelatedByChannelId) { foreach ((array) $this->collLiveChannelSegmentsRelatedByChannelId as $o) { $o->clearAllReferences($deep); } } if ($this->collLiveChannelSegmentsRelatedByEntryId) { foreach ((array) $this->collLiveChannelSegmentsRelatedByEntryId as $o) { $o->clearAllReferences($deep); } } if ($this->collkvotes) { foreach ((array) $this->collkvotes as $o) { $o->clearAllReferences($deep); } } if ($this->collconversions) { foreach ((array) $this->collconversions as $o) { $o->clearAllReferences($deep); } } if ($this->collWidgetLogs) { foreach ((array) $this->collWidgetLogs as $o) { $o->clearAllReferences($deep); } } if ($this->collmoderationFlags) { foreach ((array) $this->collmoderationFlags as $o) { $o->clearAllReferences($deep); } } if ($this->collroughcutEntrysRelatedByRoughcutId) { foreach ((array) $this->collroughcutEntrysRelatedByRoughcutId as $o) { $o->clearAllReferences($deep); } } if ($this->collroughcutEntrysRelatedByEntryId) { foreach ((array) $this->collroughcutEntrysRelatedByEntryId as $o) { $o->clearAllReferences($deep); } } if ($this->collwidgets) { foreach ((array) $this->collwidgets as $o) { $o->clearAllReferences($deep); } } if ($this->collassetParamsOutputs) { foreach ((array) $this->collassetParamsOutputs as $o) { $o->clearAllReferences($deep); } } if ($this->collassets) { foreach ((array) $this->collassets as $o) { $o->clearAllReferences($deep); } } } // if ($deep) $this->collLiveChannelSegmentsRelatedByChannelId = null; $this->collLiveChannelSegmentsRelatedByEntryId = null; $this->collkvotes = null; $this->collconversions = null; $this->collWidgetLogs = null; $this->collmoderationFlags = null; $this->collroughcutEntrysRelatedByRoughcutId = null; $this->collroughcutEntrysRelatedByEntryId = null; $this->collwidgets = null; $this->collassetParamsOutputs = null; $this->collassets = null; $this->akshow = null; $this->akuser = null; $this->aaccessControl = null; $this->aconversionProfile2 = null; } /* ---------------------- CustomData functions ------------------------- */ /** * @var myCustomData */ protected $m_custom_data = null; /** * The md5 value for the custom_data field. * @var string */ protected $custom_data_md5; /** * Store custom data old values before the changes * @var array */ protected $oldCustomDataValues = array(); /** * @return array */ public function getCustomDataOldValues() { return $this->oldCustomDataValues; } /** * @param string $name * @param string $value * @param string $namespace * @return string */ public function putInCustomData ( $name , $value , $namespace = null ) { $customData = $this->getCustomDataObj( ); $currentNamespace = ''; if($namespace) $currentNamespace = $namespace; if(!isset($this->oldCustomDataValues[$currentNamespace])) $this->oldCustomDataValues[$currentNamespace] = array(); if(!isset($this->oldCustomDataValues[$currentNamespace][$name])) $this->oldCustomDataValues[$currentNamespace][$name] = $customData->get($name, $namespace); $customData->put ( $name , $value , $namespace ); } /** * @param string $name * @param string $namespace * @param string $defaultValue * @return string */ public function getFromCustomData ( $name , $namespace = null , $defaultValue = null ) { $customData = $this->getCustomDataObj( ); $res = $customData->get ( $name , $namespace ); if ( $res === null ) return $defaultValue; return $res; } /** * @param string $name * @param string $namespace */ public function removeFromCustomData ( $name , $namespace = null) { $customData = $this->getCustomDataObj(); $currentNamespace = ''; if($namespace) $currentNamespace = $namespace; if(!isset($this->oldCustomDataValues[$currentNamespace])) $this->oldCustomDataValues[$currentNamespace] = array(); if(!isset($this->oldCustomDataValues[$currentNamespace][$name])) $this->oldCustomDataValues[$currentNamespace][$name] = $customData->get($name, $namespace); return $customData->remove ( $name , $namespace ); } /** * @param string $name * @param int $delta * @param string $namespace * @return string */ public function incInCustomData ( $name , $delta = 1, $namespace = null) { $customData = $this->getCustomDataObj( ); return $customData->inc ( $name , $delta , $namespace ); } /** * @param string $name * @param int $delta * @param string $namespace * @return string */ public function decInCustomData ( $name , $delta = 1, $namespace = null) { $customData = $this->getCustomDataObj( ); return $customData->dec ( $name , $delta , $namespace ); } /** * @return myCustomData */ public function getCustomDataObj( ) { if ( ! $this->m_custom_data ) { $this->m_custom_data = myCustomData::fromString ( $this->getCustomData() ); } return $this->m_custom_data; } /** * Must be called before saving the object */ public function setCustomDataObj() { if ( $this->m_custom_data != null ) { $this->custom_data_md5 = is_null($this->custom_data) ? null : md5($this->custom_data); $this->setCustomData( $this->m_custom_data->toString() ); } } /* ---------------------- CustomData functions ------------------------- */ } // Baseentry
agpl-3.0
nyaruka/goflow
assets/static/channel.go
3180
package static import ( "github.com/nyaruka/gocommon/urns" "github.com/nyaruka/goflow/assets" "github.com/nyaruka/goflow/envs" ) // Channel is a JSON serializable implementation of a channel asset type Channel struct { UUID_ assets.ChannelUUID `json:"uuid" validate:"required,uuid"` Name_ string `json:"name"` Address_ string `json:"address"` Schemes_ []string `json:"schemes" validate:"min=1"` Roles_ []assets.ChannelRole `json:"roles" validate:"min=1,dive,eq=send|eq=receive|eq=call|eq=answer|eq=ussd"` Parent_ *assets.ChannelReference `json:"parent" validate:"omitempty,dive"` Country_ envs.Country `json:"country,omitempty"` MatchPrefixes_ []string `json:"match_prefixes,omitempty"` AllowInternational_ bool `json:"allow_international,omitempty"` } // NewChannel creates a new channel func NewChannel(uuid assets.ChannelUUID, name string, address string, schemes []string, roles []assets.ChannelRole, parent *assets.ChannelReference) assets.Channel { return &Channel{ UUID_: uuid, Name_: name, Address_: address, Schemes_: schemes, Roles_: roles, Parent_: parent, AllowInternational_: true, } } // NewTelChannel creates a new tel channel func NewTelChannel(uuid assets.ChannelUUID, name string, address string, roles []assets.ChannelRole, parent *assets.ChannelReference, country envs.Country, matchPrefixes []string, allowInternational bool) assets.Channel { return &Channel{ UUID_: uuid, Name_: name, Address_: address, Schemes_: []string{urns.TelScheme}, Roles_: roles, Parent_: parent, Country_: country, MatchPrefixes_: matchPrefixes, AllowInternational_: allowInternational, } } // UUID returns the UUID of this channel func (c *Channel) UUID() assets.ChannelUUID { return c.UUID_ } // Name returns the name of this channel func (c *Channel) Name() string { return c.Name_ } // Address returns the address of this channel func (c *Channel) Address() string { return c.Address_ } // Schemes returns the supported schemes of this channel func (c *Channel) Schemes() []string { return c.Schemes_ } // Roles returns the roles of this channel func (c *Channel) Roles() []assets.ChannelRole { return c.Roles_ } // Parent returns a reference to this channel's parent (if any) func (c *Channel) Parent() *assets.ChannelReference { return c.Parent_ } // Country returns this channel's associated country code (if any) func (c *Channel) Country() envs.Country { return c.Country_ } // MatchPrefixes returns this channel's match prefixes values used for selecting a channel for a URN (if any) func (c *Channel) MatchPrefixes() []string { return c.MatchPrefixes_ } // AllowInternational returns whether this channel allows sending internationally (only applies to TEL schemes) func (c *Channel) AllowInternational() bool { return c.AllowInternational_ }
agpl-3.0
Nivocer/webenq
libraries/Doctrine/Validator/Timestamp.php
2173
<?php /* * $Id: Timestamp.php,v 1.2 2011/07/12 13:38:58 bart Exp $ * * 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 THE COPYRIGHT * OWNER OR CONTRIBUTORS 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ /** * Doctrine_Validator_Timestamp * * @package Doctrine * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 1.0 * @version $Revision: 1.2 $ * @author Mark Pearson <mark.pearson0@googlemail.com> */ class Doctrine_Validator_Timestamp extends Doctrine_Validator_Driver { /** * checks if given value is a valid ISO-8601 timestamp (YYYY-MM-DDTHH:MM:SS+00:00) * * @param mixed $value * @return boolean */ public function validate($value) { if (is_null($value)) { return true; } $e = explode('T', trim($value)); $date = isset($e[0]) ? $e[0]:null; $time = isset($e[1]) ? $e[1]:null; $dateValidator = Doctrine_Validator::getValidator('date'); $timeValidator = Doctrine_Validator::getValidator('time'); if ( ! $dateValidator->validate($date)) { return false; } if ( ! $timeValidator->validate($time)) { return false; } return true; } }
agpl-3.0
pistruiatul/hartapoliticii
java/src/ro/vivi/pistruiatul/Video.java
2478
package ro.vivi.pistruiatul; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class is responsible for keeping info about the video recordings of * a particular deputy. For now it only knows a link, total talk time, some * already agreggated info. * * @author vivi */ public class Video implements PageConsumer { static Logger log = Logger.getLogger("ro.vivi.pistruiatul.Video"); static private String VIDEO_URL = "pls/steno/steno.lista?uniqueId={IDV}&leg=2004&idl=1"; /** A reference to the deputy that this videos are for. */ private Deputy deputy; /** The video id used by cdep.ro to show video stuff. */ private String idv; Pattern videoInfoPattern = Pattern.compile("(.*)<b>(\\d*)</b> la <b>(\\d*)</b> puncte din sumarele " + "a <b>(\\d*)</b>(.*)video:</td><td class=\"textn\"><b>([^>]*)</td>" + "</tr></table></td>"); Pattern timeLength = Pattern.compile("(\\d*)h(\\d*)m(\\d*)s"); public Video(Deputy deputy) { this.deputy = deputy; } /** * Sets the video id for this. * @param idv */ public void setIdv(String idv) { this.idv = idv; } /** * Fetches the info from the site. */ public void crawlInfoFromSite() { if (idv == null) { return; } String path = VIDEO_URL.replace("{IDV}", idv); InternetsCrawler.enqueue(Main.HOST, path, this); } /** * Parses the page containing the video information. */ public void consume(String page) { String[] lines = page.split("\n"); int i = 0; while (i < lines.length) { Matcher m = videoInfoPattern.matcher(lines[i]); if (m.matches()) { int sessions = Integer.parseInt(m.group(3)); String length = m.group(6); int seconds = getSecondsFromString(length); log.info("Video for " + deputy.name + " (idm:" + deputy.idm + "): " + sessions + " " + length + " " + seconds); DbManager.insertVideo(deputy, idv, sessions, seconds); } i++; } } /** * Gets the number of seconds from a poorly formatted length string :-) */ private int getSecondsFromString(String length) { Matcher match = timeLength.matcher(length); if (match.matches()) { int h = Integer.parseInt(match.group(1)); int m = Integer.parseInt(match.group(2)); int s = Integer.parseInt(match.group(3)); return h * 3600 + m * 60 + s; } return 0; } }
agpl-3.0
disorganizer/brig
vendor/github.com/ipfs/go-ipfs/core/commands/urlstore.go
3253
package commands import ( "fmt" "io" "net/http" cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv" filestore "github.com/ipfs/go-ipfs/filestore" cid "gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid" mh "gx/ipfs/QmPnFwZ2JXKnXgMw8CdBPxn7FWh6LLdjUjxV1fKHuJnkr8/go-multihash" cmds "gx/ipfs/QmSXUokcP4TJpFfqozT69AVAYRtzXVMUjzQVkYX41R9Svs/go-ipfs-cmds" chunk "gx/ipfs/QmTUTG9Jg9ZRA1EzTPGTDvnwfcfKhDMnqANnP9fe4rSjMR/go-ipfs-chunker" cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit" balanced "gx/ipfs/QmfB3oNXGGq9S4B2a9YeCajoATms3Zw2VvDm8fK7VeLSV8/go-unixfs/importer/balanced" ihelper "gx/ipfs/QmfB3oNXGGq9S4B2a9YeCajoATms3Zw2VvDm8fK7VeLSV8/go-unixfs/importer/helpers" trickle "gx/ipfs/QmfB3oNXGGq9S4B2a9YeCajoATms3Zw2VvDm8fK7VeLSV8/go-unixfs/importer/trickle" ) var urlStoreCmd = &cmds.Command{ Subcommands: map[string]*cmds.Command{ "add": urlAdd, }, } var urlAdd = &cmds.Command{ Helptext: cmdkit.HelpText{ Tagline: "Add URL via urlstore.", LongDescription: ` Add URLs to ipfs without storing the data locally. The URL provided must be stable and ideally on a web server under your control. The file is added using raw-leaves but otherwise using the default settings for 'ipfs add'. The file is not pinned, so this command should be followed by an 'ipfs pin add'. This command is considered temporary until a better solution can be found. It may disappear or the semantics can change at any time. `, }, Options: []cmdkit.Option{ cmdkit.BoolOption(trickleOptionName, "t", "Use trickle-dag format for dag generation."), }, Arguments: []cmdkit.Argument{ cmdkit.StringArg("url", true, false, "URL to add to IPFS"), }, Type: &BlockStat{}, Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { url := req.Arguments[0] n, err := cmdenv.GetNode(env) if err != nil { return err } if !filestore.IsURL(url) { return fmt.Errorf("unsupported url syntax: %s", url) } cfg, err := n.Repo.Config() if err != nil { return err } if !cfg.Experimental.UrlstoreEnabled { return filestore.ErrUrlstoreNotEnabled } useTrickledag, _ := req.Options[trickleOptionName].(bool) hreq, err := http.NewRequest("GET", url, nil) if err != nil { return err } hres, err := http.DefaultClient.Do(hreq) if err != nil { return err } if hres.StatusCode != http.StatusOK { return fmt.Errorf("expected code 200, got: %d", hres.StatusCode) } chk := chunk.NewSizeSplitter(hres.Body, chunk.DefaultBlockSize) prefix := cid.NewPrefixV1(cid.DagProtobuf, mh.SHA2_256) dbp := &ihelper.DagBuilderParams{ Dagserv: n.DAG, RawLeaves: true, Maxlinks: ihelper.DefaultLinksPerBlock, NoCopy: true, CidBuilder: &prefix, URL: url, } layout := balanced.Layout if useTrickledag { layout = trickle.Layout } root, err := layout(dbp.New(chk)) if err != nil { return err } return cmds.EmitOnce(res, &BlockStat{ Key: root.Cid().String(), Size: int(hres.ContentLength), }) }, Encoders: cmds.EncoderMap{ cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, bs *BlockStat) error { _, err := fmt.Fprintln(w, bs.Key) return err }), }, }
agpl-3.0
tomolimo/processmaker-server
vendor/colosa/MichelangeloFE/src/applications/timerEventProperties.js
48498
(function () { PMDesigner.timerEventProperties = function (activity) { var that = this, evnUid = activity.getID(), activityType = activity.getEventMarker(), uidProj = PMDesigner.project.id, oldValues, tmrevn_uid = "", dataTimer = "", buttonCancel, restClientNewTimerEvent, buttonSave, restClientUpdateTimerEvent, timerEventPropertiesWindow, showHourlyItems, showDailyItems, showMonthlyItems, showOneDateTimeItems, showEveryItems, showWaitForItems, showWaitUntilItems, varshowHourlyItems, endDate, oneDateTime, daysGroup, monthsGroup, radioGroup, dateTimeVariablePicker, formTimerEvent, getFormData, getTimerEventData, validateItems, domSettings, eventType = activity.getEventType(), regexDay = new RegExp(/^(((0|1|2)?[0-9])|(3[01]))$/), regexHour = new RegExp(/^(((0|1)?[0-9])|(2[0-4]))$/), regexMinute = new RegExp(/^([0-5]?[0-9])$/); /*window*/ buttonCancel = new PMUI.ui.Button({ id: 'cancelTimmerButton', text: "Cancel".translate(), buttonType: 'error', handler: function (event) { clickedClose = false; formTimerEvent.getField('startDate').controls[0].hideCalendar(); formTimerEvent.getField('endDate').controls[0].hideCalendar(); formTimerEvent.getField('oneDateTime').controls[0].hideCalendar(); formTimerEvent.getField('dateTimeVariablePicker').controls[0].hideCalendar(); timerEventPropertiesWindow.isDirtyFormScript(); } }); restClientNewTimerEvent = function (dataToSave) { var restClient = new PMRestClient({ endpoint: 'timer-event', typeRequest: 'post', data: dataToSave, functionSuccess: function (xhr, response) { timerEventPropertiesWindow.close(); PMDesigner.msgFlash('Timer Event saved correctly'.translate(), document.body, 'success', 3000, 5); }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); } }); restClient.executeRestClient(); }; restClientUpdateTimerEvent = function (dataToSave) { var restClient = new PMRestClient({ endpoint: 'timer-event/' + formTimerEvent.getField("tmrevn_uid").getValue(), typeRequest: 'update', data: dataToSave, functionSuccess: function (xhr, response) { timerEventPropertiesWindow.close(); PMDesigner.msgFlash('Timer Event saved correctly'.translate(), document.body, 'success', 3000, 5); }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); } }); restClient.executeRestClient(); }; buttonSave = new PMUI.ui.Button({ id: 'saveTimmerButton', text: "Save".translate(), handler: function (event) { var i, opt, formData; formTimerEvent.getField("hourType").setValue(getData2PMUI(formTimerEvent.html).hourType); formTimerEvent.getField("minuteType").setValue(getData2PMUI(formTimerEvent.html).minuteType); formTimerEvent.getField("dayType").setValue(getData2PMUI(formTimerEvent.html).dayType); if (formTimerEvent.isValid()) { opt = formTimerEvent.getField("radioGroup").getValue(); formData = formTimerEvent.getData(); switch (opt) { case "1": /*hourly*/ dataTimer = { evn_uid: evnUid, tmrevn_option: "HOURLY", tmrevn_start_date: formData.startDate.substring(0, 10), tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) }; break; case "2": /*daily*/ dataTimer = { evn_uid: evnUid, tmrevn_option: "DAILY", tmrevn_start_date: formData.startDate.substring(0, 10), tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ), tmrevn_configuration_data: JSON.parse(formData.daysGroup).map(function (n) { return Number(n); }) }; break; case "3": /*monthly*/ dataTimer = { evn_uid: evnUid, tmrevn_option: "MONTHLY", tmrevn_start_date: formData.startDate.substring(0, 10), tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), tmrevn_day: formData.dayType.length == 1 ? "0" + formData.dayType : (formData.dayType.length == 0 ? "00" : formData.dayType ), tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ), tmrevn_configuration_data: JSON.parse(formData.monthsGroup).map(function (n) { return Number(n); }) }; break; case "4": /*one-date-time*/ dataTimer = { evn_uid: evnUid, tmrevn_option: "ONE-DATE-TIME", tmrevn_next_run_date: $("#oneDateTime").find("input:eq(0)").val() }; for (var i in ENABLED_FEATURES) { if (ENABLED_FEATURES[i] == 'oq3S29xemxEZXJpZEIzN01qenJUaStSekY4cTdJVm5vbWtVM0d4S2lJSS9qUT0=') { dataTimer.tmrevn_next_run_date = convertDatetimeToIso8601(dataTimer.tmrevn_next_run_date); } } break; case "5": /*every*/ dataTimer = { evn_uid: evnUid, tmrevn_option: "EVERY", tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) }; break; case "6": /*wait for*/ if ((formData.dayType === '' || formData.dayType === '00' || formData.dayType === '0') && (formData.hourType === '' || formData.hourType === '00' || formData.hourType === '0') && (formData.minuteType === '' || formData.minuteType === '00' || formData.minuteType === '0')) { PMDesigner.msgWinError("The amount of time entered is not valid. Please fill in at least one of the fields (day, hour, or minute)".translate()); return; } else { if (!regexDay.test(formData.dayType) || !regexHour.test(formData.hourType) || !regexMinute.test(formData.minuteType)) { PMDesigner.msgWinError("The amount of time entered is not valid. Please fill in at least one of the fields (day, hour, or minute)".translate()); return; } } dataTimer = { evn_uid: evnUid, tmrevn_option: "WAIT-FOR", tmrevn_day: formData.dayType.length == 1 ? "0" + formData.dayType : (formData.dayType.length == 0 ? "00" : formData.dayType ), tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) }; break; case "7": /*wait until specified date time*/ dataTimer = { evn_uid: evnUid, tmrevn_option: "WAIT-UNTIL-SPECIFIED-DATE-TIME", tmrevn_configuration_data: $("#dateTimeVariablePicker").find("input:eq(0)").val() }; break; } if (formTimerEvent.getField("tmrevn_uid").getValue() == "") { restClientNewTimerEvent(dataTimer); } else { restClientUpdateTimerEvent(dataTimer); } } }, buttonType: 'success' }); timerEventPropertiesWindow = new PMUI.ui.Window({ id: "timerEventPropertiesWindow", title: "Timer Event Properties".translate(), width: DEFAULT_WINDOW_WIDTH, height: DEFAULT_WINDOW_HEIGHT, footerItems: [ buttonCancel, buttonSave ], buttonPanelPosition: "bottom", footerAling: "right", onBeforeClose: function () { clickedClose = true; formTimerEvent.getField('startDate').controls[0].hideCalendar(); formTimerEvent.getField('endDate').controls[0].hideCalendar(); formTimerEvent.getField('oneDateTime').controls[0].hideCalendar(); formTimerEvent.getField('dateTimeVariablePicker').controls[0].hideCalendar(); timerEventPropertiesWindow.isDirtyFormScript(); } }); timerEventPropertiesWindow.isDirtyFormScript = function () { var that = this, title = "Timer Event".translate(), newValues = getFormData($("#formTimerEvent")); if (JSON.stringify(oldValues) !== JSON.stringify(newValues)) { var message_window = new PMUI.ui.MessageWindow({ id: "cancelMessageTriggers", windowMessageType: 'warning', width: 490, title: title, message: 'Are you sure you want to discard your changes?'.translate(), footerItems: [ { text: "No".translate(), handler: function () { message_window.close(); }, buttonType: "error" }, { text: "Yes".translate(), handler: function () { message_window.close(); that.close(); }, buttonType: "success" } ] }); message_window.open(); message_window.showFooter(); } else { that.close(); } }; /*end window*/ /*form*/ showHourlyItems = function () { formTimerEvent.getField('startDate').setVisible(true); formTimerEvent.getField('startDate').setRequired(true); formTimerEvent.getField('endDateCheckbox').setVisible(true); formTimerEvent.getField('endDate').setVisible(true); formTimerEvent.getField('oneDateTime').setVisible(false); formTimerEvent.getField('oneDateTime').setRequired(false); formTimerEvent.getField('daysGroup').setVisible(false); formTimerEvent.getField('daysGroup').setRequired(false); formTimerEvent.getField('monthsGroup').setVisible(false); formTimerEvent.getField('monthsGroup').setRequired(false); formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(false); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); }; showDailyItems = function () { formTimerEvent.getField('startDate').setVisible(true); formTimerEvent.getField('startDate').setRequired(true); formTimerEvent.getField('endDateCheckbox').setVisible(true); formTimerEvent.getField('endDate').setVisible(true); formTimerEvent.getField('oneDateTime').setVisible(false); formTimerEvent.getField('oneDateTime').setRequired(false); formTimerEvent.getField('daysGroup').setVisible(true); formTimerEvent.getField('daysGroup').setRequired(true); formTimerEvent.getField('oneDateTime').setRequired(false); formTimerEvent.getField('monthsGroup').setVisible(false); formTimerEvent.getField('monthsGroup').setRequired(false); formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); }; showMonthlyItems = function () { formTimerEvent.getField('startDate').setVisible(true); formTimerEvent.getField('startDate').setRequired(true); formTimerEvent.getField('endDateCheckbox').setVisible(true); formTimerEvent.getField('endDate').setVisible(true); formTimerEvent.getField('oneDateTime').setVisible(false); formTimerEvent.getField('oneDateTime').setRequired(false); formTimerEvent.getField('daysGroup').setVisible(false); formTimerEvent.getField('daysGroup').setRequired(false); formTimerEvent.getField('monthsGroup').setVisible(true); formTimerEvent.getField('monthsGroup').setRequired(true); formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(true); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); }; showOneDateTimeItems = function () { formTimerEvent.getField('startDate').setVisible(false); formTimerEvent.getField('startDate').setRequired(false); formTimerEvent.getField('endDateCheckbox').setVisible(false); formTimerEvent.getField('endDate').setVisible(false); formTimerEvent.getField('oneDateTime').setVisible(true); formTimerEvent.getField('oneDateTime').setRequired(true); formTimerEvent.getField('daysGroup').setVisible(false); formTimerEvent.getField('daysGroup').setRequired(false); formTimerEvent.getField('monthsGroup').setVisible(false); formTimerEvent.getField('monthsGroup').setRequired(false); formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(false); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(false); }; showEveryItems = function () { formTimerEvent.getField('startDate').setVisible(false); formTimerEvent.getField('startDate').setRequired(false); formTimerEvent.getField('endDateCheckbox').setVisible(false); formTimerEvent.getField('endDate').setVisible(false); formTimerEvent.getField('oneDateTime').setVisible(false); formTimerEvent.getField('oneDateTime').setRequired(false); formTimerEvent.getField('daysGroup').setVisible(false); formTimerEvent.getField('daysGroup').setRequired(false); formTimerEvent.getField('monthsGroup').setVisible(false); formTimerEvent.getField('monthsGroup').setRequired(false); formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); }; /*intermediate*/ showWaitForItems = function () { formTimerEvent.getField('startDate').setVisible(false); formTimerEvent.getField('endDateCheckbox').setVisible(false); formTimerEvent.getField('endDate').setVisible(false); formTimerEvent.getField('oneDateTime').setVisible(false); formTimerEvent.getField('daysGroup').setVisible(false); formTimerEvent.getField('daysGroup').setRequired(false); formTimerEvent.getField('monthsGroup').setVisible(false); formTimerEvent.getField('monthsGroup').setRequired(false); formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); formTimerEvent.getField('dateTimeVariablePicker').setRequired(false); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); }; showWaitUntilItems = function () { formTimerEvent.getField('startDate').setVisible(false); formTimerEvent.getField('endDateCheckbox').setVisible(false); formTimerEvent.getField('endDate').setVisible(false); formTimerEvent.getField('oneDateTime').setVisible(false); formTimerEvent.getField('daysGroup').setVisible(false); formTimerEvent.getField('daysGroup').setRequired(false); formTimerEvent.getField('monthsGroup').setVisible(false); formTimerEvent.getField('monthsGroup').setRequired(false); formTimerEvent.getField('dateTimeVariablePicker').setVisible(true); formTimerEvent.getField('dateTimeVariablePicker').setRequired(true); formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(false); }; radioGroup = new PMUI.field.RadioButtonGroupField({ id: 'radioGroup', controlPositioning: 'horizontal', maxDirectionOptions: 7, options: [ { label: "Hourly".translate(), value: "1" }, { label: "Daily".translate(), value: "2" }, { label: "Monthly".translate(), value: "3" }, { label: "One date/time".translate(), value: "4" }, { label: "Every".translate(), value: "5" }, { label: "Wait for".translate(), value: "6" }, { label: "Wait until specified date/time".translate(), value: "7" } ], onChange: function (newVal, oldVal) { switch (newVal) { case "1": showHourlyItems(); break; case "2": showDailyItems(); break; case "3": showMonthlyItems(); break; case "4": showOneDateTimeItems(); break; case "5": showEveryItems(); break; case "6": showWaitForItems(); break; case "7": showWaitUntilItems(); break; } }, value: "1" }); startDate = new PMUI.field.DateTimeField({ id: 'startDate', label: 'Start date'.translate(), datetime: false, dateFormat: 'yy-mm-dd', firstDay: 1, controlsWidth: 100, required: false, readOnly: true, minDate: 0, maxDate: 1460 }); endDate = new PMUI.field.DateTimeField({ id: 'endDate', label: "End date".translate(), value: '', disabled: true, datetime: false, dateFormat: 'yy-mm-dd', firstDay: 1, controlsWidth: 100, required: false, readOnly: true, minDate: 0, maxDate: 1460 }); oneDateTime = new PMUI.field.DateTimeField({ id: 'oneDateTime', label: 'Date time'.translate(), datetime: true, dateFormat: 'yy-mm-dd HH:ii:ss', firstDay: 1, controlsWidth: 150, required: false, readOnly: true, minDate: 0, maxDate: 1460 }); daysGroup = new PMUI.field.CheckBoxGroupField({ label: "Days".translate(), id: 'daysGroup', controlPositioning: 'vertical', maxDirectionOptions: 3, required: true, options: [ { label: 'Monday'.translate(), value: 1, name: 'monday', selected: true }, { label: 'Tuesday'.translate(), value: 2, name: 'tuesday', selected: true }, { label: 'Wednesday'.translate(), value: 3, name: 'wednesday', selected: true }, { label: 'Thursday'.translate(), value: 4, name: 'thursday', selected: true }, { label: 'Friday'.translate(), value: 5, name: 'friday', selected: true }, { label: 'Saturday'.translate(), value: 6, name: 'saturday', selected: true }, { label: 'Sunday'.translate(), value: 7, name: 'sunday', selected: true } ], onChange: function (newVal, oldVal) { } }); monthsGroup = new PMUI.field.CheckBoxGroupField({ label: "Months".translate(), id: 'monthsGroup', controlPositioning: 'vertical', maxDirectionOptions: 3, required: true, options: [ { label: 'January'.translate(), value: 1, name: 'january', selected: true }, { label: 'February'.translate(), value: 2, selected: true }, { label: 'March'.translate(), value: 3, selected: true }, { label: 'April'.translate(), value: 4, selected: true }, { label: 'May'.translate(), value: 5, selected: true }, { label: 'June'.translate(), value: 6, selected: true }, { label: 'July'.translate(), value: 7, selected: true }, { label: 'August'.translate(), value: 8, selected: true }, { label: 'September'.translate(), value: 9, selected: true }, { label: 'October'.translate(), value: 10, selected: true }, { label: 'November'.translate(), value: 11, selected: true }, { label: 'December'.translate(), value: 12, selected: true } ], onChange: function (newVal, oldVal) { } }); dateTimeVariablePicker = new PMUI.field.DateTimeField({ id: 'dateTimeVariablePicker', label: 'Date time'.translate(), datetime: true, dateFormat: 'yy-mm-dd HH:ii:ss', firstDay: 1, controlsWidth: 150, required: false, readOnly: true, minDate: 0, maxDate: 1460 }); formTimerEvent = new PMUI.form.Form({ id: "formTimerEvent", border: true, visibleHeader: false, width: '900px', height: "300px", name: "formTimerEvent", title: '', items: [ { id: "panelDetailsCustom", pmType: "panel", layout: 'vbox', fieldset: false, height: '380px', legend: "DETAILS".translate(), items: [ { id: "evnUid", pmType: "text", value: evnUid, name: "evnUid", readOnly: true, visible: false, valueType: 'string' }, { id: "activityType", pmType: "text", value: activityType, name: "activityType", readOnly: true, visible: false, valueType: 'string' }, radioGroup, { pmType: "panel", id: "datesPanel", layout: 'hbox', items: [ startDate, { pmType: "checkbox", id: "endDateCheckbox", label: "End date".translate(), controlPositioning: 'vertical', maxDirectionOptions: 2, value: '', options: [ { label: "End date:".translate(), disabled: false, value: '1', selected: false } ], onChange: function (newVal, oldVal) { if (newVal[2] == "1") { $('#endDate').find('input:eq(0)').removeProp("disabled"); } else { $('#endDate').find('input:eq(0)').val('').attr("disabled", "disabled"); formTimerEvent.getField('endDate').setValue(''); } } }, endDate, oneDateTime, dateTimeVariablePicker ] }, { pmType: "panel", id: "dayHourMonthPanel", layout: 'hbox', items: [ { id: "dayType", label: "Day".translate(), pmType: "text", value: "", name: "dayType", visible: true, valueType: 'integer', controlsWidth: 50, maxLength: 2 }, { id: "hourType", label: "Hour".translate(), pmType: "text", value: "", name: "hourType", visible: true, valueType: 'integer', controlsWidth: 50, maxLength: 2 }, { id: "minuteType", label: "Minute".translate(), pmType: "text", value: "", name: "minuteType", visible: true, valueType: 'integer', controlsWidth: 50, maxLength: 2 } ] }, daysGroup, monthsGroup, { id: "tmrevn_uid", pmType: "text", value: tmrevn_uid, name: "tmrevn_uid", visible: false, valueType: 'string' } ] } ] }); formTimerEvent.initialData = function () { var formElements = this.getItems()[0], datesPanelElements, radioGroupValues = {'radioGroup': formElements.items.get(2).getValue()}; oldValues.push(radioGroupValues); datesPanelElements = formElements.items.get(3).getItems(); }; getFormData = function ($form) { var unindexed_array = $form.serializeArray(), indexed_array = {}; $.map(unindexed_array, function (n, i) { indexed_array[n['name']] = n['value']; }); return indexed_array; }; getTimerEventData = function () { var restClient = new PMRestClient({ endpoint: 'timer-event/event/' + formTimerEvent.getField("evnUid").getValue(), typeRequest: 'get', functionSuccess: function (xhr, response) { if (typeof response === "object" && JSON.stringify(response).length > 2) { var opt = response.tmrevn_option.toUpperCase(); switch (opt) { case "HOURLY": $("#radioGroup").find("input:eq(0)").trigger("click"); formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); if (response.tmrevn_end_date != "") { formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); formTimerEvent.getField("endDate").enable(); } formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); break; case "DAILY": $("#radioGroup").find("input:eq(1)").trigger("click"); formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); if (response.tmrevn_end_date != "") { formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); formTimerEvent.getField("endDate").enable(); } formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); formTimerEvent.getField("daysGroup").setValue(""); formTimerEvent.getField("daysGroup").setValue(JSON.stringify(response.tmrevn_configuration_data.map(function (n) { return n.toString(); }))); break; case "MONTHLY": $("#radioGroup").find("input:eq(2)").trigger("click"); formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); if (response.tmrevn_end_date != "") { formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); formTimerEvent.getField("endDate").enable(); } formTimerEvent.getField("dayType").setValue(response.tmrevn_day); formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); formTimerEvent.getField("monthsGroup").setValue(""); formTimerEvent.getField("monthsGroup").setValue(JSON.stringify(response.tmrevn_configuration_data.map(function (n) { return n.toString(); }))); break; case "ONE-DATE-TIME": $("#radioGroup").find("input:eq(3)").trigger("click"); formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); var d = response.tmrevn_next_run_date.replace(/-/g, "/"); for (var i in ENABLED_FEATURES) { if (ENABLED_FEATURES[i] == 'oq3S29xemxEZXJpZEIzN01qenJUaStSekY4cTdJVm5vbWtVM0d4S2lJSS9qUT0=') { d = response.tmrevn_next_run_date; } } d = new Date(d); formTimerEvent.getField("oneDateTime").setValue(d); break; case "EVERY": $("#radioGroup").find("input:eq(4)").trigger("click"); formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); break; case "WAIT-FOR": $("#radioGroup").find("input:eq(5)").trigger("click"); formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); formTimerEvent.getField("dayType").setValue(response.tmrevn_day); formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); break; case "WAIT-UNTIL-SPECIFIED-DATE-TIME": $("#radioGroup").find("input:eq(6)").trigger("click"); formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); var d = response.tmrevn_configuration_data.replace(/-/g, "/"); d = new Date(d); formTimerEvent.getField("dateTimeVariablePicker").setValue(d); break; } } else { if (eventType == "START") { $("#radioGroup").find("input:eq(1)").trigger("click"); } else { $("#radioGroup").find("input:eq(5)").trigger("click"); } } }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); } }); restClient.executeRestClient(); }; /*end form*/ validateItems = function (itemId) { var regexTest, message, valueItem, regexTest; if (itemId === 'dayType') { regexTest = regexDay; message = "Error value: Day: 0 - 31".translate(); } else if (itemId === 'hourType') { regexTest = regexHour; message = "Error value: Hour: 0 - 23".translate(); } else if (itemId === 'minuteType') { regexTest = regexMinute; message = "Error value: Minute: 0 - 59".translate(); } valueItem = $('#' + itemId).find('span input:eq(0)').val(); if (!regexTest.test(valueItem)) { PMDesigner.msgFlash(message, timerEventPropertiesWindow, 'error', 3000, 5); $('#' + itemId).find('span input:eq(0)').val(''); return false; } }; domSettings = function () { var requiredMessage = $(document.getElementById("requiredMessage")); timerEventPropertiesWindow.body.appendChild(requiredMessage[0]); requiredMessage[0].style['marginTop'] = '70px'; timerEventPropertiesWindow.footer.html.style.textAlign = 'right'; $('#hourType, #dayType, #minuteType').find('span input:eq(0)').bind('blur change', function () { validateItems($(this).closest('div').attr('id')); }); $("#dayType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "31"}); $("#hourType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "23"}); $("#minuteType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "59"}); $("#radioGroup").css({"text-align": "center", "margin-bottom": "20px"}).find("label:eq(0)").remove(); $("#endDateCheckbox").css({"width": "170px", "top": "6px", "left": "28px"}).find("label:eq(0)").remove(); $("#endDateCheckbox").find("table:eq(0)").css("border", "0px"); $("#startDate").css("width", ""); $("#endDate").css("width", "104px").find("label:eq(0)").remove(); $("#oneDateTime").css("width", ""); $("#datesPanel").css("text-align", "center").find("label").css({ "width": "", "float": "", "text-align": "right" }); $("#dayHourMonthPanel").css("text-align", "center").find("label").css({"float": "", "width": "34.5%"}); $("#daysGroup").css("text-align", "center").find("label:eq(0)").remove(); $("#monthsGroup").css("text-align", "center").find("label:eq(0)").remove(); $("#daysGroup").find("input").each(function () { $(this).attr("name", $(this).val()); }); $("#dateTimeVariablePicker").css("width", ""); if (eventType == "START") { $(formTimerEvent.getField("radioGroup").controls[0].html).parent().show(); $(formTimerEvent.getField("radioGroup").controls[1].html).parent().show(); $(formTimerEvent.getField("radioGroup").controls[2].html).parent().show(); $(formTimerEvent.getField("radioGroup").controls[3].html).parent().show(); $(formTimerEvent.getField("radioGroup").controls[4].html).parent().show(); $(formTimerEvent.getField("radioGroup").controls[5].html).parent().hide(); $(formTimerEvent.getField("radioGroup").controls[6].html).parent().hide(); $("#radioGroup").find("input:eq(1)").trigger("click"); } else { $(formTimerEvent.getField("radioGroup").controls[0].html).parent().hide(); $(formTimerEvent.getField("radioGroup").controls[1].html).parent().hide(); $(formTimerEvent.getField("radioGroup").controls[2].html).parent().hide(); $(formTimerEvent.getField("radioGroup").controls[3].html).parent().hide(); $(formTimerEvent.getField("radioGroup").controls[4].html).parent().hide(); $(formTimerEvent.getField("radioGroup").controls[5].html).parent().show(); $(formTimerEvent.getField("radioGroup").controls[6].html).parent().show(); $("#radioGroup").find("input:eq(5)").trigger("click"); } }; timerEventPropertiesWindow.addItem(formTimerEvent); timerEventPropertiesWindow.open(); formTimerEvent.eventsDefined = false; formTimerEvent.defineEvents(); timerEventPropertiesWindow.showFooter(); domSettings(); getTimerEventData(); oldValues = getFormData($("#formTimerEvent")); }; }());
agpl-3.0
pedrommone/cidadaoatento.com
sup/controllers/mapa.php
1599
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* * Copyright (C) 2014 Pedro Maia (pedro@pedromm.com) * * This file is part of Cidadão Atento. * * Cidadão Atento is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cidadão Atento is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cidadão Atento. If not, see <http://www.gnu.org/licenses/>. */ class Mapa extends CI_Controller { public function __construct() { parent::__construct(); if (! $this->session->userdata('logado')) redirect('/login'); $this->output->enable_profiler(FALSE); $this->load->model('Avisos_model'); $this->dados = array( 'codigo' => $this->session->userdata('codigo'), 'uf' => $this->session->userdata('uf'), 'municipio' => $this->session->userdata('municipio'), 'ultimo_login' => $this->session->userdata('ultimo_login'), 'avisos' => $this->Avisos_model->get_aviso() ); } public function geral() { montaPagina('/mapa/geral', $this->dados); } } /* End of file mapa.php */ /* Location: ./application/controllers/mapa.php */
agpl-3.0
rodrigohubner/openvibe
applications/platform/acquisition-server/src/drivers/labstreaminglayer/ovasCConfigurationLabStreamingLayer.cpp
6008
#if defined(TARGET_HAS_ThirdPartyLSL) #include "ovasCConfigurationLabStreamingLayer.h" #include <lsl_cpp.h> #include "ovasIHeader.h" #include <iostream> #include <sstream> using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace OpenViBEAcquisitionServer; using namespace std; CConfigurationLabStreamingLayer::CConfigurationLabStreamingLayer(IDriverContext& rDriverContext, const char* sGtkBuilderFileName, IHeader& rHeader, CString& rSignalStream, CString& rSignalStreamID, CString& rMarkerStream, CString& rMarkerStreamID ) :CConfigurationBuilder(sGtkBuilderFileName) ,m_rDriverContext(rDriverContext) ,m_rHeader(rHeader) ,m_rSignalStream(rSignalStream) ,m_rSignalStreamID(rSignalStreamID) ,m_rMarkerStream(rMarkerStream) ,m_rMarkerStreamID(rMarkerStreamID) { } boolean CConfigurationLabStreamingLayer::preConfigure(void) { if(! CConfigurationBuilder::preConfigure()) { return false; } ::GtkComboBox* l_pComboBox=GTK_COMBO_BOX(gtk_builder_get_object(m_pBuilderConfigureInterface, "combobox_signal_stream")); if(!l_pComboBox) { return false; } ::GtkComboBox* l_pMarkerComboBox=GTK_COMBO_BOX(gtk_builder_get_object(m_pBuilderConfigureInterface, "combobox_marker_stream")); if(!l_pMarkerComboBox) { return false; } m_vSignalIndex.clear(); m_vMarkerIndex.clear(); // Allow operation without a marker stream ::gtk_combo_box_append_text(l_pMarkerComboBox, "None"); ::gtk_combo_box_set_active(l_pMarkerComboBox, 0); m_vMarkerIndex.push_back(-1); m_vStreams = lsl::resolve_streams(1.0); // See if any of the streams can be interpreted as signal or marker uint32 l_ui32nStreams = 0; uint32 l_ui32nMarkerStreams = 0; boolean l_bExactSignalMatch = false; // If we can match both name and ID, stop at that. Otherwise we auto-accept the 'name only' match. boolean l_bExactMarkerMatch = false; m_rDriverContext.getLogManager() << LogLevel_Trace << "Discovered " << static_cast<uint64>(m_vStreams.size()) << " streams in total\n"; for(uint32 i=0; i<m_vStreams.size(); i++) { if(m_vStreams[i].channel_format() == lsl::cf_float32) { std::stringstream ss; ss << m_vStreams[i].name().c_str() << " / " << m_vStreams[i].source_id().c_str() ; m_rDriverContext.getLogManager() << LogLevel_Trace << i << ". Discovered signal stream " << m_vStreams[i].name().c_str() << ", id " << ss.str().c_str() << "\n"; ::gtk_combo_box_append_text(l_pComboBox, ss.str().c_str()); m_vSignalIndex.push_back(i); if((m_rSignalStream==CString(m_vStreams[i].name().c_str()) && !l_bExactSignalMatch) || !l_ui32nStreams) { if(m_rSignalStreamID==CString(m_vStreams[i].source_id().c_str())) { l_bExactSignalMatch = true; } ::gtk_combo_box_set_active(l_pComboBox,l_ui32nStreams); } l_ui32nStreams++; } else if(m_vStreams[i].channel_format() == lsl::cf_int32) { std::stringstream ss; ss << m_vStreams[i].name().c_str() << " / " << m_vStreams[i].source_id().c_str() ; m_rDriverContext.getLogManager() << LogLevel_Trace << i << ". Discovered marker stream " << m_vStreams[i].name().c_str() << ", id " << ss.str().c_str() << "\n"; ::gtk_combo_box_append_text(l_pMarkerComboBox, ss.str().c_str()); m_vMarkerIndex.push_back(i); if((m_rMarkerStream==CString(m_vStreams[i].name().c_str()) && !l_bExactMarkerMatch) || !l_ui32nMarkerStreams) { if(m_rMarkerStreamID==CString(m_vStreams[i].source_id().c_str())) { // If we can match both name and ID, stop at that. Otherwise we accept the 'name only' match. l_bExactMarkerMatch = true; } ::gtk_combo_box_set_active(l_pMarkerComboBox,l_ui32nMarkerStreams+1); } l_ui32nMarkerStreams++; } else { // Only float32 and int32 are currently supported for signals and markers respectively m_rDriverContext.getLogManager() << LogLevel_Trace << i << ". Discovered stream with channel format " << m_vStreams[i].channel_format() << " of stream [" << m_vStreams[i].name().c_str() << "] which is not supported, skipped.\n"; continue; } } return true; } boolean CConfigurationLabStreamingLayer::postConfigure(void) { if(m_bApplyConfiguration) { // Retrieve signal stream info ::GtkComboBox* l_pComboBox=GTK_COMBO_BOX(gtk_builder_get_object(m_pBuilderConfigureInterface, "combobox_signal_stream")); if(!l_pComboBox) { m_bApplyConfiguration = false; CConfigurationBuilder::postConfigure(); // close window etc return false; } if(m_vSignalIndex.size()==0) { m_rDriverContext.getLogManager() << LogLevel_Error << "LSL: Cannot proceed without a signal stream.\n"; m_bApplyConfiguration = false; CConfigurationBuilder::postConfigure(); // close window etc return false; } const int32 l_i32SignalIndex = m_vSignalIndex[gtk_combo_box_get_active(l_pComboBox)]; m_rSignalStream = m_vStreams[l_i32SignalIndex].name().c_str(); m_rSignalStreamID = m_vStreams[l_i32SignalIndex].source_id().c_str(); ::GtkComboBox* l_pMarkerComboBox=GTK_COMBO_BOX(gtk_builder_get_object(m_pBuilderConfigureInterface, "combobox_marker_stream")); if(!l_pMarkerComboBox) { m_bApplyConfiguration = false; CConfigurationBuilder::postConfigure(); // close window etc return false; } // Retrieve marker stream info const int32 l_i32MarkerIndex = m_vMarkerIndex[gtk_combo_box_get_active(l_pMarkerComboBox)]; if(l_i32MarkerIndex>=0) { m_rMarkerStream = m_vStreams[l_i32MarkerIndex].name().c_str(); m_rMarkerStreamID = m_vStreams[l_i32MarkerIndex].source_id().c_str(); } else { m_rMarkerStream = "None"; m_rMarkerStreamID = ""; } m_rDriverContext.getLogManager() << LogLevel_Trace << "Binding to [" << m_rSignalStream << ", id " << m_rSignalStreamID << "] and [" << m_rMarkerStream << ", id " << m_rMarkerStreamID << "]\n"; } if(! CConfigurationBuilder::postConfigure()) // normal header is filled (Subject ID, Age, Gender, channels, sampling frequency), ressources are realesed { return false; } return true; } #endif
agpl-3.0
jitsni/k3po
lang/src/main/java/org/kaazing/robot/lang/ast/matcher/AstValueMatcher.java
1799
/* * Copyright (c) 2014 "Kaazing Corporation," (www.kaazing.com) * * This file is part of Robot. * * Robot 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/>. */ package org.kaazing.robot.lang.ast.matcher; public abstract class AstValueMatcher { public abstract <R, P> R accept(Visitor<R, P> visitor, P parameter) throws Exception; public interface Visitor<R, P> { R visit(AstExpressionMatcher matcher, P parameter) throws Exception; R visit(AstFixedLengthBytesMatcher matcher, P parameter) throws Exception; R visit(AstRegexMatcher matcher, P parameter) throws Exception; R visit(AstExactTextMatcher matcher, P parameter) throws Exception; R visit(AstExactBytesMatcher matcher, P parameter) throws Exception; R visit(AstVariableLengthBytesMatcher matcher, P parameter) throws Exception; R visit(AstByteLengthBytesMatcher matcher, P parameter) throws Exception; R visit(AstShortLengthBytesMatcher matcher, P parameter) throws Exception; R visit(AstIntLengthBytesMatcher matcher, P parameter) throws Exception; R visit(AstLongLengthBytesMatcher matcher, P parameter) throws Exception; } }
agpl-3.0
ronancpl/MapleSolaxiaV2
src/net/server/channel/handlers/PartySearchRegisterHandler.java
1351
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> 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 version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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/>. */ package net.server.channel.handlers; import net.AbstractMaplePacketHandler; import tools.data.input.SeekableLittleEndianAccessor; import client.MapleClient; /** * * @author Quasar */ public class PartySearchRegisterHandler extends AbstractMaplePacketHandler { @Override public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {} }
agpl-3.0
ZeeBeast/AeiaOTS
data/actions/scripts/mana_runes/donor health rune.lua
577
local exhaust = createConditionObject(CONDITION_EXHAUST) setConditionParam(exhaust, CONDITION_PARAM_TICKS, 100) -- time in seconds x1000 function onUse(cid, item, fromPosition, itemEx, toPosition) if(hasCondition(cid, CONDITION_EXHAUST)) then doSendMagicEffect(getThingPos(cid), CONST_ME_POFF) doPlayerSendCancel(cid, "You are exhausted") return true end doCreatureAddHealth(cid, math.random(600, 3000)) --parameter for total health healed doSendMagicEffect(getThingPos(cid), CONST_ME_MAGIC_BLUE) doAddCondition(cid, exhaust) return true end
agpl-3.0
mainio/decidim
decidim-meetings/spec/types/meeting_type_spec.rb
8136
# frozen_string_literal: true require "spec_helper" require "decidim/api/test/type_context" require "decidim/core/test/shared_examples/categorizable_interface_examples" require "decidim/core/test/shared_examples/scopable_interface_examples" require "decidim/core/test/shared_examples/attachable_interface_examples" require "decidim/core/test/shared_examples/authorable_interface_examples" require "decidim/core/test/shared_examples/timestamps_interface_examples" require "shared/services_interface_examples" require "shared/linked_resources_interface_examples" module Decidim module Meetings describe MeetingType, type: :graphql do include_context "with a graphql type" let(:component) { create(:meeting_component) } let(:model) { create(:meeting, component: component) } include_examples "categorizable interface" include_examples "timestamps interface" include_examples "scopable interface" include_examples "attachable interface" include_examples "services interface" include_examples "linked resources interface" describe "id" do let(:query) { "{ id }" } it "returns the meeting's id" do expect(response["id"]).to eq(model.id.to_s) end end describe "reference" do let(:query) { "{ reference }" } it "returns the meeting's reference" do expect(response["reference"]).to eq(model.reference.to_s) end end describe "title" do let(:query) { "{ title { translation(locale: \"ca\") } }" } it "returns the meeting's title" do expect(response["title"]["translation"]).to eq(model.title["ca"]) end end describe "description" do let(:query) { "{ description { translation(locale: \"ca\") } }" } it "returns the meeting's description" do expect(response["description"]["translation"]).to eq(model.description["ca"]) end end describe "startTime" do let(:query) { "{ startTime }" } it "returns the meeting's start time" do expect(Time.zone.parse(response["startTime"])).to be_within(1.second).of(model.start_time) end end describe "endTime" do let(:query) { "{ endTime }" } it "returns the meeting's end time" do expect(Time.zone.parse(response["endTime"])).to be_within(1.second).of(model.end_time) end end describe "closed" do let(:query) { "{ closed closingReport { translation(locale: \"ca\") } }" } context "when closed" do let(:model) { create(:meeting, :closed, component: component) } it "returns true" do expect(response["closed"]).to be true end it "has a closing report" do expect(response["closingReport"]).not_to be_nil expect(response["closingReport"]["translation"]).to eq(model.closing_report["ca"]) end end context "when open" do let(:model) { create(:meeting, component: component) } it "returns false" do expect(response["closed"]).to be false end it "doesn't have a closing report" do expect(response["closingReport"]).to be_nil end end end describe "agenda" do let(:query) { "{ agenda { id items { id } } }" } let(:agenda) { create(:agenda, :with_agenda_items) } before do model.update(agenda: agenda) end it "returns the agenda's items" do ids = response["agenda"]["items"].map { |item| item["id"] } expect(ids).to include(*model.agenda.agenda_items.map(&:id).map(&:to_s)) expect(response["agenda"]["id"]).to eq(agenda.id.to_s) end end describe "minutes" do let(:query) { "{ minutes { id } }" } let(:minutes) { create(:minutes) } before do model.update(minutes: minutes) end it "returns the minutes's items" do expect(response["minutes"]["id"]).to eq(minutes.id.to_s) end end context "with registrations open" do let(:model) { create(:meeting, :with_registrations_enabled, component: component) } describe "registrationsEnabled" do let(:query) { "{ registrationsEnabled }" } it "returns true" do expect(response["registrationsEnabled"]).to be true end end describe "registrationTerms" do let(:query) { "{ registrationTerms { translation(locale: \"ca\") } }" } it "returns the meeting's registration_terms" do expect(response["registrationTerms"]["translation"]).to eq(model.registration_terms["ca"]) end end describe "remainingSlots" do let(:query) { "{ remainingSlots }" } it "returns the amount of remaining slots" do expect(response["remainingSlots"]).to eq(model.remaining_slots) end end describe "attendeeCount" do let(:query) { "{ attendeeCount }" } it "returns the amount of attendees" do expect(response["attendeeCount"]).to eq(model.attendees_count) end end end describe "contributionCount" do let(:query) { "{ contributionCount }" } it "returns the amount of contributions" do expect(response["contributionCount"]).to eq(model.contributions_count) end end describe "location" do let(:query) { "{ location { translation(locale: \"ca\") } }" } it "returns the meeting's location" do expect(response["location"]["translation"]).to eq(model.location["ca"]) end end describe "locationHints" do let(:query) { "{ locationHints { translation(locale: \"ca\") } }" } it "returns the meeting's location_hints" do expect(response["locationHints"]["translation"]).to eq(model.location_hints["ca"]) end end describe "address" do let(:query) { "{ address }" } it "returns the meeting's address" do expect(response["address"]).to eq(model.address) end end describe "coordinates" do let(:query) { "{ coordinates { latitude longitude } }" } it "returns the meeting's address" do expect(response["coordinates"]).to include( "latitude" => model.latitude, "longitude" => model.longitude ) end end describe "registrationFormEnabled" do let(:query) { "{ registrationFormEnabled }" } it "returns true" do expect(response["registrationFormEnabled"]).to be true end end describe "registrationForm" do let(:query) { "{ registrationForm { id } }" } it "returns the registrationForm's items" do expect(response["registrationForm"]["id"]).to eq(model.questionnaire.id.to_s) end end describe "privateMeeting" do let(:query) { "{ privateMeeting }" } it "returns true" do expect(response["privateMeeting"]).to be false end end context "when meeting is private" do let(:query) { "{ privateMeeting }" } before do model.update(private_meeting: true, transparent: false) end it "returns true" do expect(response["privateMeeting"]).to be true end end describe "transparent" do let(:query) { "{ transparent }" } it "returns true" do expect(response["transparent"]).to be true end end describe "author" do let(:model) { create(:meeting, :not_official, author: author, component: component) } let(:author) { create(:user, organization: component.participatory_space.organization) } let(:query) { "{ author { name } }" } it "includes the user's name" do expect(response["author"]["name"]).to eq(author.name) end end end end end
agpl-3.0
RajkumarSelvaraju/FixNix_CRM
service/v4_1/SugarWebServiceUtilv4_1.php
8079
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 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 contact@sugarcrm.com. * * 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". ********************************************************************************/ require_once('service/v4/SugarWebServiceUtilv4.php'); class SugarWebServiceUtilv4_1 extends SugarWebServiceUtilv4 { /** * Validate the provided session information is correct and current. Load the session. * * @param String $session_id -- The session ID that was returned by a call to login. * @return true -- If the session is valid and loaded. * @return false -- if the session is not valid. */ function validate_authenticated($session_id) { $GLOBALS['log']->info('Begin: SoapHelperWebServices->validate_authenticated'); if(!empty($session_id)){ // only initialize session once in case this method is called multiple times if(!session_id()) { session_id($session_id); session_start(); } if(!empty($_SESSION['is_valid_session']) && $this->is_valid_ip_address('ip_address') && $_SESSION['type'] == 'user'){ global $current_user; require_once('modules/Users/User.php'); $current_user = new User(); $current_user->retrieve($_SESSION['user_id']); $this->login_success(); $GLOBALS['log']->info('Begin: SoapHelperWebServices->validate_authenticated - passed'); $GLOBALS['log']->info('End: SoapHelperWebServices->validate_authenticated'); return true; } $GLOBALS['log']->debug("calling destroy"); session_destroy(); } LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); $GLOBALS['log']->info('End: SoapHelperWebServices->validate_authenticated - validation failed'); return false; } function check_modules_access($user, $module_name, $action='write'){ if(!isset($_SESSION['avail_modules'])){ $_SESSION['avail_modules'] = get_user_module_list($user); } if(isset($_SESSION['avail_modules'][$module_name])){ if($action == 'write' && $_SESSION['avail_modules'][$module_name] == 'read_only'){ if(is_admin($user))return true; return false; }elseif($action == 'write' && strcmp(strtolower($module_name), 'users') == 0 && !$user->isAdminForModule($module_name)){ //rrs bug: 46000 - If the client is trying to write to the Users module and is not an admin then we need to stop them return false; } return true; } return false; } /** * getRelationshipResults * Returns the * * @param Mixed $bean The SugarBean instance to retrieve relationships from * @param String $link_field_name The name of the relationship entry to fetch relationships for * @param Array $link_module_fields Array of fields of relationship entries to return * @param string $optional_where String containing an optional WHERE select clause * @param string $order_by String containing field to order results by * @param Number $offset -- where to start in the return (defaults to 0) * @param Number $limit -- number of results to return (defaults to all) * @return array|bool Returns an Array of relationship results; false if relationship could not be retrieved */ function getRelationshipResults($bean, $link_field_name, $link_module_fields, $optional_where = '', $order_by = '', $offset = 0, $limit = '') { $GLOBALS['log']->info('Begin: SoapHelperWebServices->getRelationshipResults'); require_once('include/TimeDate.php'); global $beanList, $beanFiles, $current_user; global $disable_date_format, $timedate; $bean->load_relationship($link_field_name); if (isset($bean->$link_field_name)) { //First get all the related beans $params = array(); $params['offset'] = $offset; $params['limit'] = $limit; if (!empty($optional_where)) { $params['where'] = $optional_where; } $related_beans = $bean->$link_field_name->getBeans($params); //Create a list of field/value rows based on $link_module_fields $list = array(); $filterFields = array(); if (!empty($order_by) && !empty($related_beans)) { $related_beans = order_beans($related_beans, $order_by); } foreach($related_beans as $id => $bean) { if (empty($filterFields) && !empty($link_module_fields)) { $filterFields = $this->filter_fields($bean, $link_module_fields); } $row = array(); foreach ($filterFields as $field) { if (isset($bean->$field)) { if (isset($bean->field_defs[$field]['type']) && $bean->field_defs[$field]['type'] == 'date') { $row[$field] = $timedate->to_display_date_time($bean->$field); } else { $row[$field] = $bean->$field; } } else { $row[$field] = ""; } } //Users can't see other user's hashes if(is_a($bean, 'User') && $current_user->id != $bean->id && isset($row['user_hash'])) { $row['user_hash'] = ""; } $row = clean_sensitive_data($bean->field_defs, $row); $list[] = $row; } $GLOBALS['log']->info('End: SoapHelperWebServices->getRelationshipResults'); return array('rows' => $list, 'fields_set_on_rows' => $filterFields); } else { $GLOBALS['log']->info('End: SoapHelperWebServices->getRelationshipResults - ' . $link_field_name . ' relationship does not exists'); return false; } // else } // fn }
agpl-3.0
abetusk/dev
notes/src/node_modules/broker-factory/build/es2019/interfaces/worker-event.js
40
//# sourceMappingURL=worker-event.js.map
agpl-3.0
inteos/IBAdmin
templates/storage/defined.js
498
<!-- page script --> <script> $(function () { $("#storagelist").DataTable({ "language": { "emptyTable": "No Storage defined" }, "bAutoWidth": false, "columnDefs": [ { "width": "64px", "targets": 5 }, { "width": "96px", "orderable": false, "targets": 6 } // 32px for every button ] } ); }); </script> {% include "pages/refresh.js" with jobstatuswidgetRefresh=1 %} {% include 'widgets/helpbutton.js' with helppage='storage.defined' %}
agpl-3.0
simonoche/wterritoires
lib/form/doctrine/base/BaseInvitationForm.class.php
2736
<?php /** * Invitation form base class. * * @method Invitation getObject() Returns the current form's model object * * @package rrr * @subpackage form * @author Your name here * @version SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $ */ abstract class BaseInvitationForm extends BaseFormDoctrine { public function setup() { $this->setWidgets(array( 'id' => new sfWidgetFormInputHidden(), 'profil_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Profil'), 'add_empty' => true)), 'projet_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Projet'), 'add_empty' => true)), 'event_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Event'), 'add_empty' => true)), 'inviteur_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Inviteur'), 'add_empty' => true)), 'story_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Story'), 'add_empty' => true)), 'date' => new sfWidgetFormDateTime(), 'hidden' => new sfWidgetFormInputCheckbox(), 'created_at' => new sfWidgetFormDateTime(), 'updated_at' => new sfWidgetFormDateTime(), )); $this->setValidators(array( 'id' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)), 'profil_id' => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('Profil'), 'required' => false)), 'projet_id' => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('Projet'), 'required' => false)), 'event_id' => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('Event'), 'required' => false)), 'inviteur_id' => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('Inviteur'), 'required' => false)), 'story_id' => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('Story'), 'required' => false)), 'date' => new sfValidatorDateTime(array('required' => false)), 'hidden' => new sfValidatorBoolean(array('required' => false)), 'created_at' => new sfValidatorDateTime(), 'updated_at' => new sfValidatorDateTime(), )); $this->widgetSchema->setNameFormat('invitation[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); $this->setupInheritance(); parent::setup(); } public function getModelName() { return 'Invitation'; } }
agpl-3.0
publishing-systems/automated_digital_publishing_server
web/lang/en/project_new.lang.php
1742
<?php /* Copyright (C) 2014 Stephan Kreutzer * * This file is part of automated_digital_publishing_server. * * automated_digital_publishing_server is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 or any later version, * as published by the Free Software Foundation. * * automated_digital_publishing_server 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 3 for more details. * * You should have received a copy of the GNU Affero General Public License 3 * along with automated_digital_publishing_server. If not, see <http://www.gnu.org/licenses/>. */ /** * @file $/web/lang/en/project_new.lang.php * @author Stephan Kreutzer * @since 2014-06-08 */ define("LANG_PAGETITLE", "Create Project"); define("LANG_HEADER", "Create new project"); define("LANG_PROJECTNEWBUTTON", "Create"); define("LANG_PROJECTTITLECAPTION", "Name of the project"); define("LANG_PROJECTTYPECAPTION", "Project type (format of the source file)"); define("LANG_PROJECTTYPE1", "OpenOffice/LibreOffice document (template1.ott)"); define("LANG_PROJECTTYPE2", "EPUB2"); define("LANG_FINDPROJECTSDIRECTORYFAILED", "Project directory is missing."); define("LANG_FINDPROJECTLISTFAILED", "Project list is missing."); define("LANG_READPROJECTLISTFAILED", "Can't read project list."); define("LANG_WRITETOPROJECTLISTFAILED", "Can't write to project list."); define("LANG_PROJECTCREATEDSUCCESSFULLY", "Project created successfully."); define("LANG_CONTINUE", "Continue"); define("LANG_LICENSE", "Licensing"); ?>
agpl-3.0
krahman/rethinkdb
src/unittest/rdb_btree.cc
18596
// Copyright 2010-2013 RethinkDB, all rights reserved. #include "errors.hpp" #include <boost/bind.hpp> #include "arch/io/disk.hpp" #include "arch/runtime/coroutines.hpp" #include "arch/timing.hpp" #include "btree/btree_store.hpp" #include "btree/operations.hpp" #include "buffer_cache/mirrored/config.hpp" #include "containers/archive/boost_types.hpp" #include "rdb_protocol/btree.hpp" #include "rdb_protocol/pb_utils.hpp" #include "rdb_protocol/protocol.hpp" #include "rdb_protocol/sym.hpp" #include "serializer/config.hpp" #include "unittest/gtest.hpp" #include "unittest/unittest_utils.hpp" #include "rdb_protocol/minidriver.hpp" #define TOTAL_KEYS_TO_INSERT 1000 #define MAX_RETRIES_FOR_SINDEX_POSTCONSTRUCT 5 #pragma GCC diagnostic ignored "-Wshadow" namespace unittest { void insert_rows(int start, int finish, btree_store_t<rdb_protocol_t> *store) { guarantee(start <= finish); for (int i = start; i < finish; ++i) { cond_t dummy_interruptor; scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> superblock; write_token_pair_t token_pair; store->new_write_token_pair(&token_pair); store->acquire_superblock_for_write( repli_timestamp_t::invalid, 1, WRITE_DURABILITY_SOFT, &token_pair, &txn, &superblock, &dummy_interruptor); block_id_t sindex_block_id = superblock->get_sindex_block_id(); std::string data = strprintf("{\"id\" : %d, \"sid\" : %d}", i, i * i); point_write_response_t response; store_key_t pk(make_counted<const ql::datum_t>(static_cast<double>(i))->print_primary()); rdb_modification_report_t mod_report(pk); rdb_set(pk, make_counted<ql::datum_t>(scoped_cJSON_t(cJSON_Parse(data.c_str()))), false, store->btree.get(), repli_timestamp_t::invalid, txn.get(), superblock.get(), &response, &mod_report.info, static_cast<profile::trace_t *>(NULL)); { scoped_ptr_t<buf_lock_t> sindex_block; store->acquire_sindex_block_for_write( &token_pair, txn.get(), &sindex_block, sindex_block_id, &dummy_interruptor); btree_store_t<rdb_protocol_t>::sindex_access_vector_t sindexes; store->aquire_post_constructed_sindex_superblocks_for_write( sindex_block.get(), txn.get(), &sindexes); rdb_update_sindexes(sindexes, &mod_report, txn.get()); mutex_t::acq_t acq; store->lock_sindex_queue(sindex_block.get(), &acq); write_message_t wm; wm << rdb_sindex_change_t(mod_report); store->sindex_queue_push(wm, &acq); } } } void insert_rows_and_pulse_when_done(int start, int finish, btree_store_t<rdb_protocol_t> *store, cond_t *pulse_when_done) { insert_rows(start, finish, store); pulse_when_done->pulse(); } std::string create_sindex(btree_store_t<rdb_protocol_t> *store) { cond_t dummy_interruptor; std::string sindex_id = uuid_to_str(generate_uuid()); write_token_pair_t token_pair; store->new_write_token_pair(&token_pair); scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> super_block; store->acquire_superblock_for_write(repli_timestamp_t::invalid, 1, WRITE_DURABILITY_SOFT, &token_pair, &txn, &super_block, &dummy_interruptor); ql::sym_t one(1); ql::protob_t<const Term> mapping = ql::r::var(one)["sid"].release_counted(); ql::map_wire_func_t m(mapping, make_vector(one), get_backtrace(mapping)); sindex_multi_bool_t multi_bool = sindex_multi_bool_t::SINGLE; write_message_t wm; wm << m; wm << multi_bool; vector_stream_t stream; stream.reserve(wm.size()); int res = send_write_message(&stream, &wm); guarantee(res == 0); UNUSED bool b = store->add_sindex( &token_pair, sindex_id, stream.vector(), txn.get(), super_block.get(), &dummy_interruptor); return sindex_id; } void drop_sindex(btree_store_t<rdb_protocol_t> *store, const std::string &sindex_id) { cond_t dummy_interuptor; write_token_pair_t token_pair; store->new_write_token_pair(&token_pair); scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> super_block; store->acquire_superblock_for_write(repli_timestamp_t::invalid, 1, WRITE_DURABILITY_SOFT, &token_pair, &txn, &super_block, &dummy_interuptor); value_sizer_t<rdb_value_t> sizer(store->cache->get_block_size()); rdb_value_deleter_t deleter; store->drop_sindex( &token_pair, sindex_id, txn.get(), super_block.get(), &sizer, &deleter, &dummy_interuptor); } void bring_sindexes_up_to_date( btree_store_t<rdb_protocol_t> *store, std::string sindex_id) { cond_t dummy_interruptor; write_token_pair_t token_pair; store->new_write_token_pair(&token_pair); scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> super_block; store->acquire_superblock_for_write(repli_timestamp_t::invalid, 1, WRITE_DURABILITY_SOFT, &token_pair, &txn, &super_block, &dummy_interruptor); scoped_ptr_t<buf_lock_t> sindex_block; store->acquire_sindex_block_for_write( &token_pair, txn.get(), &sindex_block, super_block->get_sindex_block_id(), &dummy_interruptor); std::set<std::string> created_sindexes; created_sindexes.insert(sindex_id); rdb_protocol_details::bring_sindexes_up_to_date(created_sindexes, store, sindex_block.get(), txn.get()); nap(1000); } void spawn_writes_and_bring_sindexes_up_to_date(btree_store_t<rdb_protocol_t> *store, std::string sindex_id, cond_t *background_inserts_done) { cond_t dummy_interruptor; write_token_pair_t token_pair; store->new_write_token_pair(&token_pair); scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> super_block; store->acquire_superblock_for_write( repli_timestamp_t::invalid, 1, WRITE_DURABILITY_SOFT, &token_pair, &txn, &super_block, &dummy_interruptor); scoped_ptr_t<buf_lock_t> sindex_block; store->acquire_sindex_block_for_write( &token_pair, txn.get(), &sindex_block, super_block->get_sindex_block_id(), &dummy_interruptor); coro_t::spawn_sometime(boost::bind(&insert_rows_and_pulse_when_done, (TOTAL_KEYS_TO_INSERT * 9) / 10, TOTAL_KEYS_TO_INSERT, store, background_inserts_done)); std::set<std::string> created_sindexes; created_sindexes.insert(sindex_id); rdb_protocol_details::bring_sindexes_up_to_date(created_sindexes, store, sindex_block.get(), txn.get()); } void _check_keys_are_present(btree_store_t<rdb_protocol_t> *store, std::string sindex_id) { cond_t dummy_interruptor; for (int i = 0; i < TOTAL_KEYS_TO_INSERT; ++i) { read_token_pair_t token_pair; store->new_read_token_pair(&token_pair); scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> super_block; store->acquire_superblock_for_read(rwi_read, &token_pair.main_read_token, &txn, &super_block, &dummy_interruptor, true); scoped_ptr_t<real_superblock_t> sindex_sb; bool sindex_exists = store->acquire_sindex_superblock_for_read(sindex_id, super_block->get_sindex_block_id(), &token_pair, txn.get(), &sindex_sb, static_cast<std::vector<char>*>(NULL), &dummy_interruptor); ASSERT_TRUE(sindex_exists); rdb_protocol_t::rget_read_response_t res; double ii = i * i; /* The only thing this does is have a NULL scoped_ptr_t<trace_t> in it * which prevents to profiling code from crashing. */ ql::env_t dummy_env(NULL); rdb_rget_slice( store->get_sindex_slice(sindex_id), rdb_protocol_t::sindex_key_range( store_key_t(make_counted<const ql::datum_t>(ii)->print_primary()), store_key_t(make_counted<const ql::datum_t>(ii)->print_primary())), txn.get(), sindex_sb.get(), &dummy_env, // env_t ql::batchspec_t::user(ql::batch_type_t::NORMAL, counted_t<const ql::datum_t>()), rdb_protocol_details::transform_t(), boost::optional<rdb_protocol_details::terminal_t>(), sorting_t::ASCENDING, &res); rdb_protocol_t::rget_read_response_t::stream_t *stream = boost::get<rdb_protocol_t::rget_read_response_t::stream_t>(&res.result); ASSERT_TRUE(stream != NULL); ASSERT_EQ(1ul, stream->size()); std::string expected_data = strprintf("{\"id\" : %d, \"sid\" : %d}", i, i * i); scoped_cJSON_t expected_value(cJSON_Parse(expected_data.c_str())); ASSERT_EQ(ql::datum_t(expected_value.get()), *stream->front().data); } } void check_keys_are_present(btree_store_t<rdb_protocol_t> *store, std::string sindex_id) { for (int i = 0; i < MAX_RETRIES_FOR_SINDEX_POSTCONSTRUCT; ++i) { try { _check_keys_are_present(store, sindex_id); } catch (const sindex_not_post_constructed_exc_t&) { } /* Unfortunately we don't have an easy way right now to tell if the * sindex has actually been postconstructed so we just need to * check by polling. */ nap(100); } } void _check_keys_are_NOT_present(btree_store_t<rdb_protocol_t> *store, std::string sindex_id) { /* Check that we don't have any of the keys (we just deleted them all) */ cond_t dummy_interruptor; for (int i = 0; i < TOTAL_KEYS_TO_INSERT; ++i) { read_token_pair_t token_pair; store->new_read_token_pair(&token_pair); scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> super_block; store->acquire_superblock_for_read(rwi_read, &token_pair.main_read_token, &txn, &super_block, &dummy_interruptor, true); scoped_ptr_t<real_superblock_t> sindex_sb; bool sindex_exists = store->acquire_sindex_superblock_for_read(sindex_id, super_block->get_sindex_block_id(), &token_pair, txn.get(), &sindex_sb, static_cast<std::vector<char>*>(NULL), &dummy_interruptor); ASSERT_TRUE(sindex_exists); rdb_protocol_t::rget_read_response_t res; double ii = i * i; /* The only thing this does is have a NULL scoped_ptr_t<trace_t> in it * which prevents to profiling code from crashing. */ ql::env_t dummy_env(NULL); rdb_rget_slice( store->get_sindex_slice(sindex_id), rdb_protocol_t::sindex_key_range( store_key_t(make_counted<const ql::datum_t>(ii)->print_primary()), store_key_t(make_counted<const ql::datum_t>(ii)->print_primary())), txn.get(), sindex_sb.get(), &dummy_env, // env_t ql::batchspec_t::user(ql::batch_type_t::NORMAL, counted_t<const ql::datum_t>()), rdb_protocol_details::transform_t(), boost::optional<rdb_protocol_details::terminal_t>(), sorting_t::ASCENDING, &res); rdb_protocol_t::rget_read_response_t::stream_t *stream = boost::get<rdb_protocol_t::rget_read_response_t::stream_t>(&res.result); ASSERT_TRUE(stream != NULL); ASSERT_EQ(0ul, stream->size()); } } void check_keys_are_NOT_present(btree_store_t<rdb_protocol_t> *store, std::string sindex_id) { for (int i = 0; i < MAX_RETRIES_FOR_SINDEX_POSTCONSTRUCT; ++i) { try { _check_keys_are_NOT_present(store, sindex_id); } catch (const sindex_not_post_constructed_exc_t&) { } /* Unfortunately we don't have an easy way right now to tell if the * sindex has actually been postconstructed so we just need to * check by polling. */ nap(100); } } void run_sindex_post_construction() { recreate_temporary_directory(base_path_t(".")); temp_file_t temp_file; io_backender_t io_backender(file_direct_io_mode_t::buffered_desired); filepath_file_opener_t file_opener(temp_file.name(), &io_backender); standard_serializer_t::create( &file_opener, standard_serializer_t::static_config_t()); standard_serializer_t serializer( standard_serializer_t::dynamic_config_t(), &file_opener, &get_global_perfmon_collection()); rdb_protocol_t::store_t store( &serializer, "unit_test_store", GIGABYTE, true, &get_global_perfmon_collection(), NULL, &io_backender, base_path_t(".")); cond_t dummy_interruptor; insert_rows(0, (TOTAL_KEYS_TO_INSERT * 9) / 10, &store); std::string sindex_id = create_sindex(&store); cond_t background_inserts_done; spawn_writes_and_bring_sindexes_up_to_date(&store, sindex_id, &background_inserts_done); background_inserts_done.wait(); check_keys_are_present(&store, sindex_id); } TEST(RDBBtree, SindexPostConstruct) { run_in_thread_pool(&run_sindex_post_construction); } void run_erase_range_test() { recreate_temporary_directory(base_path_t(".")); temp_file_t temp_file; io_backender_t io_backender(file_direct_io_mode_t::buffered_desired); filepath_file_opener_t file_opener(temp_file.name(), &io_backender); standard_serializer_t::create( &file_opener, standard_serializer_t::static_config_t()); standard_serializer_t serializer( standard_serializer_t::dynamic_config_t(), &file_opener, &get_global_perfmon_collection()); rdb_protocol_t::store_t store( &serializer, "unit_test_store", GIGABYTE, true, &get_global_perfmon_collection(), NULL, &io_backender, base_path_t(".")); cond_t dummy_interruptor; insert_rows(0, (TOTAL_KEYS_TO_INSERT * 9) / 10, &store); std::string sindex_id = create_sindex(&store); cond_t background_inserts_done; spawn_writes_and_bring_sindexes_up_to_date(&store, sindex_id, &background_inserts_done); background_inserts_done.wait(); check_keys_are_present(&store, sindex_id); { /* Now we erase all of the keys we just inserted. */ write_token_pair_t token_pair; store.new_write_token_pair(&token_pair); scoped_ptr_t<transaction_t> txn; scoped_ptr_t<real_superblock_t> super_block; store.acquire_superblock_for_write(repli_timestamp_t::invalid, 1, WRITE_DURABILITY_SOFT, &token_pair, &txn, &super_block, &dummy_interruptor); const hash_region_t<key_range_t> test_range = hash_region_t<key_range_t>::universe(); rdb_protocol_details::range_key_tester_t tester(&test_range); rdb_erase_range(store.btree.get(), &tester, key_range_t::universe(), txn.get(), super_block.get(), &store, &token_pair, &dummy_interruptor); } check_keys_are_NOT_present(&store, sindex_id); } TEST(RDBBtree, SindexEraseRange) { run_in_thread_pool(&run_erase_range_test); } void run_sindex_interruption_via_drop_test() { recreate_temporary_directory(base_path_t(".")); temp_file_t temp_file; io_backender_t io_backender(file_direct_io_mode_t::buffered_desired); filepath_file_opener_t file_opener(temp_file.name(), &io_backender); standard_serializer_t::create( &file_opener, standard_serializer_t::static_config_t()); standard_serializer_t serializer( standard_serializer_t::dynamic_config_t(), &file_opener, &get_global_perfmon_collection()); rdb_protocol_t::store_t store( &serializer, "unit_test_store", GIGABYTE, true, &get_global_perfmon_collection(), NULL, &io_backender, base_path_t(".")); cond_t dummy_interuptor; insert_rows(0, (TOTAL_KEYS_TO_INSERT * 9) / 10, &store); std::string sindex_id = create_sindex(&store); cond_t background_inserts_done; spawn_writes_and_bring_sindexes_up_to_date(&store, sindex_id, &background_inserts_done); drop_sindex(&store, sindex_id); background_inserts_done.wait(); } TEST(RDBBtree, SindexInterruptionViaDrop) { run_in_thread_pool(&run_sindex_interruption_via_drop_test); } void run_sindex_interruption_via_store_delete() { recreate_temporary_directory(base_path_t(".")); temp_file_t temp_file; io_backender_t io_backender(file_direct_io_mode_t::buffered_desired); filepath_file_opener_t file_opener(temp_file.name(), &io_backender); standard_serializer_t::create( &file_opener, standard_serializer_t::static_config_t()); standard_serializer_t serializer( standard_serializer_t::dynamic_config_t(), &file_opener, &get_global_perfmon_collection()); scoped_ptr_t<rdb_protocol_t::store_t> store( new rdb_protocol_t::store_t( &serializer, "unit_test_store", GIGABYTE, true, &get_global_perfmon_collection(), NULL, &io_backender, base_path_t("."))); cond_t dummy_interuptor; insert_rows(0, (TOTAL_KEYS_TO_INSERT * 9) / 10, store.get()); std::string sindex_id = create_sindex(store.get()); bring_sindexes_up_to_date(store.get(), sindex_id); store.reset(); } TEST(RDBBtree, SindexInterruptionViaStoreDelete) { run_in_thread_pool(&run_sindex_interruption_via_store_delete); } } //namespace unittest
agpl-3.0
tmyroadctfig/mpxj
net/sf/mpxj/mspdi/MSPDIWriter.java
76701
/* * file: MSPDIWriter.java * author: Jon Iles * copyright: (c) Packwood Software 2005 * date: 2005-12-30 */ /* * 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 net.sf.mpxj.mspdi; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import net.sf.mpxj.AccrueType; import net.sf.mpxj.AssignmentField; import net.sf.mpxj.Availability; import net.sf.mpxj.CostRateTable; import net.sf.mpxj.CostRateTableEntry; import net.sf.mpxj.DataType; import net.sf.mpxj.DateRange; import net.sf.mpxj.Day; import net.sf.mpxj.DayType; import net.sf.mpxj.Duration; import net.sf.mpxj.ExtendedAttributeAssignmentFields; import net.sf.mpxj.ExtendedAttributeResourceFields; import net.sf.mpxj.ExtendedAttributeTaskFields; import net.sf.mpxj.FieldType; import net.sf.mpxj.MPPAssignmentField; import net.sf.mpxj.MPPResourceField; import net.sf.mpxj.MPPTaskField; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectCalendarWeek; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.ProjectHeader; import net.sf.mpxj.Relation; import net.sf.mpxj.RelationType; import net.sf.mpxj.Resource; import net.sf.mpxj.ResourceAssignment; import net.sf.mpxj.ResourceField; import net.sf.mpxj.ResourceType; import net.sf.mpxj.ScheduleFrom; import net.sf.mpxj.Task; import net.sf.mpxj.TaskField; import net.sf.mpxj.TaskMode; import net.sf.mpxj.TimeUnit; import net.sf.mpxj.TimephasedWork; import net.sf.mpxj.mspdi.schema.ObjectFactory; import net.sf.mpxj.mspdi.schema.Project; import net.sf.mpxj.mspdi.schema.TimephasedDataType; import net.sf.mpxj.mspdi.schema.Project.Calendars.Calendar.Exceptions; import net.sf.mpxj.mspdi.schema.Project.Calendars.Calendar.WorkWeeks; import net.sf.mpxj.mspdi.schema.Project.Calendars.Calendar.WorkWeeks.WorkWeek; import net.sf.mpxj.mspdi.schema.Project.Calendars.Calendar.WorkWeeks.WorkWeek.TimePeriod; import net.sf.mpxj.mspdi.schema.Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays; import net.sf.mpxj.mspdi.schema.Project.Resources.Resource.AvailabilityPeriods; import net.sf.mpxj.mspdi.schema.Project.Resources.Resource.Rates; import net.sf.mpxj.mspdi.schema.Project.Resources.Resource.AvailabilityPeriods.AvailabilityPeriod; import net.sf.mpxj.utility.DateUtility; import net.sf.mpxj.utility.NumberUtility; import net.sf.mpxj.writer.AbstractProjectWriter; /** * This class creates a new MSPDI file from the contents of an ProjectFile instance. */ public final class MSPDIWriter extends AbstractProjectWriter { /** * Sets a flag to control whether timephased assignment data is split * into days. The default is true. * * @param flag boolean flag */ public void setSplitTimephasedAsDays(boolean flag) { m_splitTimephasedAsDays = flag; } /** * Retrieves a flag to control whether timephased assignment data is split * into days. The default is true. * * @return boolean true */ public boolean getSplitTimephasedAsDays() { return m_splitTimephasedAsDays; } /** * Sets a flag to control whether timephased resource assignment data * is written to the file. The default is false. * * @param value boolean flag */ public void setWriteTimephasedData(boolean value) { m_writeTimphasedData = value; } /** * Retrieves the state of the flag which controls whether timephased * resource assignment data is written to the file. The default is false. * * @return boolean flag */ public boolean getWriteTimephasedData() { return m_writeTimphasedData; } /** * Set the save version to use when generating an MSPDI file. * * @param version save version */ public void setSaveVersion(SaveVersion version) { m_saveVersion = version; } /** * Retrieve the save version current set. * * @return current save version */ public SaveVersion getSaveVersion() { return m_saveVersion; } /** * {@inheritDoc} */ @Override public void write(ProjectFile projectFile, OutputStream stream) throws IOException { try { if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } m_projectFile = projectFile; m_projectFile.validateUniqueIDsForMicrosoftProject(); Marshaller marshaller = CONTEXT.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m_taskExtendedAttributes = new HashSet<TaskField>(); m_resourceExtendedAttributes = new HashSet<ResourceField>(); m_assignmentExtendedAttributes = new HashSet<AssignmentField>(); m_factory = new ObjectFactory(); Project project = m_factory.createProject(); writeProjectHeader(project); writeCalendars(project); writeResources(project); writeTasks(project); writeAssignments(project); writeProjectExtendedAttributes(project); DatatypeConverter.setParentFile(m_projectFile); marshaller.marshal(project, stream); } catch (JAXBException ex) { throw new IOException(ex.toString()); } finally { m_projectFile = null; m_factory = null; m_taskExtendedAttributes = null; m_resourceExtendedAttributes = null; m_assignmentExtendedAttributes = null; } } /** * This method writes project header data to an MSPDI file. * * @param project Root node of the MSPDI file */ private void writeProjectHeader(Project project) { ProjectHeader header = m_projectFile.getProjectHeader(); project.setActualsInSync(Boolean.valueOf(header.getActualsInSync())); project.setAdminProject(Boolean.valueOf(header.getAdminProject())); project.setAuthor(header.getAuthor()); project.setAutoAddNewResourcesAndTasks(Boolean.valueOf(header.getAutoAddNewResourcesAndTasks())); project.setAutolink(Boolean.valueOf(header.getAutolink())); project.setBaselineForEarnedValue(NumberUtility.getBigInteger(header.getBaselineForEarnedValue())); project.setCalendarUID(m_projectFile.getCalendar() == null ? BigInteger.ONE : NumberUtility.getBigInteger(m_projectFile.getCalendar().getUniqueID())); project.setCategory(header.getCategory()); project.setCompany(header.getCompany()); project.setCreationDate(DatatypeConverter.printDate(header.getCreationDate())); project.setCriticalSlackLimit(NumberUtility.getBigInteger(header.getCriticalSlackLimit())); project.setCurrencyCode(header.getCurrencyCode()); project.setCurrencyDigits(BigInteger.valueOf(header.getCurrencyDigits().intValue())); project.setCurrencySymbol(header.getCurrencySymbol()); project.setCurrencySymbolPosition(header.getSymbolPosition()); project.setCurrentDate(DatatypeConverter.printDate(header.getCurrentDate())); project.setDaysPerMonth(NumberUtility.getBigInteger(header.getDaysPerMonth())); project.setDefaultFinishTime(DatatypeConverter.printTime(header.getDefaultEndTime())); project.setDefaultFixedCostAccrual(header.getDefaultFixedCostAccrual()); project.setDefaultOvertimeRate(DatatypeConverter.printRate(header.getDefaultOvertimeRate())); project.setDefaultStandardRate(DatatypeConverter.printRate(header.getDefaultStandardRate())); project.setDefaultStartTime(DatatypeConverter.printTime(header.getDefaultStartTime())); project.setDefaultTaskEVMethod(DatatypeConverter.printEarnedValueMethod(header.getDefaultTaskEarnedValueMethod())); project.setDefaultTaskType(header.getDefaultTaskType()); project.setDurationFormat(DatatypeConverter.printDurationTimeUnits(header.getDefaultDurationUnits(), false)); project.setEarnedValueMethod(DatatypeConverter.printEarnedValueMethod(header.getEarnedValueMethod())); project.setEditableActualCosts(Boolean.valueOf(header.getEditableActualCosts())); project.setExtendedCreationDate(DatatypeConverter.printDate(header.getExtendedCreationDate())); project.setFinishDate(DatatypeConverter.printDate(header.getFinishDate())); project.setFiscalYearStart(Boolean.valueOf(header.getFiscalYearStart())); project.setFYStartDate(NumberUtility.getBigInteger(header.getFiscalYearStartMonth())); project.setHonorConstraints(Boolean.valueOf(header.getHonorConstraints())); project.setInsertedProjectsLikeSummary(Boolean.valueOf(header.getInsertedProjectsLikeSummary())); project.setLastSaved(DatatypeConverter.printDate(header.getLastSaved())); project.setManager(header.getManager()); project.setMicrosoftProjectServerURL(Boolean.valueOf(header.getMicrosoftProjectServerURL())); project.setMinutesPerDay(NumberUtility.getBigInteger(header.getMinutesPerDay())); project.setMinutesPerWeek(NumberUtility.getBigInteger(header.getMinutesPerWeek())); project.setMoveCompletedEndsBack(Boolean.valueOf(header.getMoveCompletedEndsBack())); project.setMoveCompletedEndsForward(Boolean.valueOf(header.getMoveCompletedEndsForward())); project.setMoveRemainingStartsBack(Boolean.valueOf(header.getMoveRemainingStartsBack())); project.setMoveRemainingStartsForward(Boolean.valueOf(header.getMoveRemainingStartsForward())); project.setMultipleCriticalPaths(Boolean.valueOf(header.getMultipleCriticalPaths())); project.setName(header.getName()); project.setNewTasksEffortDriven(Boolean.valueOf(header.getNewTasksEffortDriven())); project.setNewTasksEstimated(Boolean.valueOf(header.getNewTasksEstimated())); project.setNewTaskStartDate(header.getNewTaskStartIsProjectStart() == true ? BigInteger.ZERO : BigInteger.ONE); project.setProjectExternallyEdited(Boolean.valueOf(header.getProjectExternallyEdited())); project.setRemoveFileProperties(Boolean.valueOf(header.getRemoveFileProperties())); project.setRevision(NumberUtility.getBigInteger(header.getRevision())); project.setSaveVersion(BigInteger.valueOf(m_saveVersion.getValue())); project.setScheduleFromStart(Boolean.valueOf(header.getScheduleFrom() == ScheduleFrom.START)); project.setSplitsInProgressTasks(Boolean.valueOf(header.getSplitInProgressTasks())); project.setSpreadActualCost(Boolean.valueOf(header.getSpreadActualCost())); project.setSpreadPercentComplete(Boolean.valueOf(header.getSpreadPercentComplete())); project.setStartDate(DatatypeConverter.printDate(header.getStartDate())); project.setStatusDate(DatatypeConverter.printDate(header.getStatusDate())); project.setSubject(header.getSubject()); project.setTaskUpdatesResource(Boolean.valueOf(header.getUpdatingTaskStatusUpdatesResourceStatus())); project.setTitle(header.getProjectTitle()); project.setUID(header.getUniqueID()); project.setWeekStartDay(DatatypeConverter.printDay(header.getWeekStartDay())); project.setWorkFormat(DatatypeConverter.printWorkUnits(header.getDefaultWorkUnits())); } /** * This method writes project extended attribute data into an MSPDI file. * * @param project Root node of the MSPDI file */ private void writeProjectExtendedAttributes(Project project) { Project.ExtendedAttributes attributes = m_factory.createProjectExtendedAttributes(); project.setExtendedAttributes(attributes); List<Project.ExtendedAttributes.ExtendedAttribute> list = attributes.getExtendedAttribute(); writeTaskFieldAliases(list); writeResourceFieldAliases(list); } /** * Writes field aliases. * * @param list field alias list */ private void writeTaskFieldAliases(List<Project.ExtendedAttributes.ExtendedAttribute> list) { Map<TaskField, String> fieldAliasMap = m_projectFile.getTaskFieldAliasMap(); for (int loop = 0; loop < ExtendedAttributeTaskFields.FIELD_ARRAY.length; loop++) { TaskField key = ExtendedAttributeTaskFields.FIELD_ARRAY[loop]; Integer fieldID = Integer.valueOf(MPPTaskField.getID(key) | MPPTaskField.TASK_FIELD_BASE); String name = key.getName(); String alias = fieldAliasMap.get(key); if (m_taskExtendedAttributes.contains(key) || alias != null) { Project.ExtendedAttributes.ExtendedAttribute attribute = m_factory.createProjectExtendedAttributesExtendedAttribute(); list.add(attribute); attribute.setFieldID(fieldID.toString()); attribute.setFieldName(name); attribute.setAlias(alias); } } } /** * Writes field aliases. * * @param list field alias list */ private void writeResourceFieldAliases(List<Project.ExtendedAttributes.ExtendedAttribute> list) { Map<ResourceField, String> fieldAliasMap = m_projectFile.getResourceFieldAliasMap(); for (int loop = 0; loop < ExtendedAttributeResourceFields.FIELD_ARRAY.length; loop++) { ResourceField key = ExtendedAttributeResourceFields.FIELD_ARRAY[loop]; Integer fieldID = Integer.valueOf(MPPResourceField.getID(key) | MPPResourceField.RESOURCE_FIELD_BASE); String name = key.getName(); String alias = fieldAliasMap.get(key); if (m_resourceExtendedAttributes.contains(key) || alias != null) { Project.ExtendedAttributes.ExtendedAttribute attribute = m_factory.createProjectExtendedAttributesExtendedAttribute(); list.add(attribute); attribute.setFieldID(fieldID.toString()); attribute.setFieldName(name); attribute.setAlias(alias); } } } /** * This method writes calendar data to an MSPDI file. * * @param project Root node of the MSPDI file */ private void writeCalendars(Project project) { // // Create the new MSPDI calendar list // Project.Calendars calendars = m_factory.createProjectCalendars(); project.setCalendars(calendars); List<Project.Calendars.Calendar> calendar = calendars.getCalendar(); // // Process each calendar in turn // for (ProjectCalendar cal : m_projectFile.getCalendars()) { calendar.add(writeCalendar(cal)); } } /** * This method writes data for a single calendar to an MSPDI file. * * @param bc Base calendar data * @return New MSPDI calendar instance */ private Project.Calendars.Calendar writeCalendar(ProjectCalendar bc) { // // Create a calendar // Project.Calendars.Calendar calendar = m_factory.createProjectCalendarsCalendar(); calendar.setUID(NumberUtility.getBigInteger(bc.getUniqueID())); calendar.setIsBaseCalendar(Boolean.valueOf(!bc.isDerived())); ProjectCalendar base = bc.getParent(); if (base != null) { calendar.setBaseCalendarUID(NumberUtility.getBigInteger(base.getUniqueID())); } calendar.setName(bc.getName()); // // Create a list of normal days // Project.Calendars.Calendar.WeekDays days = m_factory.createProjectCalendarsCalendarWeekDays(); Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time; ProjectCalendarHours bch; List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList = days.getWeekDay(); for (int loop = 1; loop < 8; loop++) { DayType workingFlag = bc.getWorkingDay(Day.getInstance(loop)); if (workingFlag != DayType.DEFAULT) { Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay(); dayList.add(day); day.setDayType(BigInteger.valueOf(loop)); day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING)); if (workingFlag == DayType.WORKING) { Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes(); day.setWorkingTimes(times); List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime(); bch = bc.getCalendarHours(Day.getInstance(loop)); if (bch != null) { for (DateRange range : bch) { if (range != null) { time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime(); timesList.add(time); time.setFromTime(DatatypeConverter.printTime(range.getStart())); time.setToTime(DatatypeConverter.printTime(range.getEnd())); } } } } } } // // Create a list of exceptions // // A quirk of MS Project is that these exceptions must be // in date order in the file, otherwise they are ignored // List<ProjectCalendarException> exceptions = new ArrayList<ProjectCalendarException>(bc.getCalendarExceptions()); if (!exceptions.isEmpty()) { Collections.sort(exceptions); writeExceptions(calendar, dayList, exceptions); } // // Do not add a weekdays tag to the calendar unless it // has valid entries. // Fixes SourceForge bug 1854747: MPXJ and MSP 2007 XML formats // if (!dayList.isEmpty()) { calendar.setWeekDays(days); } writeWorkWeeks(calendar, bc); m_projectFile.fireCalendarWrittenEvent(bc); return (calendar); } /** * Main entry point used to determine the format used to write * calendar exceptions. * * @param calendar parent calendar * @param dayList list of calendar days * @param exceptions list of exceptions */ private void writeExceptions(Project.Calendars.Calendar calendar, List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions) { if (m_saveVersion.getValue() < SaveVersion.Project2007.getValue()) { writeExcepions9(dayList, exceptions); } else { writeExcepions12(calendar, exceptions); } } /** * Write exceptions in the format used by MSPDI files prior to Project 2007. * * @param dayList list of calendar days * @param exceptions list of exceptions */ private void writeExcepions9(List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions) { for (ProjectCalendarException exception : exceptions) { boolean working = exception.getWorking(); Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay(); dayList.add(day); day.setDayType(BIGINTEGER_ZERO); day.setDayWorking(Boolean.valueOf(working)); Project.Calendars.Calendar.WeekDays.WeekDay.TimePeriod period = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayTimePeriod(); day.setTimePeriod(period); period.setFromDate(DatatypeConverter.printDate(exception.getFromDate())); period.setToDate(DatatypeConverter.printDate(exception.getToDate())); if (working) { Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes(); day.setWorkingTimes(times); List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime(); for (DateRange range : exception) { Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime(); timesList.add(time); time.setFromTime(DatatypeConverter.printTime(range.getStart())); time.setToTime(DatatypeConverter.printTime(range.getEnd())); } } } } /** * Write exceptions into the format used by MSPDI files from * Project 2007 onwards. * * @param calendar parent calendar * @param exceptions list of exceptions */ private void writeExcepions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions) { Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions(); calendar.setExceptions(ce); List<Exceptions.Exception> el = ce.getException(); for (ProjectCalendarException exception : exceptions) { Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException(); el.add(ex); ex.setEnteredByOccurrences(Boolean.FALSE); ex.setOccurrences(BigInteger.ONE); ex.setType(BigInteger.ONE); boolean working = exception.getWorking(); ex.setDayWorking(Boolean.valueOf(working)); Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod(); ex.setTimePeriod(period); period.setFromDate(DatatypeConverter.printDate(exception.getFromDate())); period.setToDate(DatatypeConverter.printDate(exception.getToDate())); if (working) { Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes(); ex.setWorkingTimes(times); List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime(); for (DateRange range : exception) { Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime(); timesList.add(time); time.setFromTime(DatatypeConverter.printTime(range.getStart())); time.setToTime(DatatypeConverter.printTime(range.getEnd())); } } } } /** * Write the work weeks associated with this calendar. * * @param xmlCalendar XML calendar instance * @param mpxjCalendar MPXJ calendar instance */ private void writeWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar) { List<ProjectCalendarWeek> weeks = mpxjCalendar.getWorkWeeks(); if (!weeks.isEmpty()) { WorkWeeks xmlWorkWeeks = m_factory.createProjectCalendarsCalendarWorkWeeks(); xmlCalendar.setWorkWeeks(xmlWorkWeeks); List<WorkWeek> xmlWorkWeekList = xmlWorkWeeks.getWorkWeek(); for (ProjectCalendarWeek week : weeks) { WorkWeek xmlWeek = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeek(); xmlWorkWeekList.add(xmlWeek); xmlWeek.setName(week.getName()); TimePeriod xmlTimePeriod = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekTimePeriod(); xmlWeek.setTimePeriod(xmlTimePeriod); xmlTimePeriod.setFromDate(DatatypeConverter.printDate(week.getDateRange().getStart())); xmlTimePeriod.setToDate(DatatypeConverter.printDate(week.getDateRange().getEnd())); WeekDays xmlWeekDays = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDays(); xmlWeek.setWeekDays(xmlWeekDays); List<Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay> dayList = xmlWeekDays.getWeekDay(); for (int loop = 1; loop < 8; loop++) { DayType workingFlag = week.getWorkingDay(Day.getInstance(loop)); if (workingFlag != DayType.DEFAULT) { Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDay(); dayList.add(day); day.setDayType(BigInteger.valueOf(loop)); day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING)); if (workingFlag == DayType.WORKING) { Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDayWorkingTimes(); day.setWorkingTimes(times); List<Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime(); ProjectCalendarHours bch = week.getCalendarHours(Day.getInstance(loop)); if (bch != null) { for (DateRange range : bch) { if (range != null) { Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarWorkWeeksWorkWeekWeekDaysWeekDayWorkingTimesWorkingTime(); timesList.add(time); time.setFromTime(DatatypeConverter.printTime(range.getStart())); time.setToTime(DatatypeConverter.printTime(range.getEnd())); } } } } } } } } } /** * This method writes resource data to an MSPDI file. * * @param project Root node of the MSPDI file */ private void writeResources(Project project) { Project.Resources resources = m_factory.createProjectResources(); project.setResources(resources); List<Project.Resources.Resource> list = resources.getResource(); for (Resource resource : m_projectFile.getAllResources()) { list.add(writeResource(resource)); } } /** * This method writes data for a single resource to an MSPDI file. * * @param mpx Resource data * @return New MSPDI resource instance */ private Project.Resources.Resource writeResource(Resource mpx) { Project.Resources.Resource xml = m_factory.createProjectResourcesResource(); ProjectCalendar cal = mpx.getResourceCalendar(); if (cal != null) { xml.setCalendarUID(NumberUtility.getBigInteger(cal.getUniqueID())); } xml.setAccrueAt(mpx.getAccrueAt()); xml.setActiveDirectoryGUID(mpx.getActiveDirectoryGUID()); xml.setActualCost(DatatypeConverter.printCurrency(mpx.getActualCost())); xml.setActualOvertimeCost(DatatypeConverter.printCurrency(mpx.getActualOvertimeCost())); xml.setActualOvertimeWork(DatatypeConverter.printDuration(this, mpx.getActualOvertimeWork())); xml.setActualOvertimeWorkProtected(DatatypeConverter.printDuration(this, mpx.getActualOvertimeWorkProtected())); xml.setActualWork(DatatypeConverter.printDuration(this, mpx.getActualWork())); xml.setActualWorkProtected(DatatypeConverter.printDuration(this, mpx.getActualWorkProtected())); xml.setACWP(DatatypeConverter.printCurrency(mpx.getACWP())); xml.setAvailableFrom(DatatypeConverter.printDate(mpx.getAvailableFrom())); xml.setAvailableTo(DatatypeConverter.printDate(mpx.getAvailableTo())); xml.setBCWS(DatatypeConverter.printCurrency(mpx.getBCWS())); xml.setBCWP(DatatypeConverter.printCurrency(mpx.getBCWP())); xml.setBookingType(mpx.getBookingType()); xml.setIsBudget(Boolean.valueOf(mpx.getBudget())); xml.setCanLevel(Boolean.valueOf(mpx.getCanLevel())); xml.setCode(mpx.getCode()); xml.setCost(DatatypeConverter.printCurrency(mpx.getCost())); xml.setCostPerUse(DatatypeConverter.printCurrency(mpx.getCostPerUse())); xml.setCostVariance(DatatypeConverter.printCurrency(mpx.getCostVariance())); xml.setCreationDate(DatatypeConverter.printDate(mpx.getCreationDate())); xml.setCV(DatatypeConverter.printCurrency(mpx.getCV())); xml.setEmailAddress(mpx.getEmailAddress()); xml.setFinish(DatatypeConverter.printDate(mpx.getFinish())); xml.setGroup(mpx.getGroup()); xml.setHyperlink(mpx.getHyperlink()); xml.setHyperlinkAddress(mpx.getHyperlinkAddress()); xml.setHyperlinkSubAddress(mpx.getHyperlinkSubAddress()); xml.setID(NumberUtility.getBigInteger(mpx.getID())); xml.setInitials(mpx.getInitials()); xml.setIsEnterprise(Boolean.valueOf(mpx.getEnterprise())); xml.setIsGeneric(Boolean.valueOf(mpx.getGeneric())); xml.setIsInactive(Boolean.valueOf(mpx.getInactive())); xml.setIsNull(Boolean.valueOf(mpx.getNull())); xml.setMaterialLabel(mpx.getMaterialLabel()); xml.setMaxUnits(DatatypeConverter.printUnits(mpx.getMaxUnits())); xml.setName(mpx.getName()); if (!mpx.getNotes().isEmpty()) { xml.setNotes(mpx.getNotes()); } xml.setNTAccount(mpx.getNtAccount()); xml.setOverAllocated(Boolean.valueOf(mpx.getOverAllocated())); xml.setOvertimeCost(DatatypeConverter.printCurrency(mpx.getOvertimeCost())); xml.setOvertimeRate(DatatypeConverter.printRate(mpx.getOvertimeRate())); xml.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(mpx.getOvertimeRateUnits())); xml.setOvertimeWork(DatatypeConverter.printDuration(this, mpx.getOvertimeWork())); xml.setPeakUnits(DatatypeConverter.printUnits(mpx.getPeakUnits())); xml.setPercentWorkComplete(NumberUtility.getBigInteger(mpx.getPercentWorkComplete())); xml.setPhonetics(mpx.getPhonetics()); xml.setRegularWork(DatatypeConverter.printDuration(this, mpx.getRegularWork())); xml.setRemainingCost(DatatypeConverter.printCurrency(mpx.getRemainingCost())); xml.setRemainingOvertimeCost(DatatypeConverter.printCurrency(mpx.getRemainingOvertimeCost())); xml.setRemainingOvertimeWork(DatatypeConverter.printDuration(this, mpx.getRemainingOvertimeWork())); xml.setRemainingWork(DatatypeConverter.printDuration(this, mpx.getRemainingWork())); xml.setStandardRate(DatatypeConverter.printRate(mpx.getStandardRate())); xml.setStandardRateFormat(DatatypeConverter.printTimeUnit(mpx.getStandardRateUnits())); xml.setStart(DatatypeConverter.printDate(mpx.getStart())); xml.setSV(DatatypeConverter.printCurrency(mpx.getSV())); xml.setUID(mpx.getUniqueID()); xml.setWork(DatatypeConverter.printDuration(this, mpx.getWork())); xml.setWorkGroup(mpx.getWorkGroup()); xml.setWorkVariance(DatatypeConverter.printDurationInDecimalThousandthsOfMinutes(mpx.getWorkVariance())); if (mpx.getType() == ResourceType.COST) { xml.setType(ResourceType.MATERIAL); xml.setIsCostResource(Boolean.TRUE); } else { xml.setType(mpx.getType()); } writeResourceExtendedAttributes(xml, mpx); writeResourceBaselines(xml, mpx); writeCostRateTables(xml, mpx); writeAvailability(xml, mpx); return (xml); } /** * Writes resource baseline data. * * @param xmlResource MSPDI resource * @param mpxjResource MPXJ resource */ private void writeResourceBaselines(Project.Resources.Resource xmlResource, Resource mpxjResource) { Project.Resources.Resource.Baseline baseline = m_factory.createProjectResourcesResourceBaseline(); boolean populated = false; Number cost = mpxjResource.getBaselineCost(); if (cost != null && cost.intValue() != 0) { populated = true; baseline.setCost(DatatypeConverter.printCurrency(cost)); } Duration work = mpxjResource.getBaselineWork(); if (work != null && work.getDuration() != 0) { populated = true; baseline.setWork(DatatypeConverter.printDuration(this, work)); } if (populated) { xmlResource.getBaseline().add(baseline); baseline.setNumber(BigInteger.ZERO); } for (int loop = 1; loop <= 10; loop++) { baseline = m_factory.createProjectResourcesResourceBaseline(); populated = false; cost = mpxjResource.getBaselineCost(loop); if (cost != null && cost.intValue() != 0) { populated = true; baseline.setCost(DatatypeConverter.printCurrency(cost)); } work = mpxjResource.getBaselineWork(loop); if (work != null && work.getDuration() != 0) { populated = true; baseline.setWork(DatatypeConverter.printDuration(this, work)); } if (populated) { xmlResource.getBaseline().add(baseline); baseline.setNumber(BigInteger.valueOf(loop)); } } } /** * This method writes extended attribute data for a resource. * * @param xml MSPDI resource * @param mpx MPXJ resource */ private void writeResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx) { Project.Resources.Resource.ExtendedAttribute attrib; List<Project.Resources.Resource.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute(); for (int loop = 0; loop < ExtendedAttributeResourceFields.FIELD_ARRAY.length; loop++) { ResourceField mpxFieldID = ExtendedAttributeResourceFields.FIELD_ARRAY[loop]; Object value = mpx.getCachedValue(mpxFieldID); if (writeExtendedAttribute(value, mpxFieldID)) { m_resourceExtendedAttributes.add(mpxFieldID); Integer xmlFieldID = Integer.valueOf(MPPResourceField.getID(mpxFieldID) | MPPResourceField.RESOURCE_FIELD_BASE); attrib = m_factory.createProjectResourcesResourceExtendedAttribute(); extendedAttributes.add(attrib); attrib.setFieldID(xmlFieldID.toString()); attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType())); attrib.setDurationFormat(printExtendedAttributeDurationFormat(value)); } } } /** * This method is called to determine if an extended attribute * should be written to the file, or whether the default value * can be assumed. * * @param value extended attribute value * @param type extended attribute data type * @return boolean flag */ private boolean writeExtendedAttribute(Object value, FieldType type) { boolean write = true; if (value == null) { write = false; } else { DataType dataType = type.getDataType(); switch (dataType) { case BOOLEAN: { write = ((Boolean) value).booleanValue(); break; } case CURRENCY: case NUMERIC: { write = (((Number) value).intValue() != 0); break; } case DURATION: { write = (((Duration) value).getDuration() != 0); break; } default: { break; } } } return write; } /** * Writes a resource's cost rate tables. * * @param xml MSPDI resource * @param mpx MPXJ resource */ private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx) { //Rates rates = m_factory.createProjectResourcesResourceRates(); //xml.setRates(rates); //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate(); List<Project.Resources.Resource.Rates.Rate> ratesList = null; for (int tableIndex = 0; tableIndex < 5; tableIndex++) { CostRateTable table = mpx.getCostRateTable(tableIndex); if (table != null) { Date from = DateUtility.FIRST_DATE; for (CostRateTableEntry entry : table) { if (costRateTableWriteRequired(entry, from)) { if (ratesList == null) { Rates rates = m_factory.createProjectResourcesResourceRates(); xml.setRates(rates); ratesList = rates.getRate(); } Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate(); ratesList.add(rate); rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse())); rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate())); rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat())); rate.setRatesFrom(DatatypeConverter.printDate(from)); from = entry.getEndDate(); rate.setRatesTo(DatatypeConverter.printDate(from)); rate.setRateTable(BigInteger.valueOf(tableIndex)); rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate())); rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat())); } } } } } /** * This method determines whether the cost rate table should be written. * A default cost rate table should not be written to the file. * * @param entry cost rate table entry * @param from from date * @return boolean flag */ private boolean costRateTableWriteRequired(CostRateTableEntry entry, Date from) { boolean fromDate = (DateUtility.compare(from, DateUtility.FIRST_DATE) > 0); boolean toDate = (DateUtility.compare(entry.getEndDate(), DateUtility.LAST_DATE) > 0); boolean costPerUse = (NumberUtility.getDouble(entry.getCostPerUse()) != 0); boolean overtimeRate = (entry.getOvertimeRate() != null && entry.getOvertimeRate().getAmount() != 0); boolean standardRate = (entry.getStandardRate() != null && entry.getStandardRate().getAmount() != 0); return (fromDate || toDate || costPerUse || overtimeRate || standardRate); } /** * This method writes a resource's availability table. * * @param xml MSPDI resource * @param mpx MPXJ resource */ private void writeAvailability(Project.Resources.Resource xml, Resource mpx) { AvailabilityPeriods periods = m_factory.createProjectResourcesResourceAvailabilityPeriods(); xml.setAvailabilityPeriods(periods); List<AvailabilityPeriod> list = periods.getAvailabilityPeriod(); for (Availability availability : mpx.getAvailability()) { AvailabilityPeriod period = m_factory.createProjectResourcesResourceAvailabilityPeriodsAvailabilityPeriod(); list.add(period); DateRange range = availability.getRange(); period.setAvailableFrom(DatatypeConverter.printDate(range.getStart())); period.setAvailableTo(DatatypeConverter.printDate(range.getEnd())); period.setAvailableUnits(DatatypeConverter.printUnits(availability.getUnits())); } } /** * This method writes task data to an MSPDI file. * * @param project Root node of the MSPDI file */ private void writeTasks(Project project) { Project.Tasks tasks = m_factory.createProjectTasks(); project.setTasks(tasks); List<Project.Tasks.Task> list = tasks.getTask(); for (Task task : m_projectFile.getAllTasks()) { list.add(writeTask(task)); } } /** * This method writes data for a single task to an MSPDI file. * * @param mpx Task data * @return new task instance */ private Project.Tasks.Task writeTask(Task mpx) { Project.Tasks.Task xml = m_factory.createProjectTasksTask(); xml.setActive(Boolean.valueOf(mpx.getActive())); xml.setActualCost(DatatypeConverter.printCurrency(mpx.getActualCost())); xml.setActualDuration(DatatypeConverter.printDuration(this, mpx.getActualDuration())); xml.setActualFinish(DatatypeConverter.printDate(mpx.getActualFinish())); xml.setActualOvertimeCost(DatatypeConverter.printCurrency(mpx.getActualOvertimeCost())); xml.setActualOvertimeWork(DatatypeConverter.printDuration(this, mpx.getActualOvertimeWork())); xml.setActualOvertimeWorkProtected(DatatypeConverter.printDuration(this, mpx.getActualOvertimeWorkProtected())); xml.setActualStart(DatatypeConverter.printDate(mpx.getActualStart())); xml.setActualWork(DatatypeConverter.printDuration(this, mpx.getActualWork())); xml.setActualWorkProtected(DatatypeConverter.printDuration(this, mpx.getActualWorkProtected())); xml.setACWP(DatatypeConverter.printCurrency(mpx.getACWP())); xml.setBCWP(DatatypeConverter.printCurrency(mpx.getBCWP())); xml.setBCWS(DatatypeConverter.printCurrency(mpx.getBCWS())); xml.setCalendarUID(getTaskCalendarID(mpx)); xml.setConstraintDate(DatatypeConverter.printDate(mpx.getConstraintDate())); xml.setConstraintType(DatatypeConverter.printConstraintType(mpx.getConstraintType())); xml.setContact(mpx.getContact()); xml.setCost(DatatypeConverter.printCurrency(mpx.getCost())); xml.setCreateDate(DatatypeConverter.printDate(mpx.getCreateDate())); xml.setCritical(Boolean.valueOf(mpx.getCritical())); xml.setCV(DatatypeConverter.printCurrency(mpx.getCV())); xml.setDeadline(DatatypeConverter.printDate(mpx.getDeadline())); xml.setDuration(DatatypeConverter.printDurationMandatory(this, mpx.getDuration())); xml.setDurationText(mpx.getDurationText()); xml.setDurationFormat(DatatypeConverter.printDurationTimeUnits(mpx.getDuration(), mpx.getEstimated())); xml.setEarlyFinish(DatatypeConverter.printDate(mpx.getEarlyFinish())); xml.setEarlyStart(DatatypeConverter.printDate(mpx.getEarlyStart())); xml.setEarnedValueMethod(DatatypeConverter.printEarnedValueMethod(mpx.getEarnedValueMethod())); xml.setEffortDriven(Boolean.valueOf(mpx.getEffortDriven())); xml.setEstimated(Boolean.valueOf(mpx.getEstimated())); xml.setExternalTask(Boolean.valueOf(mpx.getExternalTask())); xml.setExternalTaskProject(mpx.getProject()); xml.setFinish(DatatypeConverter.printDate(mpx.getFinish())); xml.setFinishText(mpx.getFinishText()); xml.setFinishVariance(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getFinishVariance())); xml.setFixedCost(DatatypeConverter.printCurrency(mpx.getFixedCost())); AccrueType fixedCostAccrual = mpx.getFixedCostAccrual(); if (fixedCostAccrual == null) { fixedCostAccrual = AccrueType.PRORATED; } xml.setFixedCostAccrual(fixedCostAccrual); // This is not correct //xml.setFreeSlack(BigInteger.valueOf((long)DatatypeConverter.printDurationInMinutes(mpx.getFreeSlack())*1000)); //xml.setFreeSlack(BIGINTEGER_ZERO); xml.setHideBar(Boolean.valueOf(mpx.getHideBar())); xml.setIsNull(Boolean.valueOf(mpx.getNull())); xml.setIsSubproject(Boolean.valueOf(mpx.getSubProject() != null)); xml.setIsSubprojectReadOnly(Boolean.valueOf(mpx.getSubprojectReadOnly())); xml.setHyperlink(mpx.getHyperlink()); xml.setHyperlinkAddress(mpx.getHyperlinkAddress()); xml.setHyperlinkSubAddress(mpx.getHyperlinkSubAddress()); xml.setID(NumberUtility.getBigInteger(mpx.getID())); xml.setIgnoreResourceCalendar(Boolean.valueOf(mpx.getIgnoreResourceCalendar())); xml.setLateFinish(DatatypeConverter.printDate(mpx.getLateFinish())); xml.setLateStart(DatatypeConverter.printDate(mpx.getLateStart())); xml.setLevelAssignments(Boolean.valueOf(mpx.getLevelAssignments())); xml.setLevelingCanSplit(Boolean.valueOf(mpx.getLevelingCanSplit())); if (mpx.getLevelingDelay() != null) { Duration levelingDelay = mpx.getLevelingDelay(); double tenthMinutes = 10.0 * Duration.convertUnits(levelingDelay.getDuration(), levelingDelay.getUnits(), TimeUnit.MINUTES, m_projectFile.getProjectHeader()).getDuration(); xml.setLevelingDelay(BigInteger.valueOf((long) tenthMinutes)); xml.setLevelingDelayFormat(DatatypeConverter.printDurationTimeUnits(levelingDelay, false)); } xml.setManual(Boolean.valueOf(mpx.getTaskMode() == TaskMode.MANUALLY_SCHEDULED)); if (mpx.getTaskMode() == TaskMode.MANUALLY_SCHEDULED) { xml.setManualDuration(DatatypeConverter.printDuration(this, mpx.getDuration())); xml.setManualFinish(DatatypeConverter.printDate(mpx.getFinish())); xml.setManualStart(DatatypeConverter.printDate(mpx.getStart())); } xml.setMilestone(Boolean.valueOf(mpx.getMilestone())); xml.setName(mpx.getName()); if (!mpx.getNotes().isEmpty()) { xml.setNotes(mpx.getNotes()); } xml.setOutlineLevel(NumberUtility.getBigInteger(mpx.getOutlineLevel())); xml.setOutlineNumber(mpx.getOutlineNumber()); xml.setOverAllocated(Boolean.valueOf(mpx.getOverAllocated())); xml.setOvertimeCost(DatatypeConverter.printCurrency(mpx.getOvertimeCost())); xml.setOvertimeWork(DatatypeConverter.printDuration(this, mpx.getOvertimeWork())); xml.setPercentComplete(NumberUtility.getBigInteger(mpx.getPercentageComplete())); xml.setPercentWorkComplete(NumberUtility.getBigInteger(mpx.getPercentageWorkComplete())); xml.setPhysicalPercentComplete(NumberUtility.getBigInteger(mpx.getPhysicalPercentComplete())); xml.setPriority(DatatypeConverter.printPriority(mpx.getPriority())); xml.setRecurring(Boolean.valueOf(mpx.getRecurring())); xml.setRegularWork(DatatypeConverter.printDuration(this, mpx.getRegularWork())); xml.setRemainingCost(DatatypeConverter.printCurrency(mpx.getRemainingCost())); if (mpx.getRemainingDuration() == null) { Duration duration = mpx.getDuration(); if (duration != null) { double amount = duration.getDuration(); amount -= ((amount * NumberUtility.getDouble(mpx.getPercentageComplete())) / 100); xml.setRemainingDuration(DatatypeConverter.printDuration(this, Duration.getInstance(amount, duration.getUnits()))); } } else { xml.setRemainingDuration(DatatypeConverter.printDuration(this, mpx.getRemainingDuration())); } xml.setRemainingOvertimeCost(DatatypeConverter.printCurrency(mpx.getRemainingOvertimeCost())); xml.setRemainingOvertimeWork(DatatypeConverter.printDuration(this, mpx.getRemainingOvertimeWork())); xml.setRemainingWork(DatatypeConverter.printDuration(this, mpx.getRemainingWork())); xml.setResume(DatatypeConverter.printDate(mpx.getResume())); xml.setResumeValid(Boolean.valueOf(mpx.getResumeValid())); xml.setRollup(Boolean.valueOf(mpx.getRollup())); xml.setStart(DatatypeConverter.printDate(mpx.getStart())); xml.setStartText(mpx.getStartText()); xml.setStartVariance(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getStartVariance())); xml.setStop(DatatypeConverter.printDate(mpx.getStop())); xml.setSubprojectName(mpx.getSubprojectName()); xml.setSummary(Boolean.valueOf(mpx.getSummary())); xml.setTotalSlack(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getTotalSlack())); xml.setType(mpx.getType()); xml.setUID(mpx.getUniqueID()); xml.setWBS(mpx.getWBS()); xml.setWBSLevel(mpx.getWBSLevel()); xml.setWork(DatatypeConverter.printDuration(this, mpx.getWork())); xml.setWorkVariance(DatatypeConverter.printDurationInDecimalThousandthsOfMinutes(mpx.getWorkVariance())); if (mpx.getTaskMode() == TaskMode.MANUALLY_SCHEDULED) { xml.setManualDuration(DatatypeConverter.printDuration(this, mpx.getManualDuration())); } writePredecessors(xml, mpx); writeTaskExtendedAttributes(xml, mpx); writeTaskBaselines(xml, mpx); return (xml); } /** * Writes task baseline data. * * @param xmlTask MSPDI task * @param mpxjTask MPXJ task */ private void writeTaskBaselines(Project.Tasks.Task xmlTask, Task mpxjTask) { Project.Tasks.Task.Baseline baseline = m_factory.createProjectTasksTaskBaseline(); boolean populated = false; Number cost = mpxjTask.getBaselineCost(); if (cost != null && cost.intValue() != 0) { populated = true; baseline.setCost(DatatypeConverter.printCurrency(cost)); } Duration duration = mpxjTask.getBaselineDuration(); if (duration != null && duration.getDuration() != 0) { populated = true; baseline.setDuration(DatatypeConverter.printDuration(this, duration)); baseline.setDurationFormat(DatatypeConverter.printDurationTimeUnits(duration, false)); } Date date = mpxjTask.getBaselineFinish(); if (date != null) { populated = true; baseline.setFinish(DatatypeConverter.printDate(date)); } date = mpxjTask.getBaselineStart(); if (date != null) { populated = true; baseline.setStart(DatatypeConverter.printDate(date)); } duration = mpxjTask.getBaselineWork(); if (duration != null && duration.getDuration() != 0) { populated = true; baseline.setWork(DatatypeConverter.printDuration(this, duration)); } if (populated) { baseline.setNumber(BigInteger.ZERO); xmlTask.getBaseline().add(baseline); } for (int loop = 1; loop <= 10; loop++) { baseline = m_factory.createProjectTasksTaskBaseline(); populated = false; cost = mpxjTask.getBaselineCost(loop); if (cost != null && cost.intValue() != 0) { populated = true; baseline.setCost(DatatypeConverter.printCurrency(cost)); } duration = mpxjTask.getBaselineDuration(loop); if (duration != null && duration.getDuration() != 0) { populated = true; baseline.setDuration(DatatypeConverter.printDuration(this, duration)); baseline.setDurationFormat(DatatypeConverter.printDurationTimeUnits(duration, false)); } date = mpxjTask.getBaselineFinish(loop); if (date != null) { populated = true; baseline.setFinish(DatatypeConverter.printDate(date)); } date = mpxjTask.getBaselineStart(loop); if (date != null) { populated = true; baseline.setStart(DatatypeConverter.printDate(date)); } duration = mpxjTask.getBaselineWork(loop); if (duration != null && duration.getDuration() != 0) { populated = true; baseline.setWork(DatatypeConverter.printDuration(this, duration)); } if (populated) { baseline.setNumber(BigInteger.valueOf(loop)); xmlTask.getBaseline().add(baseline); } } } /** * This method writes extended attribute data for a task. * * @param xml MSPDI task * @param mpx MPXJ task */ private void writeTaskExtendedAttributes(Project.Tasks.Task xml, Task mpx) { Project.Tasks.Task.ExtendedAttribute attrib; List<Project.Tasks.Task.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute(); for (int loop = 0; loop < ExtendedAttributeTaskFields.FIELD_ARRAY.length; loop++) { TaskField mpxFieldID = ExtendedAttributeTaskFields.FIELD_ARRAY[loop]; Object value = mpx.getCachedValue(mpxFieldID); if (writeExtendedAttribute(value, mpxFieldID)) { m_taskExtendedAttributes.add(mpxFieldID); Integer xmlFieldID = Integer.valueOf(MPPTaskField.getID(mpxFieldID) | MPPTaskField.TASK_FIELD_BASE); attrib = m_factory.createProjectTasksTaskExtendedAttribute(); extendedAttributes.add(attrib); attrib.setFieldID(xmlFieldID.toString()); attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType())); attrib.setDurationFormat(printExtendedAttributeDurationFormat(value)); } } } /** * Converts a duration to duration time units. * * @param value duration value * @return duration time units */ private BigInteger printExtendedAttributeDurationFormat(Object value) { BigInteger result = null; if (value instanceof Duration) { result = DatatypeConverter.printDurationTimeUnits(((Duration) value).getUnits(), false); } return (result); } /** * This method retrieves the UID for a calendar associated with a task. * * @param mpx MPX Task instance * @return calendar UID */ private BigInteger getTaskCalendarID(Task mpx) { BigInteger result = null; ProjectCalendar cal = mpx.getCalendar(); if (cal != null) { result = NumberUtility.getBigInteger(cal.getUniqueID()); } else { result = BigInteger.valueOf(-1); } return (result); } /** * This method writes predecessor data to an MSPDI file. * We have to deal with a slight anomaly in this method that is introduced * by the MPX file format. It would be possible for someone to create an * MPX file with both the predecessor list and the unique ID predecessor * list populated... which means that we must process both and avoid adding * duplicate predecessors. Also interesting to note is that MSP98 populates * the predecessor list, not the unique ID predecessor list, as you might * expect. * * @param xml MSPDI task data * @param mpx MPX task data */ private void writePredecessors(Project.Tasks.Task xml, Task mpx) { List<Project.Tasks.Task.PredecessorLink> list = xml.getPredecessorLink(); List<Relation> predecessors = mpx.getPredecessors(); if (predecessors != null) { for (Relation rel : predecessors) { Integer taskUniqueID = rel.getTargetTask().getUniqueID(); list.add(writePredecessor(taskUniqueID, rel.getType(), rel.getLag())); m_projectFile.fireRelationWrittenEvent(rel); } } } /** * This method writes a single predecessor link to the MSPDI file. * * @param taskID The task UID * @param type The predecessor type * @param lag The lag duration * @return A new link to be added to the MSPDI file */ private Project.Tasks.Task.PredecessorLink writePredecessor(Integer taskID, RelationType type, Duration lag) { Project.Tasks.Task.PredecessorLink link = m_factory.createProjectTasksTaskPredecessorLink(); link.setPredecessorUID(NumberUtility.getBigInteger(taskID)); link.setType(BigInteger.valueOf(type.getValue())); if (lag != null && lag.getDuration() != 0) { double linkLag = lag.getDuration(); if (lag.getUnits() != TimeUnit.PERCENT) { linkLag = 10.0 * Duration.convertUnits(linkLag, lag.getUnits(), TimeUnit.MINUTES, m_projectFile.getProjectHeader()).getDuration(); } link.setLinkLag(BigInteger.valueOf((long) linkLag)); link.setLagFormat(DatatypeConverter.printDurationTimeUnits(lag.getUnits(), false)); } return (link); } /** * This method writes assignment data to an MSPDI file. * * @param project Root node of the MSPDI file */ private void writeAssignments(Project project) { Project.Assignments assignments = m_factory.createProjectAssignments(); project.setAssignments(assignments); List<Project.Assignments.Assignment> list = assignments.getAssignment(); for (ResourceAssignment assignment : m_projectFile.getAllResourceAssignments()) { list.add(writeAssignment(assignment)); } // // Check to see if we have any tasks that have a percent complete value // but do not have resource assignments. If any exist, then we must // write a dummy resource assignment record to ensure that the MSPDI // file shows the correct percent complete amount for the task. // boolean autoUniqueID = m_projectFile.getAutoAssignmentUniqueID(); if (!autoUniqueID) { m_projectFile.setAutoAssignmentUniqueID(true); } for (Task task : m_projectFile.getAllTasks()) { double percentComplete = NumberUtility.getDouble(task.getPercentageComplete()); if (percentComplete != 0 && task.getResourceAssignments().isEmpty() == true) { ResourceAssignment dummy = m_projectFile.newResourceAssignment(task); Duration duration = task.getDuration(); if (duration == null) { duration = Duration.getInstance(0, TimeUnit.HOURS); } double durationValue = duration.getDuration(); TimeUnit durationUnits = duration.getUnits(); double actualWork = (durationValue * percentComplete) / 100; double remainingWork = durationValue - actualWork; dummy.setResourceUniqueID(NULL_RESOURCE_ID); dummy.setWork(duration); dummy.setActualWork(Duration.getInstance(actualWork, durationUnits)); dummy.setRemainingWork(Duration.getInstance(remainingWork, durationUnits)); list.add(writeAssignment(dummy)); } } m_projectFile.setAutoAssignmentUniqueID(autoUniqueID); } /** * This method writes data for a single assignment to an MSPDI file. * * @param mpx Resource assignment data * @return New MSPDI assignment instance */ private Project.Assignments.Assignment writeAssignment(ResourceAssignment mpx) { Project.Assignments.Assignment xml = m_factory.createProjectAssignmentsAssignment(); xml.setActualCost(DatatypeConverter.printCurrency(mpx.getActualCost())); xml.setActualFinish(DatatypeConverter.printDate(mpx.getActualFinish())); xml.setActualOvertimeCost(DatatypeConverter.printCurrency(mpx.getActualOvertimeCost())); xml.setActualOvertimeWork(DatatypeConverter.printDuration(this, mpx.getActualOvertimeWork())); xml.setActualStart(DatatypeConverter.printDate(mpx.getActualStart())); xml.setActualWork(DatatypeConverter.printDuration(this, mpx.getActualWork())); xml.setACWP(DatatypeConverter.printCurrency(mpx.getACWP())); xml.setBCWP(DatatypeConverter.printCurrency(mpx.getBCWP())); xml.setBCWS(DatatypeConverter.printCurrency(mpx.getBCWS())); xml.setBudgetCost(DatatypeConverter.printCurrency(mpx.getBudgetCost())); xml.setBudgetWork(DatatypeConverter.printDuration(this, mpx.getBudgetWork())); xml.setCost(DatatypeConverter.printCurrency(mpx.getCost())); if (mpx.getCostRateTableIndex() != 0) { xml.setCostRateTable(BigInteger.valueOf(mpx.getCostRateTableIndex())); } xml.setCreationDate(DatatypeConverter.printDate(mpx.getCreateDate())); xml.setCV(DatatypeConverter.printCurrency(mpx.getCV())); xml.setDelay(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getDelay())); xml.setFinish(DatatypeConverter.printDate(mpx.getFinish())); xml.setHasFixedRateUnits(Boolean.valueOf(mpx.getVariableRateUnits() == null)); xml.setFixedMaterial(Boolean.valueOf(mpx.getResource() != null && mpx.getResource().getType() == ResourceType.MATERIAL)); xml.setHyperlink(mpx.getHyperlink()); xml.setHyperlinkAddress(mpx.getHyperlinkAddress()); xml.setHyperlinkSubAddress(mpx.getHyperlinkSubAddress()); xml.setLevelingDelay(DatatypeConverter.printDurationInTenthsOfInMinutes(mpx.getLevelingDelay())); xml.setLevelingDelayFormat(DatatypeConverter.printDurationTimeUnits(mpx.getLevelingDelay(), false)); if (!mpx.getNotes().isEmpty()) { xml.setNotes(mpx.getNotes()); } xml.setOvertimeCost(DatatypeConverter.printCurrency(mpx.getOvertimeCost())); xml.setOvertimeWork(DatatypeConverter.printDuration(this, mpx.getOvertimeWork())); xml.setPercentWorkComplete(NumberUtility.getBigInteger(mpx.getPercentageWorkComplete())); xml.setRateScale(mpx.getVariableRateUnits() == null ? null : DatatypeConverter.printTimeUnit(mpx.getVariableRateUnits())); xml.setRegularWork(DatatypeConverter.printDuration(this, mpx.getRegularWork())); xml.setRemainingCost(DatatypeConverter.printCurrency(mpx.getRemainingCost())); xml.setRemainingOvertimeCost(DatatypeConverter.printCurrency(mpx.getRemainingOvertimeCost())); xml.setRemainingOvertimeWork(DatatypeConverter.printDuration(this, mpx.getRemainingOvertimeWork())); xml.setRemainingWork(DatatypeConverter.printDuration(this, mpx.getRemainingWork())); xml.setResourceUID(mpx.getResource() == null ? BigInteger.valueOf(NULL_RESOURCE_ID.intValue()) : BigInteger.valueOf(NumberUtility.getInt(mpx.getResourceUniqueID()))); xml.setStart(DatatypeConverter.printDate(mpx.getStart())); xml.setSV(DatatypeConverter.printCurrency(mpx.getSV())); xml.setTaskUID(NumberUtility.getBigInteger(mpx.getTask().getUniqueID())); xml.setUID(NumberUtility.getBigInteger(mpx.getUniqueID())); xml.setUnits(DatatypeConverter.printUnits(mpx.getUnits())); xml.setVAC(DatatypeConverter.printCurrency(mpx.getVAC())); xml.setWork(DatatypeConverter.printDuration(this, mpx.getWork())); xml.setWorkContour(mpx.getWorkContour()); xml.setCostVariance(DatatypeConverter.printCurrency(mpx.getCostVariance())); xml.setWorkVariance(DatatypeConverter.printDurationInDecimalThousandthsOfMinutes(mpx.getWorkVariance())); xml.setStartVariance(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getStartVariance())); xml.setFinishVariance(DatatypeConverter.printDurationInIntegerThousandthsOfMinutes(mpx.getFinishVariance())); writeAssignmentBaselines(xml, mpx); writeAssignmentExtendedAttributes(xml, mpx); writeAssignmentTimephasedData(mpx, xml); m_projectFile.fireAssignmentWrittenEvent(mpx); return (xml); } /** * Writes assignment baseline data. * * @param xml MSPDI assignment * @param mpxj MPXJ assignment */ private void writeAssignmentBaselines(Project.Assignments.Assignment xml, ResourceAssignment mpxj) { Project.Assignments.Assignment.Baseline baseline = m_factory.createProjectAssignmentsAssignmentBaseline(); boolean populated = false; Number cost = mpxj.getBaselineCost(); if (cost != null && cost.intValue() != 0) { populated = true; baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost)); } Date date = mpxj.getBaselineFinish(); if (date != null) { populated = true; baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date)); } date = mpxj.getBaselineStart(); if (date != null) { populated = true; baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date)); } Duration duration = mpxj.getBaselineWork(); if (duration != null && duration.getDuration() != 0) { populated = true; baseline.setWork(DatatypeConverter.printDuration(this, duration)); } if (populated) { baseline.setNumber("0"); xml.getBaseline().add(baseline); } for (int loop = 1; loop <= 10; loop++) { baseline = m_factory.createProjectAssignmentsAssignmentBaseline(); populated = false; cost = mpxj.getBaselineCost(loop); if (cost != null && cost.intValue() != 0) { populated = true; baseline.setCost(DatatypeConverter.printExtendedAttributeCurrency(cost)); } date = mpxj.getBaselineFinish(loop); if (date != null) { populated = true; baseline.setFinish(DatatypeConverter.printExtendedAttributeDate(date)); } date = mpxj.getBaselineStart(loop); if (date != null) { populated = true; baseline.setStart(DatatypeConverter.printExtendedAttributeDate(date)); } duration = mpxj.getBaselineWork(loop); if (duration != null && duration.getDuration() != 0) { populated = true; baseline.setWork(DatatypeConverter.printDuration(this, duration)); } if (populated) { baseline.setNumber(Integer.toString(loop)); xml.getBaseline().add(baseline); } } } /** * This method writes extended attribute data for an assignment. * * @param xml MSPDI assignment * @param mpx MPXJ assignment */ private void writeAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx) { Project.Assignments.Assignment.ExtendedAttribute attrib; List<Project.Assignments.Assignment.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute(); for (int loop = 0; loop < ExtendedAttributeAssignmentFields.FIELD_ARRAY.length; loop++) { AssignmentField mpxFieldID = ExtendedAttributeAssignmentFields.FIELD_ARRAY[loop]; Object value = mpx.getCachedValue(mpxFieldID); if (writeExtendedAttribute(value, mpxFieldID)) { m_assignmentExtendedAttributes.add(mpxFieldID); Integer xmlFieldID = Integer.valueOf(MPPAssignmentField.getID(mpxFieldID) | MPPAssignmentField.ASSIGNMENT_FIELD_BASE); attrib = m_factory.createProjectAssignmentsAssignmentExtendedAttribute(); extendedAttributes.add(attrib); attrib.setFieldID(xmlFieldID.toString()); attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType())); attrib.setDurationFormat(printExtendedAttributeDurationFormat(value)); } } } /** * Writes the timephased data for a resource assignment. * * @param mpx MPXJ assignment * @param xml MSDPI assignment */ private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml) { if (m_writeTimphasedData && mpx.getHasTimephasedData()) { List<TimephasedDataType> list = xml.getTimephasedData(); ProjectCalendar calendar = mpx.getCalendar(); BigInteger assignmentID = xml.getUID(); List<TimephasedWork> complete = mpx.getTimephasedActualWork(); List<TimephasedWork> planned = mpx.getTimephasedWork(); if (m_splitTimephasedAsDays) { TimephasedWork lastComplete = null; if (!complete.isEmpty()) { lastComplete = complete.get(complete.size() - 1); } TimephasedWork firstPlanned = null; if (!planned.isEmpty()) { firstPlanned = planned.get(0); } planned = splitDays(calendar, mpx.getTimephasedWork(), null, lastComplete); complete = splitDays(calendar, complete, firstPlanned, null); } writeAssignmentTimephasedData(assignmentID, list, planned, 1); writeAssignmentTimephasedData(assignmentID, list, complete, 2); } } /** * Splits timephased data into individual days. * * @param calendar current calendar * @param list list of timephased assignment data * @param first first planned assignment * @param last last completed assignment * @return list of timephased data ready for output */ private List<TimephasedWork> splitDays(ProjectCalendar calendar, List<TimephasedWork> list, TimephasedWork first, TimephasedWork last) { List<TimephasedWork> result = new LinkedList<TimephasedWork>(); for (TimephasedWork assignment : list) { Date startDate = assignment.getStart(); Date finishDate = assignment.getFinish(); Date startDay = DateUtility.getDayStartDate(startDate); Date finishDay = DateUtility.getDayStartDate(finishDate); if (startDay.getTime() == finishDay.getTime()) { Date startTime = calendar.getStartTime(startDay); Date currentStart = DateUtility.setTime(startDay, startTime); if (startDate.getTime() > currentStart.getTime()) { boolean paddingRequired = true; if (last != null) { Date lastFinish = last.getFinish(); if (lastFinish.getTime() == startDate.getTime()) { paddingRequired = false; } else { Date lastFinishDay = DateUtility.getDayStartDate(lastFinish); if (startDay.getTime() == lastFinishDay.getTime()) { currentStart = lastFinish; } } } if (paddingRequired) { Duration zeroHours = Duration.getInstance(0, TimeUnit.HOURS); TimephasedWork padding = new TimephasedWork(); padding.setStart(currentStart); padding.setFinish(startDate); padding.setTotalAmount(zeroHours); padding.setAmountPerDay(zeroHours); result.add(padding); } } result.add(assignment); Date endTime = calendar.getFinishTime(startDay); Date currentFinish = DateUtility.setTime(startDay, endTime); if (finishDate.getTime() < currentFinish.getTime()) { boolean paddingRequired = true; if (first != null) { Date firstStart = first.getStart(); if (firstStart.getTime() == finishDate.getTime()) { paddingRequired = false; } else { Date firstStartDay = DateUtility.getDayStartDate(firstStart); if (finishDay.getTime() == firstStartDay.getTime()) { currentFinish = firstStart; } } } if (paddingRequired) { Duration zeroHours = Duration.getInstance(0, TimeUnit.HOURS); TimephasedWork padding = new TimephasedWork(); padding.setStart(finishDate); padding.setFinish(currentFinish); padding.setTotalAmount(zeroHours); padding.setAmountPerDay(zeroHours); result.add(padding); } } } else { Date currentStart = startDate; Calendar cal = Calendar.getInstance(); boolean isWorking = calendar.isWorkingDate(currentStart); while (currentStart.getTime() < finishDate.getTime()) { if (isWorking) { Date endTime = calendar.getFinishTime(currentStart); Date currentFinish = DateUtility.setTime(currentStart, endTime); if (currentFinish.getTime() > finishDate.getTime()) { currentFinish = finishDate; } TimephasedWork split = new TimephasedWork(); split.setStart(currentStart); split.setFinish(currentFinish); split.setTotalAmount(assignment.getAmountPerDay()); split.setAmountPerDay(assignment.getAmountPerDay()); result.add(split); } cal.setTime(currentStart); cal.add(Calendar.DAY_OF_YEAR, 1); currentStart = cal.getTime(); isWorking = calendar.isWorkingDate(currentStart); if (isWorking) { Date startTime = calendar.getStartTime(currentStart); DateUtility.setTime(cal, startTime); currentStart = cal.getTime(); } } } } return result; } /** * Writes a list of timephased data to the MSPDI file. * * @param assignmentID current assignment ID * @param list output list of timephased data items * @param data input list of timephased data * @param type list type (planned or completed) */ private void writeAssignmentTimephasedData(BigInteger assignmentID, List<TimephasedDataType> list, List<TimephasedWork> data, int type) { for (TimephasedWork mpx : data) { TimephasedDataType xml = m_factory.createTimephasedDataType(); list.add(xml); xml.setStart(DatatypeConverter.printDate(mpx.getStart())); xml.setFinish(DatatypeConverter.printDate(mpx.getFinish())); xml.setType(BigInteger.valueOf(type)); xml.setUID(assignmentID); xml.setUnit(DatatypeConverter.printDurationTimeUnits(mpx.getTotalAmount(), false)); xml.setValue(DatatypeConverter.printDuration(this, mpx.getTotalAmount())); } } /** * Package-private accessor method used to retrieve the project file * currently being processed by this writer. * * @return project file instance */ ProjectFile getProjectFile() { return (m_projectFile); } /** * Cached context to minimise construction cost. */ private static JAXBContext CONTEXT; /** * Note any error occurring during context construction. */ private static JAXBException CONTEXT_EXCEPTION; static { try { // // JAXB RI property to speed up construction // System.setProperty("com.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot", "true"); // // Construct the context // CONTEXT = JAXBContext.newInstance("net.sf.mpxj.mspdi.schema", MSPDIWriter.class.getClassLoader()); } catch (JAXBException ex) { CONTEXT_EXCEPTION = ex; CONTEXT = null; } } private ObjectFactory m_factory; private ProjectFile m_projectFile; private Set<TaskField> m_taskExtendedAttributes; private Set<ResourceField> m_resourceExtendedAttributes; private Set<AssignmentField> m_assignmentExtendedAttributes; private boolean m_splitTimephasedAsDays = true; private boolean m_writeTimphasedData; private SaveVersion m_saveVersion = SaveVersion.Project2002; private static final BigInteger BIGINTEGER_ZERO = BigInteger.valueOf(0); private static final Integer NULL_RESOURCE_ID = Integer.valueOf(-65535); }
lgpl-2.1
jemora/shabono-hotel
buscador_reservaciones2.php
6092
<?php require_once('conector/conector.php');?> <? $dbh=mysql_connect ($hostname,$username,$password) or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ($database); $resultinfo = mysql_query("SELECT * FROM informacion WHERE cod LIKE '0'"); ?> <title><? while ($row=mysql_fetch_array($resultinfo)) { echo "".$row["nombre"].""; } mysql_free_result($resultinfo)?></title> <script language="JavaScript" type="text/javascript" src="date-picker.js"></script> <!-- body,td,th { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; } .Estilo3 {font-size: 10px} --> </style><div align="center"><img src="imagenes/banne9.gif" width="607" height="30" /> <br /> </div> </p> <table width="607" border="0" align="center" cellpadding="0" cellspacing="0"> <!-- fwtable fwsrc="Untitled" fwbase="visor.jpg" fwstyle="Dreamweaver" fwdocid = "237802607" fwnested="0" --> <tr> <td><img src="imagenes/spacer.gif" width="5" height="1" border="0" alt="" /></td> <td><img src="imagenes/spacer.gif" width="593" height="1" border="0" alt="" /></td> <td><img src="imagenes/spacer.gif" width="9" height="1" border="0" alt="" /></td> <td><img src="imagenes/spacer.gif" width="1" height="1" border="0" alt="" /></td> </tr> <tr> <td colspan="3"><img src="imagenes/visor_r1_c1.jpg" alt="" name="visor_r1_c1" width="607" height="11" border="0" id="visor_r1_c1" /></td> <td><img src="imagenes/spacer.gif" width="1" height="11" border="0" alt="" /></td> </tr> <tr> <td background="imagenes/visor_r2_c1.jpg">&nbsp;</td> <td><table width="0" border="0" align="center" cellspacing="0"> <tr> <th width="29" scope="col">&nbsp;</th> <th width="553" colspan="2" scope="col"><table width="176" height="28" border="0" align="left" cellspacing="0" bgcolor="#FF9900"> <tr> <td width="174" height="28" bgcolor="#FFFFFF"><form name="form1" action="?id2=tipo" method="post"> <div align="left"> <table width="550" border="0" cellspacing="0"> <tr> <th colspan="5" scope="col"><div align="left"><strong>Habitaciones Reservadas por Tipo</strong></div></th> </tr> <tr> <th width="147" height="26" scope="col"><span class="Estilo3">Tipo de Habitacion:</span></th> <th width="47" scope="col"><font face="Arial, Helvetica, sans-serif"><font face="Arial, Helvetica, sans-serif" size="1"><span class="titulos"> <select name="tipo" id="tipo" style="background-color:e3e3e3; border: 1px solid #666666; font-size:8pt; color: #000099"> <?php mysql_select_db($database, $connFlashblog); $query_rsCategorias = "SELECT * FROM hab_tipo ORDER BY id_tipo ASC"; $rsCategorias = mysql_query($query_rsCategorias, $connFlashblog) or die(mysql_error()); $row_rsCategorias = mysql_fetch_assoc($rsCategorias); $totalRows_rsCategorias = mysql_num_rows($rsCategorias); do { ?> <option value="<?php echo $row_rsCategorias['id_tipo']?>" ><?php echo $row_rsCategorias['tipo']?></option> <?php } while ($row_rsCategorias = mysql_fetch_assoc($rsCategorias)); ?> </select> </span></font></font></th> <th width="106" scope="col"><div align="right" class="Estilo3">Fecha Desde:</div></th> <th width="152" scope="col"><div align="right"> <input name="fecha1" type="text" id="fecha1" value="<? echo $fecha1; ?>" size="15" /> <a href="javascript:show_calendar('form1.fecha1');" onmouseover="window.status='Date Picker';return true;" onmouseout="window.status='';return true;"><img src="show-calendar.gif" width="24" height="22" border="0" align="absmiddle" /></a></div></th> <th width="88" scope="col"><font face="Arial, Helvetica, sans-serif"><font face="Arial, Helvetica, sans-serif" size="1"><span class="titulos"> <input name="submit22222" type="submit" value="Buscar" /> </span></font></font></th> </tr> <tr> <th scope="col">&nbsp;</th> <th scope="col">&nbsp;</th> <th scope="col"><div align="right" class="Estilo3">Fecha Hasta:</div></th> <td> <div align="right"> <input name="fecha2" type="text" id="fecha2" value="<? echo $fecha1; ?>" size="15" /> <a href="javascript:show_calendar('form1.fecha2');" onmouseover="window.status='Date Picker';return true;" onmouseout="window.status='';return true;"><img src="show-calendar.gif" width="24" height="22" border="0" align="absmiddle" /></a></div></td><th scope="col"></th> </tr> </table> </div> </form></td> </tr> </table> </th> </tr> <tr> <th height="2" colspan="3" scope="col"></th> </tr> </table></td> <td background="imagenes/visor_r2_c3.jpg">&nbsp;</td> <td><img src="imagenes/spacer.gif" width="1" height="55" border="0" alt="" /></td> </tr> <tr> <td colspan="3"><img src="imagenes/visor_r3_c1.jpg" alt="" name="visor_r3_c1" width="607" height="13" border="0" id="visor_r3_c1" /></td> <td><img src="imagenes/spacer.gif" width="1" height="13" border="0" alt="" /></td> </tr> </table> <table width="601" border="0" align="center" cellspacing="0"> <tr> <td><?php include('imprimir.php'); ?></td> </tr> <tr> <td><?php if ( $id2 == 'tipo' ) { include("opcion_reserva_x_tipo.php"); } else if ( $test1[0] == '0' ) { echo ""; } ?></td> </tr> </table> <p>&nbsp;</p> <p>&nbsp;</p>
lgpl-2.1
BG2-Dev-Team/BG2-Code
public/haptics/haptic_utils.cpp
10495
#include "cbase.h" #ifdef CLIENT_DLL #include "tier3/tier3.h" #include "iviewrender.h" #include "inputsystem/iinputsystem.h" #include "vgui/IInputInternal.h" #include "c_basecombatweapon.h" #include "c_baseplayer.h" #include "haptics/ihaptics.h" #include "hud_macros.h" #include "iclientvehicle.h" #include "c_prop_vehicle.h" #include "prediction.h" #include "activitylist.h" #ifdef TERROR #include "ClientTerrorPlayer.h" #endif extern vgui::IInputInternal *g_InputInternal; #else #include "usermessages.h" #endif #include "haptics/haptic_utils.h" #include "haptics/haptic_msgs.h" #ifndef TERROR #ifndef FCVAR_RELEASE #define FCVAR_RELEASE 0 #endif #endif #ifdef CLIENT_DLL ConVar hap_HasDevice ( "hap_HasDevice", "0", FCVAR_USERINFO/*|FCVAR_HIDDEN*/, "falcon is connected" ); // damage scale on a title basis. Convar referenced in the haptic dll. #ifdef PORTAL #define HAP_DEFAULT_DAMAGE_SCALE_GAME "0.75" #elif TF_CLIENT_DLL #define HAP_DEFAULT_DAMAGE_SCALE_GAME "0.3" #else #define HAP_DEFAULT_DAMAGE_SCALE_GAME "1.0" #endif ConVar hap_damagescale_game("hap_damagescale_game", HAP_DEFAULT_DAMAGE_SCALE_GAME); #undef HAP_DEFAULT_DAMAGE_SCALE_GAME #endif void HapticSendWeaponAnim(CBaseCombatWeapon* weapon, int iActivity) { //ignore idle if(iActivity == ACT_VM_IDLE) return; #if defined( CLIENT_DLL ) //if(hap_PrintEvents.GetBool()) // Msg("Client Activity :%s %s %s\n",weapon->GetName(),"Activities",VarArgs("%i",iActivity)); if ( weapon->IsPredicted() ) haptics->ProcessHapticWeaponActivity(weapon->GetName(),iActivity); #else if( !weapon->IsPredicted() && weapon->GetOwner() && weapon->GetOwner()->IsPlayer()) { HapticMsg_SendWeaponAnim( ToBasePlayer(weapon->GetOwner()), iActivity ); } #endif } void HapticSetDrag(CBasePlayer* pPlayer, float drag) { #ifdef CLIENT_DLL haptics->SetDrag(drag); #else HapticMsg_SetDrag( pPlayer, drag ); #endif } #ifdef CLIENT_DLL void HapticsHandleMsg_HapSetDrag( float drag ) { haptics->SetDrag(drag); } #endif void HapticSetConstantForce(CBasePlayer* pPlayer, Vector force) { #ifdef CLIENT_DLL haptics->SetConstantForce(force); #else HapticMsg_SetConstantForce( pPlayer, force ); #endif } #ifdef CLIENT_DLL #ifndef HAPTICS_TEST_PREFIX #define HAPTICS_TEST_PREFIX #endif static CSysModule *pFalconModule =0; void ConnectHaptics(CreateInterfaceFn appFactory) { bool success = false; // NVNT load haptics module pFalconModule = Sys_LoadModule( HAPTICS_TEST_PREFIX HAPTICS_DLL_NAME ); if(pFalconModule) { CreateInterfaceFn factory = Sys_GetFactory( pFalconModule ); if(factory) { haptics = reinterpret_cast< IHaptics* >( factory( HAPTICS_INTERFACE_VERSION, NULL ) ); if(haptics && haptics->Initialize(engine, view, g_InputInternal, gpGlobals, appFactory, g_pVGuiInput->GetIMEWindow(), filesystem, enginevgui, ActivityList_IndexForName, ActivityList_NameForIndex)) { success = true; hap_HasDevice.SetValue(1); } } } if(!success) { Sys_UnloadModule(pFalconModule); pFalconModule = 0; haptics = new CHapticsStubbed; } if(haptics->HasDevice()) { Assert( (void*)haptics == inputsystem->GetHapticsInterfaceAddress() ); } HookHapticMessages(); } void DisconnectHaptics() { if (haptics) haptics->ShutdownHaptics(); if(pFalconModule) { Sys_UnloadModule(pFalconModule); pFalconModule = 0; }else{ // delete the stub. delete haptics; } haptics = NULL; } //Might be able to handle this better... void HapticsHandleMsg_HapSetConst( Vector const &constant ) { //Msg("__MsgFunc_HapSetConst: %f %f %f\n",constant.x,constant.y,constant.z); haptics->SetConstantForce(constant); //C_BasePlayer* pPlayer = C_BasePlayer::GetLocalPlayer(); } //Might be able to handle this better... void HapticsHandleMsg_SPHapWeapEvent( int iActivity ) { C_BasePlayer* pPlayer = C_BasePlayer::GetLocalPlayer(); C_BaseCombatWeapon* weap = NULL; if(pPlayer) weap = pPlayer->GetActiveWeapon(); if(weap) haptics->ProcessHapticEvent(4,"Weapons",weap->GetName(),"Activities",VarArgs("%i",iActivity)); } void HapticsHandleMsg_HapPunch( QAngle const &angle ) { haptics->HapticsPunch(1,angle); } #ifdef TERROR ConVar hap_zombie_damage_scale("hap_zombie_damage_scale", "0.25", FCVAR_RELEASE|FCVAR_NEVER_AS_STRING); #endif void HapticsHandleMsg_HapDmg( float pitch, float yaw, float damage, int damageType ) { if(!haptics->HasDevice()) return; #ifdef TERROR C_TerrorPlayer *pPlayer = C_TerrorPlayer::GetLocalTerrorPlayer(); #else C_BasePlayer *pPlayer = CBasePlayer::GetLocalPlayer(); #endif if(pPlayer) { Vector damageDirection; damageDirection.x = cos(pitch*M_PI/180.0)*sin(yaw*M_PI/180.0); damageDirection.y = -sin(pitch*M_PI/180.0); damageDirection.z = -(cos(pitch*M_PI/180.0)*cos(yaw*M_PI/180.0)); #ifdef TERROR if(pPlayer->GetTeamNumber()==TEAM_ZOMBIE) { damageDirection *= hap_zombie_damage_scale.GetFloat(); } #endif haptics->ApplyDamageEffect(damage, damageType, damageDirection); } } ConVar hap_melee_scale("hap_melee_scale", "0.8", FCVAR_RELEASE|FCVAR_NEVER_AS_STRING); void HapticsHandleMsg_HapMeleeContact() { haptics->HapticsPunch(hap_melee_scale.GetFloat(), QAngle(0,0,0)); } ConVar hap_noclip_avatar_scale("hap_noclip_avatar_scale", "0.10f", FCVAR_RELEASE|FCVAR_NEVER_AS_STRING); void UpdateAvatarEffect(void) { if(!haptics->HasDevice()) return; Vector vel; Vector vvel; Vector evel; QAngle eye; C_BasePlayer* pPlayer = C_BasePlayer::GetLocalPlayer(); if(!pPlayer) return; eye = pPlayer->GetAbsAngles(); if(pPlayer->IsInAVehicle() && pPlayer->GetVehicle()) { pPlayer->GetVehicle()->GetVehicleEnt()->EstimateAbsVelocity(vvel); eye = pPlayer->GetVehicle()->GetVehicleEnt()->EyeAngles(); if(!Q_stristr(pPlayer->GetVehicle()->GetVehicleEnt()->GetClassname(),"choreo")) { eye[YAW] += 90; } } else { vel = pPlayer->GetAbsVelocity(); } Vector PlayerVel = pPlayer->GetAbsVelocity(); //Choreo vehicles use player avatar and don't produce their own velocity if(!pPlayer->GetVehicle() || abs(vvel.Length()) == 0 ) { vel = PlayerVel; } else vel = vvel; VectorYawRotate(vel, -90 -eye[YAW], vel ); vel.y = -vel.y; vel.z = -vel.z; switch(pPlayer->GetMoveType()) { case MOVETYPE_NOCLIP: vel *= hap_noclip_avatar_scale.GetFloat(); break; default: break; } haptics->UpdateAvatarVelocity(vel); } #endif #ifndef CLIENT_DLL void HapticsDamage(CBasePlayer* pPlayer, const CTakeDamageInfo &info) { #if !defined(TF_DLL) && !defined(CSTRIKE_DLL) if(!pPlayer->HasHaptics()) return;// do not send to non haptic users. Vector DamageDirection(0,0,0); CBaseEntity *eInflictor = info.GetInflictor(); // Pat: nuero toxix crash fix if(!eInflictor) { return; } // Player Data Vector playerPosition = pPlayer->GetLocalOrigin(); Vector inflictorPosition = eInflictor->GetLocalOrigin(); Vector posWithDir = playerPosition + (playerPosition - inflictorPosition); pPlayer->WorldToEntitySpace(posWithDir, &DamageDirection); QAngle dir(0,0,0); VectorAngles(DamageDirection, dir); float yawAngle = dir[YAW]; float pitchAngle = dir[PITCH]; int bitDamageType = info.GetDamageType(); if(bitDamageType & DMG_FALL) { pitchAngle = ((float)-90.0); // coming from beneath } else if(bitDamageType & DMG_BURN && (bitDamageType & ~DMG_BURN)==0) { // just burn, use the z axis here. pitchAngle = 0.0; } #ifdef TERROR else if( (bitDamageType & ( DMG_PARALYZE | DMG_NERVEGAS | DMG_POISON | DMG_RADIATION | DMG_DROWNRECOVER | DMG_ACID | DMG_SLOWBURN ) ) && (bitDamageType & ~( DMG_PARALYZE | DMG_NERVEGAS | DMG_POISON | DMG_RADIATION | DMG_DROWNRECOVER | DMG_ACID | DMG_SLOWBURN ) )==0 ) { // it is time based. and should not really do a punch. return; } #endif float sendDamage = info.GetDamage(); if(sendDamage>0.0f) { HapticMsg_HapDmg( pPlayer, pitchAngle, -yawAngle, sendDamage, bitDamageType ); } #endif } void HapticPunch(CBasePlayer* pPlayer, float x, float y, float z) { HapticMsg_Punch( pPlayer, x, y, z ); } void HapticMeleeContact(CBasePlayer* pPlayer) { HapticMsg_MeleeContact( pPlayer ); } #endif // NOT CLIENT_DLL void HapticProcessSound(const char* soundname, int entIndex) { #ifdef CLIENT_DLL if (prediction->InPrediction() && prediction->IsFirstTimePredicted()) { bool local = false; C_BaseEntity *ent = C_BaseEntity::Instance( entIndex ); if(ent) local = (entIndex == -1 || ent == C_BasePlayer::GetLocalPlayer() || ent == C_BasePlayer::GetLocalPlayer()->GetActiveWeapon()); haptics->ProcessHapticEvent(2,"Sounds",soundname); } #endif } #ifdef CLIENT_DLL // NVNT add || defined(OTHER_DEFINITION) if your game uses vehicles. #if defined( HL2_CLIENT_DLL ) #define HAPTIC_VEHICLE_DEFAULT "1" #else #define HAPTIC_VEHICLE_DEFAULT "0" #endif // determines weather the vehicles control box option is faded ConVar hap_ui_vehicles( "hap_ui_vehicles", HAPTIC_VEHICLE_DEFAULT, 0 ); #undef HAPTIC_VEHICLE_DEFAULT void HapticsEnteredVehicle(C_BaseEntity* vehicle, C_BaseCombatCharacter *pPassenger ) { if(!vehicle) return; // NVNT notify haptics system of navigation change. C_PropVehicleDriveable* drivable = dynamic_cast<C_PropVehicleDriveable*>(vehicle); bool hasgun = false; if(drivable) hasgun = drivable->HasGun(); if(Q_stristr(vehicle->GetClassname(),"airboat")) { haptics->ProcessHapticEvent(2,"Movement","airboat"); if(hasgun) haptics->SetNavigationClass("vehicle_gun"); else haptics->SetNavigationClass("vehicle_airboat"); } else if(Q_stristr(vehicle->GetClassname(),"jeepepisodic")) { haptics->ProcessHapticEvent(2,"Movement","BaseVehicle"); haptics->SetNavigationClass("vehicle_nogun"); } else if(Q_stristr(vehicle->GetClassname(),"jeep")) { haptics->ProcessHapticEvent(2,"Movement","BaseVehicle"); haptics->SetNavigationClass("vehicle_gun"); } else if(Q_stristr(vehicle->GetClassname(),"choreo")) { haptics->ProcessHapticEvent(2,"Movement","ChoreoVehicle"); haptics->SetNavigationClass("vehicle_gun_nofix");//Give this a bit of aiming } else { haptics->ProcessHapticEvent(2,"Movement","BaseVehicle"); haptics->SetNavigationClass("vehicle_nogun"); } Msg("VehicleType:%s:\n",vehicle->GetClassname()); } void HapticsExitedVehicle(C_BaseEntity* vehicle, C_BaseCombatCharacter *pPassenger ) { // NVNT notify haptics system of navigation change. haptics->SetNavigationClass("on_foot"); haptics->ProcessHapticEvent(2,"Movement","BasePlayer"); } #endif
lgpl-2.1
cureos/accord
Sources/Accord.Statistics/Models/Regression/Nonlinear/GeneralizedLinearRegression.cs
21390
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2016 // cesarsouza at gmail.com // // 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 // namespace Accord.Statistics.Models.Regression { using System; using System.Linq; using Accord.Statistics.Links; using Accord.Statistics.Testing; /// <summary> /// Generalized Linear Model Regression. /// </summary> /// /// <remarks> /// /// <para> /// References: /// <list type="bullet"> /// <item><description> /// Bishop, Christopher M.; Pattern Recognition and Machine Learning. /// Springer; 1st ed. 2006.</description></item> /// <item><description> /// Amos Storkey. (2005). Learning from Data: Learning Logistic Regressors. School of Informatics. /// Available on: http://www.inf.ed.ac.uk/teaching/courses/lfd/lectures/logisticlearn-print.pdf </description></item> /// <item><description> /// Cosma Shalizi. (2009). Logistic Regression and Newton's Method. Available on: /// http://www.stat.cmu.edu/~cshalizi/350/lectures/26/lecture-26.pdf </description></item> /// <item><description> /// Edward F. Conor. Logistic Regression. Website. Available on: /// http://userwww.sfsu.edu/~efc/classes/biol710/logistic/logisticreg.htm </description></item> /// </list></para> /// </remarks> /// /// <example> /// <code> /// // Suppose we have the following data about some patients. /// // The first variable is continuous and represent patient /// // age. The second variable is dichotomic and give whether /// // they smoke or not (This is completely fictional data). /// double[][] input = /// { /// new double[] { 55, 0 }, // 0 - no cancer /// new double[] { 28, 0 }, // 0 /// new double[] { 65, 1 }, // 0 /// new double[] { 46, 0 }, // 1 - have cancer /// new double[] { 86, 1 }, // 1 /// new double[] { 56, 1 }, // 1 /// new double[] { 85, 0 }, // 0 /// new double[] { 33, 0 }, // 0 /// new double[] { 21, 1 }, // 0 /// new double[] { 42, 1 }, // 1 /// }; /// /// // We also know if they have had lung cancer or not, and /// // we would like to know whether smoking has any connection /// // with lung cancer (This is completely fictional data). /// double[] output = /// { /// 0, 0, 0, 1, 1, 1, 0, 0, 0, 1 /// }; /// /// /// // To verify this hypothesis, we are going to create a GLM /// // regression model for those two inputs (age and smoking). /// var regression = new GeneralizedLinearRegression(new ProbitLinkFunction(), inputs: 2); /// /// // Next, we are going to estimate this model. For this, we /// // will use the Iteratively Reweighted Least Squares method. /// var teacher = new IterativeReweightedLeastSquares(regression); /// /// // Now, we will iteratively estimate our model. The Run method returns /// // the maximum relative change in the model parameters and we will use /// // it as the convergence criteria. /// /// double delta = 0; /// do /// { /// // Perform an iteration /// delta = teacher.Run(input, output); /// /// } while (delta > 0.001); /// /// </code> /// </example> /// [Serializable] public class GeneralizedLinearRegression : ICloneable { private ILinkFunction linkFunction; private double[] coefficients; private double[] standardErrors; //--------------------------------------------- #region Constructor /// <summary> /// Creates a new Generalized Linear Regression Model. /// </summary> /// /// <param name="function">The link function to use.</param> /// <param name="inputs">The number of input variables for the model.</param> /// public GeneralizedLinearRegression(ILinkFunction function, int inputs) { this.linkFunction = function; this.coefficients = new double[inputs + 1]; this.standardErrors = new double[inputs + 1]; } /// <summary> /// Creates a new Generalized Linear Regression Model. /// </summary> /// /// <param name="function">The link function to use.</param> /// <param name="inputs">The number of input variables for the model.</param> /// <param name="intercept">The starting intercept value. Default is 0.</param> /// public GeneralizedLinearRegression(ILinkFunction function, int inputs, double intercept) : this(function, inputs) { this.coefficients[0] = intercept; } /// <summary> /// Creates a new Generalized Linear Regression Model. /// </summary> /// /// <param name="function">The link function to use.</param> /// <param name="coefficients">The coefficient vector.</param> /// <param name="standardErrors">The standard error vector.</param> /// public GeneralizedLinearRegression(ILinkFunction function, double[] coefficients, double[] standardErrors) { this.linkFunction = function; this.coefficients = coefficients; this.standardErrors = standardErrors; } #endregion //--------------------------------------------- #region Properties /// <summary> /// Gets the coefficient vector, in which the /// first value is always the intercept value. /// </summary> /// public double[] Coefficients { get { return coefficients; } } /// <summary> /// Gets the standard errors associated with each /// coefficient during the model estimation phase. /// </summary> /// public double[] StandardErrors { get { return standardErrors; } } /// <summary> /// Gets the number of inputs handled by this model. /// </summary> /// public int Inputs { get { return coefficients.Length - 1; } } /// <summary> /// Gets the link function used by /// this generalized linear model. /// </summary> /// public ILinkFunction Link { get { return linkFunction; } } /// <summary> /// Gets or sets the intercept term. This is always the /// first value of the <see cref="Coefficients"/> array. /// </summary> /// public double Intercept { get { return coefficients[0]; } set { coefficients[0] = value; } } #endregion //--------------------------------------------- #region Public Methods /// <summary> /// Computes the model output for the given input vector. /// </summary> /// /// <param name="input">The input vector.</param> /// /// <returns>The output value.</returns> /// public double Compute(double[] input) { double sum = coefficients[0]; for (int i = 1; i < coefficients.Length; i++) sum += input[i - 1] * coefficients[i]; return linkFunction.Inverse(sum); } /// <summary> /// Computes the model output for each of the given input vectors. /// </summary> /// /// <param name="input">The array of input vectors.</param> /// /// <returns>The array of output values.</returns> /// public double[] Compute(double[][] input) { double[] output = new double[input.Length]; for (int i = 0; i < input.Length; i++) output[i] = Compute(input[i]); return output; } /// <summary> /// Gets the Wald Test for a given coefficient. /// </summary> /// /// <remarks> /// The Wald statistical test is a test for a model parameter in which /// the estimated parameter θ is compared with another proposed parameter /// under the assumption that the difference between them will be approximately /// normal. There are several problems with the use of the Wald test. Please /// take a look on substitute tests based on the log-likelihood if possible. /// </remarks> /// /// <param name="index"> /// The coefficient's index. The first value /// (at zero index) is the intercept value. /// </param> /// public WaldTest GetWaldTest(int index) { return new WaldTest(coefficients[index], 0.0, standardErrors[index]); } /// <summary> /// Gets the Log-Likelihood for the model. /// </summary> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// <returns> /// The Log-Likelihood (a measure of performance) of /// the model calculated over the given data sets. /// </returns> /// public double GetLogLikelihood(double[][] input, double[] output) { double sum = 0; for (int i = 0; i < input.Length; i++) { double actualOutput = Compute(input[i]); double expectedOutput = output[i]; if (actualOutput != 0) sum += expectedOutput * Math.Log(actualOutput); if (actualOutput != 1) sum += (1 - expectedOutput) * Math.Log(1 - actualOutput); Accord.Diagnostics.Debug.Assert(!Double.IsNaN(sum)); } return sum; } /// <summary> /// Gets the Log-Likelihood for the model. /// </summary> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// <param name="weights">The weights associated with each input vector.</param> /// /// <returns> /// The Log-Likelihood (a measure of performance) of /// the model calculated over the given data sets. /// </returns> /// public double GetLogLikelihood(double[][] input, double[] output, double[] weights) { double sum = 0; for (int i = 0; i < input.Length; i++) { double w = weights[i]; double actualOutput = Compute(input[i]); double expectedOutput = output[i]; if (actualOutput != 0) sum += expectedOutput * Math.Log(actualOutput) * w; if (actualOutput != 1) sum += (1 - expectedOutput) * Math.Log(1 - actualOutput) * w; Accord.Diagnostics.Debug.Assert(!Double.IsNaN(sum)); } return sum; } /// <summary> /// Gets the Deviance for the model. /// </summary> /// /// <remarks> /// The deviance is defined as -2*Log-Likelihood. /// </remarks> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// <returns> /// The deviance (a measure of performance) of the model /// calculated over the given data sets. /// </returns> /// public double GetDeviance(double[][] input, double[] output) { return -2.0 * GetLogLikelihood(input, output); } /// <summary> /// Gets the Deviance for the model. /// </summary> /// /// <remarks> /// The deviance is defined as -2*Log-Likelihood. /// </remarks> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// <param name="weights">The weights associated with each input vector.</param> /// /// <returns> /// The deviance (a measure of performance) of the model /// calculated over the given data sets. /// </returns> /// public double GetDeviance(double[][] input, double[] output, double[] weights) { return -2.0 * GetLogLikelihood(input, output, weights); } /// <summary> /// Gets the Log-Likelihood Ratio between two models. /// </summary> /// /// <remarks> /// The Log-Likelihood ratio is defined as 2*(LL - LL0). /// </remarks> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// <param name="regression">Another Logistic Regression model.</param> /// /// <returns>The Log-Likelihood ratio (a measure of performance /// between two models) calculated over the given data sets.</returns> /// public double GetLogLikelihoodRatio(double[][] input, double[] output, GeneralizedLinearRegression regression) { return 2.0 * (this.GetLogLikelihood(input, output) - regression.GetLogLikelihood(input, output)); } /// <summary> /// Gets the Log-Likelihood Ratio between two models. /// </summary> /// /// <remarks> /// The Log-Likelihood ratio is defined as 2*(LL - LL0). /// </remarks> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// <param name="weights">The weights associated with each input vector.</param> /// <param name="regression">Another Logistic Regression model.</param> /// /// <returns>The Log-Likelihood ratio (a measure of performance /// between two models) calculated over the given data sets.</returns> /// public double GetLogLikelihoodRatio(double[][] input, double[] output, double[] weights, GeneralizedLinearRegression regression) { return 2.0 * (this.GetLogLikelihood(input, output, weights) - regression.GetLogLikelihood(input, output, weights)); } /// <summary> /// The likelihood ratio test of the overall model, also called the model chi-square test. /// </summary> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// /// <remarks> /// <para> /// The Chi-square test, also called the likelihood ratio test or the log-likelihood test /// is based on the deviance of the model (-2*log-likelihood). The log-likelihood ratio test /// indicates whether there is evidence of the need to move from a simpler model to a more /// complicated one (where the simpler model is nested within the complicated one).</para> /// <para> /// The difference between the log-likelihood ratios for the researcher's model and a /// simpler model is often called the "model chi-square".</para> /// </remarks> /// public ChiSquareTest ChiSquare(double[][] input, double[] output) { double y0 = 0; double y1 = 0; for (int i = 0; i < output.Length; i++) { y0 += 1.0 - output[i]; y1 += output[i]; } var intercept = Math.Log(y1 / y0); var regression = new GeneralizedLinearRegression(linkFunction, Inputs, intercept); double ratio = GetLogLikelihoodRatio(input, output, regression); return new ChiSquareTest(ratio, coefficients.Length - 1); } /// <summary> /// The likelihood ratio test of the overall model, also called the model chi-square test. /// </summary> /// /// <param name="input">A set of input data.</param> /// <param name="output">A set of output data.</param> /// <param name="weights">The weights associated with each input vector.</param> /// /// <remarks> /// <para> /// The Chi-square test, also called the likelihood ratio test or the log-likelihood test /// is based on the deviance of the model (-2*log-likelihood). The log-likelihood ratio test /// indicates whether there is evidence of the need to move from a simpler model to a more /// complicated one (where the simpler model is nested within the complicated one).</para> /// <para> /// The difference between the log-likelihood ratios for the researcher's model and a /// simpler model is often called the "model chi-square".</para> /// </remarks> /// public ChiSquareTest ChiSquare(double[][] input, double[] output, double[] weights) { double y0 = 0; double y1 = 0; for (int i = 0; i < output.Length; i++) { y0 += (1.0 - output[i]) * weights[i]; y1 += output[i] * weights[i]; } var intercept = Math.Log(y1 / y0); var regression = new GeneralizedLinearRegression(linkFunction, Inputs, intercept); double ratio = GetLogLikelihoodRatio(input, output, weights, regression); return new ChiSquareTest(ratio, coefficients.Length - 1); } /// <summary> /// Creates a new GeneralizedLinearRegression that is a copy of the current instance. /// </summary> /// public object Clone() { ILinkFunction function = (ILinkFunction)linkFunction.Clone(); var regression = new GeneralizedLinearRegression(function, coefficients.Length); regression.coefficients = (double[])this.coefficients.Clone(); regression.standardErrors = (double[])this.standardErrors.Clone(); return regression; } /// <summary> /// Creates a GeneralizedLinearRegression from a <see cref="LogisticRegression"/> object. /// </summary> /// /// <param name="regression">A <see cref="LogisticRegression"/> object.</param> /// <param name="makeCopy">True to make a copy of the logistic regression values, false /// to use the actual values. If the actual values are used, changes done on one model /// will be reflected on the other model.</param> /// /// <returns>A new <see cref="GeneralizedLinearRegression"/> which is a copy of the /// given <see cref="LogisticRegression"/>.</returns> /// public static GeneralizedLinearRegression FromLogisticRegression( LogisticRegression regression, bool makeCopy) { if (makeCopy) { double[] coefficients = (double[])regression.Coefficients.Clone(); double[] standardErrors = (double[])regression.StandardErrors.Clone(); return new GeneralizedLinearRegression(new LogitLinkFunction(), coefficients, standardErrors); } else { return new GeneralizedLinearRegression(new LogitLinkFunction(), regression.Coefficients, regression.StandardErrors); } } #endregion } }
lgpl-2.1
geotools/geotools
modules/ogc/net.opengis.wcs/src/net/opengis/gml/util/GmlAdapterFactory.java
19854
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.gml.util; import net.opengis.gml.*; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see net.opengis.gml.GmlPackage * @generated */ public class GmlAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static GmlPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GmlAdapterFactory() { if (modelPackage == null) { modelPackage = GmlPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected GmlSwitch modelSwitch = new GmlSwitch() { @Override public Object caseAbstractGeometricPrimitiveType(AbstractGeometricPrimitiveType object) { return createAbstractGeometricPrimitiveTypeAdapter(); } @Override public Object caseAbstractGeometryBaseType(AbstractGeometryBaseType object) { return createAbstractGeometryBaseTypeAdapter(); } @Override public Object caseAbstractGeometryType(AbstractGeometryType object) { return createAbstractGeometryTypeAdapter(); } @Override public Object caseAbstractGMLType(AbstractGMLType object) { return createAbstractGMLTypeAdapter(); } @Override public Object caseAbstractMetaDataType(AbstractMetaDataType object) { return createAbstractMetaDataTypeAdapter(); } @Override public Object caseAbstractRingPropertyType(AbstractRingPropertyType object) { return createAbstractRingPropertyTypeAdapter(); } @Override public Object caseAbstractRingType(AbstractRingType object) { return createAbstractRingTypeAdapter(); } @Override public Object caseAbstractSurfaceType(AbstractSurfaceType object) { return createAbstractSurfaceTypeAdapter(); } @Override public Object caseBoundingShapeType(BoundingShapeType object) { return createBoundingShapeTypeAdapter(); } @Override public Object caseCodeListType(CodeListType object) { return createCodeListTypeAdapter(); } @Override public Object caseCodeType(CodeType object) { return createCodeTypeAdapter(); } @Override public Object caseDirectPositionType(DirectPositionType object) { return createDirectPositionTypeAdapter(); } @Override public Object caseDocumentRoot(DocumentRoot object) { return createDocumentRootAdapter(); } @Override public Object caseEnvelopeType(EnvelopeType object) { return createEnvelopeTypeAdapter(); } @Override public Object caseEnvelopeWithTimePeriodType(EnvelopeWithTimePeriodType object) { return createEnvelopeWithTimePeriodTypeAdapter(); } @Override public Object caseGridEnvelopeType(GridEnvelopeType object) { return createGridEnvelopeTypeAdapter(); } @Override public Object caseGridLimitsType(GridLimitsType object) { return createGridLimitsTypeAdapter(); } @Override public Object caseGridType(GridType object) { return createGridTypeAdapter(); } @Override public Object caseLinearRingType(LinearRingType object) { return createLinearRingTypeAdapter(); } @Override public Object caseMetaDataPropertyType(MetaDataPropertyType object) { return createMetaDataPropertyTypeAdapter(); } @Override public Object casePointType(PointType object) { return createPointTypeAdapter(); } @Override public Object casePolygonType(PolygonType object) { return createPolygonTypeAdapter(); } @Override public Object caseRectifiedGridType(RectifiedGridType object) { return createRectifiedGridTypeAdapter(); } @Override public Object caseReferenceType(ReferenceType object) { return createReferenceTypeAdapter(); } @Override public Object caseStringOrRefType(StringOrRefType object) { return createStringOrRefTypeAdapter(); } @Override public Object caseTimePositionType(TimePositionType object) { return createTimePositionTypeAdapter(); } @Override public Object caseVectorType(VectorType object) { return createVectorTypeAdapter(); } @Override public Object defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return (Adapter)modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractGeometricPrimitiveType <em>Abstract Geometric Primitive Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractGeometricPrimitiveType * @generated */ public Adapter createAbstractGeometricPrimitiveTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractGeometryBaseType <em>Abstract Geometry Base Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractGeometryBaseType * @generated */ public Adapter createAbstractGeometryBaseTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractGeometryType <em>Abstract Geometry Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractGeometryType * @generated */ public Adapter createAbstractGeometryTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractGMLType <em>Abstract GML Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractGMLType * @generated */ public Adapter createAbstractGMLTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractMetaDataType <em>Abstract Meta Data Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractMetaDataType * @generated */ public Adapter createAbstractMetaDataTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractRingPropertyType <em>Abstract Ring Property Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractRingPropertyType * @generated */ public Adapter createAbstractRingPropertyTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractRingType <em>Abstract Ring Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractRingType * @generated */ public Adapter createAbstractRingTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.AbstractSurfaceType <em>Abstract Surface Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.AbstractSurfaceType * @generated */ public Adapter createAbstractSurfaceTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.BoundingShapeType <em>Bounding Shape Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.BoundingShapeType * @generated */ public Adapter createBoundingShapeTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.CodeListType <em>Code List Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.CodeListType * @generated */ public Adapter createCodeListTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.CodeType <em>Code Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.CodeType * @generated */ public Adapter createCodeTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.DirectPositionType <em>Direct Position Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.DirectPositionType * @generated */ public Adapter createDirectPositionTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.DocumentRoot <em>Document Root</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.DocumentRoot * @generated */ public Adapter createDocumentRootAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.EnvelopeType <em>Envelope Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.EnvelopeType * @generated */ public Adapter createEnvelopeTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.EnvelopeWithTimePeriodType <em>Envelope With Time Period Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.EnvelopeWithTimePeriodType * @generated */ public Adapter createEnvelopeWithTimePeriodTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.GridEnvelopeType <em>Grid Envelope Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.GridEnvelopeType * @generated */ public Adapter createGridEnvelopeTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.GridLimitsType <em>Grid Limits Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.GridLimitsType * @generated */ public Adapter createGridLimitsTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.GridType <em>Grid Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.GridType * @generated */ public Adapter createGridTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.LinearRingType <em>Linear Ring Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.LinearRingType * @generated */ public Adapter createLinearRingTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.MetaDataPropertyType <em>Meta Data Property Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.MetaDataPropertyType * @generated */ public Adapter createMetaDataPropertyTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.PointType <em>Point Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.PointType * @generated */ public Adapter createPointTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.PolygonType <em>Polygon Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.PolygonType * @generated */ public Adapter createPolygonTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.RectifiedGridType <em>Rectified Grid Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.RectifiedGridType * @generated */ public Adapter createRectifiedGridTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.ReferenceType <em>Reference Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.ReferenceType * @generated */ public Adapter createReferenceTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.StringOrRefType <em>String Or Ref Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.StringOrRefType * @generated */ public Adapter createStringOrRefTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.TimePositionType <em>Time Position Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.TimePositionType * @generated */ public Adapter createTimePositionTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link net.opengis.gml.VectorType <em>Vector Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see net.opengis.gml.VectorType * @generated */ public Adapter createVectorTypeAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //GmlAdapterFactory
lgpl-2.1
hohonuuli/vars
vars-annotation/src/main/java/vars/annotation/ui/buttons/UndoButton.java
788
package vars.annotation.ui.buttons; import org.bushe.swing.event.EventBus; import mbarix4j.swing.JFancyButton; import vars.annotation.ui.commandqueue.RedoEvent; import vars.annotation.ui.commandqueue.UndoEvent; import javax.swing.ImageIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * @author Brian Schlining * @since 2011-10-11 */ public class UndoButton extends JFancyButton { public UndoButton() { setIcon(new ImageIcon(getClass().getResource("/images/vars/annotation/24px/undo.png"))); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EventBus.publish(new UndoEvent()); } }); setToolTipText("Undo"); } }
lgpl-2.1
rhusar/jboss-remoting
src/main/java/org/jboss/remoting3/spi/ConnectionProvider.java
3627
/* * JBoss, Home of Professional Open Source * Copyright 2010, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.remoting3.spi; import java.net.SocketAddress; import java.net.URI; import java.util.Collection; import java.util.function.UnaryOperator; import org.jboss.remoting3.HandleableCloseable; import org.wildfly.security.auth.client.AuthenticationConfiguration; import org.xnio.Cancellable; import org.xnio.OptionMap; import org.xnio.Result; import javax.net.ssl.SSLContext; import javax.security.sasl.SaslClientFactory; /** * A connection provider. Used to establish connections with remote systems. There is typically one instance * of this interface per connection provider factory per endpoint. */ public interface ConnectionProvider extends HandleableCloseable<ConnectionProvider> { /** * Open an outbound connection, using the (optionally) given socket addresses as source and destination. * This method is expected to be non-blocking, with the result stored in the result variable possibly asynchronously. * * @param destination the destination URI, or {@code null} if none is given * @param bindAddress the address to bind to, or {@code null} if none is given * @param connectOptions the options to use for this connection * @param result the result which should receive the connection * @param authenticationConfiguration the configuration to use for authentication of the connection * @param sslContext the SSL context to use * @param saslClientFactoryOperator A unary operator to apply to the SaslClientFactory used. * @param serverMechs the list of server mechanism names to advertise to the peer (may be empty; not {@code null}) * @return a handle which may be used to cancel the connect attempt * @throws IllegalArgumentException if any of the given arguments are not valid for this protocol */ Cancellable connect(URI destination, SocketAddress bindAddress, OptionMap connectOptions, Result<ConnectionHandlerFactory> result, AuthenticationConfiguration authenticationConfiguration, SSLContext sslContext, UnaryOperator<SaslClientFactory> saslClientFactoryOperator, final Collection<String> serverMechs); /** * Get the user data associated with this connection provider. This object should implement all of the * provider interfaces which are supported by this provider. Must not return {@code null}. * * @return the user data (not {@code null}) * @see NetworkServerProvider */ Object getProviderInterface(); /** * The object to use when a connection provider has no provider interfaces. */ Object NO_PROVIDER_INTERFACES = new Object(); }
lgpl-2.1
Uli1/mapnik
plugins/input/shape/shape_index_featureset.hpp
2334
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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 * *****************************************************************************/ #ifndef SHAPE_INDEX_FEATURESET_HPP #define SHAPE_INDEX_FEATURESET_HPP // stl #include <set> #include <vector> // mapnik #include <mapnik/geom_util.hpp> #include <mapnik/feature.hpp> #include <mapnik/unicode.hpp> #include <mapnik/value_types.hpp> // boost #include <boost/utility.hpp> #include "shape_datasource.hpp" #include "shape_io.hpp" using mapnik::Featureset; using mapnik::box2d; using mapnik::feature_ptr; using mapnik::context_ptr; template <typename filterT> class shape_index_featureset : public Featureset { public: shape_index_featureset(filterT const& filter, std::unique_ptr<shape_io> && shape_ptr, std::set<std::string> const& attribute_names, std::string const& encoding, std::string const& shape_name, int row_limit); virtual ~shape_index_featureset(); feature_ptr next(); private: filterT filter_; context_ptr ctx_; std::unique_ptr<shape_io> shape_ptr_; const std::unique_ptr<mapnik::transcoder> tr_; std::vector<int> offsets_; std::vector<int>::iterator itr_; std::vector<int> attr_ids_; mapnik::value_integer row_limit_; mutable int count_; mutable box2d<double> feature_bbox_; }; #endif // SHAPE_INDEX_FEATURESET_HPP
lgpl-2.1
stulp/dmpbbo
src/functionapproximators/ModelParametersRRRFF.cpp
5888
/** * @file ModelParametersRRRFF.cpp * @brief ModelParametersRRRFF class source file. * @author Freek Stulp, Thibaut Munzer * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo 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. * * DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #include "functionapproximators/ModelParametersRRRFF.hpp" #include "functionapproximators/BasisFunction.hpp" #include "functionapproximators/UnifiedModel.hpp" #include "dmpbbo_io/BoostSerializationToString.hpp" #include <iostream> using namespace Eigen; using namespace std; namespace DmpBbo { ModelParametersRRRFF::ModelParametersRRRFF(Eigen::VectorXd weights, Eigen::MatrixXd cosines_periodes, Eigen::VectorXd cosines_phase) : weights_(weights), cosines_periodes_(cosines_periodes), cosines_phase_(cosines_phase) { assert(cosines_phase.size() == cosines_periodes.rows()); assert(weights.rows() == cosines_periodes.rows()); nb_in_dim_ = cosines_periodes.cols(); // int nb_output_dim = weights.cols(); all_values_vector_size_ = 0; all_values_vector_size_ += weights_.rows() * weights_.cols(); all_values_vector_size_ += cosines_phase_.size(); all_values_vector_size_ += cosines_periodes_.rows() * cosines_periodes_.cols(); }; ModelParameters* ModelParametersRRRFF::clone(void) const { return new ModelParametersRRRFF(weights_, cosines_periodes_, cosines_phase_); } void ModelParametersRRRFF::cosineActivations(const Eigen::Ref<const Eigen::MatrixXd>& inputs, Eigen::MatrixXd& cosine_activations) const { if (caching_) { // If the cached inputs matrix has the same size as the one now requested // (this also takes care of the case when inputs_cached is empty and need to be initialized) if ( inputs.rows()==inputs_cached_.rows() && inputs.cols()==inputs_cached_.cols() ) { // And they have the same values if ( (inputs.array()==inputs_cached_.array()).all() ) { // Then you can return the cached values cosine_activations = cosine_activations_cached_; return; } } } BasisFunction::Cosine::activations(cosines_periodes_,cosines_phase_,inputs,cosine_activations); if (caching_) { // Cache the current results now. inputs_cached_ = inputs; cosine_activations_cached_ = cosine_activations; } } int ModelParametersRRRFF::getExpectedInputDim(void) const { return nb_in_dim_; }; string ModelParametersRRRFF::toString(void) const { RETURN_STRING_FROM_BOOST_SERIALIZATION_XML("ModelParametersRRRFF"); }; void ModelParametersRRRFF::getSelectableParameters(set<string>& selected_values_labels) const { selected_values_labels = set<string>(); selected_values_labels.insert("weights"); selected_values_labels.insert("phases"); selected_values_labels.insert("periods"); } void ModelParametersRRRFF::getParameterVectorMask(const std::set<std::string> selected_values_labels, VectorXi& selected_mask) const { selected_mask.resize(getParameterVectorAllSize()); selected_mask.fill(0); int offset = 0; int size; size = weights_.rows() * weights_.cols(); if (selected_values_labels.find("weights")!=selected_values_labels.end()) selected_mask.segment(offset,size).fill(1); offset += size; size = cosines_phase_.size(); if (selected_values_labels.find("phases")!=selected_values_labels.end()) selected_mask.segment(offset,size).fill(2); offset += size; size = cosines_periodes_.rows() * cosines_periodes_.cols(); if (selected_values_labels.find("periods")!=selected_values_labels.end()) selected_mask.segment(offset,size).fill(3); offset += size; assert(offset == getParameterVectorAllSize()); } void ModelParametersRRRFF::getParameterVectorAll(VectorXd& values) const { values.resize(getParameterVectorAllSize()); int offset = 0; for (int c = 0; c < weights_.cols(); c++) { values.segment(offset, weights_.rows()) = weights_.col(c); offset += weights_.rows(); } values.segment(offset, cosines_phase_.size()) = cosines_phase_; offset += cosines_phase_.size(); for (int c = 0; c < cosines_periodes_.cols(); c++) { values.segment(offset, cosines_periodes_.rows()) = cosines_periodes_.col(c); offset += cosines_periodes_.rows(); } assert(offset == getParameterVectorAllSize()); }; void ModelParametersRRRFF::setParameterVectorAll(const VectorXd& values) { if (all_values_vector_size_ != values.size()) { cerr << __FILE__ << ":" << __LINE__ << ": values is of wrong size." << endl; return; } int offset = 0; for (int c = 0; c < weights_.cols(); c++) { weights_.col(c) = values.segment(offset, weights_.rows()); offset += weights_.rows(); } cosines_phase_ = values.segment(offset, cosines_phase_.size()); offset += cosines_phase_.size(); for (int c = 0; c < cosines_periodes_.cols(); c++) { cosines_periodes_.col(c) = values.segment(offset, cosines_periodes_.rows()); offset += cosines_periodes_.rows(); } assert(offset == getParameterVectorAllSize()); }; UnifiedModel* ModelParametersRRRFF::toUnifiedModel(void) const { return new UnifiedModel(cosines_periodes_, cosines_phase_, weights_); } }
lgpl-2.1
cdmdotnet/CQRS
wiki/docs/4.2/html/search/variables_4.js
562
var searchData= [ ['eventsprocessedstreamname_2784',['EventsProcessedStreamName',['../classCqrs_1_1EventStore_1_1Bus_1_1EventStoreBasedLastEventProcessedStore_aa3125d75a64df58026e0fd785f99bfff.html#aa3125d75a64df58026e0fd785f99bfff',1,'Cqrs::EventStore::Bus::EventStoreBasedLastEventProcessedStore']]], ['eventtype_2785',['EventType',['../classCqrs_1_1EventStore_1_1Bus_1_1EventStoreBasedLastEventProcessedStore_a63b4ae4f14e782d605aff1bd214db3f1.html#a63b4ae4f14e782d605aff1bd214db3f1',1,'Cqrs::EventStore::Bus::EventStoreBasedLastEventProcessedStore']]] ];
lgpl-2.1
kobolabs/qt-everywhere-4.8.0
src/gui/text/qfont_x11.cpp
9553
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #define QT_FATAL_ASSERT #include "qplatformdefs.h" #include "qfont.h" #include "qapplication.h" #include "qfontinfo.h" #include "qfontdatabase.h" #include "qfontmetrics.h" #include "qpaintdevice.h" #include "qtextcodec.h" #include "qiodevice.h" #include "qhash.h" #include <private/qunicodetables_p.h> #include "qfont_p.h" #include "qfontengine_p.h" #include "qfontengine_x11_p.h" #include "qtextengine_p.h" #include <private/qt_x11_p.h> #include "qx11info_x11.h" #include <time.h> #include <stdlib.h> #include <ctype.h> #define QFONTLOADER_DEBUG #define QFONTLOADER_DEBUG_VERBOSE QT_BEGIN_NAMESPACE double qt_pixelSize(double pointSize, int dpi) { if (pointSize < 0) return -1.; if (dpi == 75) // the stupid 75 dpi setting on X11 dpi = 72; return (pointSize * dpi) /72.; } double qt_pointSize(double pixelSize, int dpi) { if (pixelSize < 0) return -1.; if (dpi == 75) // the stupid 75 dpi setting on X11 dpi = 72; return pixelSize * 72. / ((double) dpi); } /* Removes wildcards from an XLFD. Returns \a xlfd with all wildcards removed if a match for \a xlfd is found, otherwise it returns \a xlfd. */ static QByteArray qt_fixXLFD(const QByteArray &xlfd) { QByteArray ret = xlfd; int count = 0; char **fontNames = XListFonts(QX11Info::display(), xlfd, 32768, &count); if (count > 0) ret = fontNames[0]; XFreeFontNames(fontNames); return ret ; } typedef QHash<int, QString> FallBackHash; Q_GLOBAL_STATIC(FallBackHash, fallBackHash) // Returns the user-configured fallback family for the specified script. QString qt_fallback_font_family(int script) { FallBackHash *hash = fallBackHash(); return hash->value(script); } // Sets the fallback family for the specified script. Q_GUI_EXPORT void qt_x11_set_fallback_font_family(int script, const QString &family) { FallBackHash *hash = fallBackHash(); if (!family.isEmpty()) hash->insert(script, family); else hash->remove(script); } int QFontPrivate::defaultEncodingID = -1; void QFont::initialize() { extern int qt_encoding_id_for_mib(int mib); // from qfontdatabase_x11.cpp QTextCodec *codec = QTextCodec::codecForLocale(); // determine the default encoding id using the locale, otherwise // fallback to latin1 (mib == 4) int mib = codec ? codec->mibEnum() : 4; // for asian locales, use the mib for the font codec instead of the locale codec switch (mib) { case 38: // eucKR mib = 36; break; case 2025: // GB2312 mib = 57; break; case 113: // GBK mib = -113; break; case 114: // GB18030 mib = -114; break; case 2026: // Big5 mib = -2026; break; case 2101: // Big5-HKSCS mib = -2101; break; case 16: // JIS7 mib = 15; break; case 17: // SJIS case 18: // eucJP mib = 63; break; } // get the default encoding id for the locale encoding... QFontPrivate::defaultEncodingID = qt_encoding_id_for_mib(mib); } void QFont::cleanup() { QFontCache::cleanup(); } /*! \internal X11 Only: Returns the screen with which this font is associated. */ int QFont::x11Screen() const { return d->screen; } /*! \internal X11 Only: Associate the font with the specified \a screen. */ void QFont::x11SetScreen(int screen) { if (screen < 0) // assume default screen = QX11Info::appScreen(); if (screen == d->screen) return; // nothing to do detach(); d->screen = screen; } Qt::HANDLE QFont::handle() const { QFontEngine *engine = d->engineForScript(QUnicodeTables::Common); Q_ASSERT(engine != 0); if (engine->type() == QFontEngine::Multi) engine = static_cast<QFontEngineMulti *>(engine)->engine(0); if (engine->type() == QFontEngine::XLFD) return static_cast<QFontEngineXLFD *>(engine)->fontStruct()->fid; return 0; } FT_Face QFont::freetypeFace() const { #ifndef QT_NO_FREETYPE QFontEngine *engine = d->engineForScript(QUnicodeTables::Common); if (engine->type() == QFontEngine::Multi) engine = static_cast<QFontEngineMulti *>(engine)->engine(0); #ifndef QT_NO_FONTCONFIG if (engine->type() == QFontEngine::Freetype) { const QFontEngineFT *ft = static_cast<const QFontEngineFT *>(engine); return ft->non_locked_face(); } else #endif if (engine->type() == QFontEngine::XLFD) { const QFontEngineXLFD *xlfd = static_cast<const QFontEngineXLFD *>(engine); return xlfd->non_locked_face(); } #endif return 0; } QString QFont::rawName() const { QFontEngine *engine = d->engineForScript(QUnicodeTables::Common); Q_ASSERT(engine != 0); if (engine->type() == QFontEngine::Multi) engine = static_cast<QFontEngineMulti *>(engine)->engine(0); if (engine->type() == QFontEngine::XLFD) return QString::fromLatin1(engine->name()); return QString(); } struct QtFontDesc; void QFont::setRawName(const QString &name) { detach(); // from qfontdatabase_x11.cpp extern bool qt_fillFontDef(const QByteArray &xlfd, QFontDef *fd, int dpi, QtFontDesc *desc); if (!qt_fillFontDef(qt_fixXLFD(name.toLatin1()), &d->request, d->dpi, 0)) { qWarning("QFont::setRawName: Invalid XLFD: \"%s\"", name.toLatin1().constData()); setFamily(name); setRawMode(true); } else { resolve_mask = QFont::AllPropertiesResolved; } } QString QFont::lastResortFamily() const { return QString::fromLatin1("Helvetica"); } QString QFont::defaultFamily() const { switch (d->request.styleHint) { case QFont::Times: return QString::fromLatin1("Times"); case QFont::Courier: return QString::fromLatin1("Courier"); case QFont::Monospace: return QString::fromLatin1("Courier New"); case QFont::Cursive: return QString::fromLatin1("Comic Sans MS"); case QFont::Fantasy: return QString::fromLatin1("Impact"); case QFont::Decorative: return QString::fromLatin1("Old English"); case QFont::Helvetica: case QFont::System: default: return QString::fromLatin1("Helvetica"); } } /* Returns a last resort raw font name for the font matching algorithm. This is used if even the last resort family is not available. It returns \e something, almost no matter what. The current implementation tries a wide variety of common fonts, returning the first one it finds. The implementation may change at any time. */ static const char * const tryFonts[] = { "-*-helvetica-medium-r-*-*-*-120-*-*-*-*-*-*", "-*-courier-medium-r-*-*-*-120-*-*-*-*-*-*", "-*-times-medium-r-*-*-*-120-*-*-*-*-*-*", "-*-lucida-medium-r-*-*-*-120-*-*-*-*-*-*", "-*-helvetica-*-*-*-*-*-120-*-*-*-*-*-*", "-*-courier-*-*-*-*-*-120-*-*-*-*-*-*", "-*-times-*-*-*-*-*-120-*-*-*-*-*-*", "-*-lucida-*-*-*-*-*-120-*-*-*-*-*-*", "-*-helvetica-*-*-*-*-*-*-*-*-*-*-*-*", "-*-courier-*-*-*-*-*-*-*-*-*-*-*-*", "-*-times-*-*-*-*-*-*-*-*-*-*-*-*", "-*-lucida-*-*-*-*-*-*-*-*-*-*-*-*", "-*-fixed-*-*-*-*-*-*-*-*-*-*-*-*", "6x13", "7x13", "8x13", "9x15", "fixed", 0 }; // Returns true if the font exists, false otherwise static bool fontExists(const QString &fontName) { int count; char **fontNames = XListFonts(QX11Info::display(), (char*)fontName.toLatin1().constData(), 32768, &count); if (fontNames) XFreeFontNames(fontNames); return count != 0; } QString QFont::lastResortFont() const { static QString last; // already found if (! last.isNull()) return last; int i = 0; const char* f; while ((f = tryFonts[i])) { last = QString::fromLatin1(f); if (fontExists(last)) return last; i++; } #if defined(CHECK_NULL) qFatal("QFontPrivate::lastResortFont: Cannot find any reasonable font"); #endif return last; } QT_END_NAMESPACE
lgpl-2.1
faint32/ZedGraph
demo/ZedGraph.Demo/PercentStkBarDemo.cs
4100
//============================================================================ //ZedGraph Class Library - A Flexible Charting Library for .Net //Copyright (C) 2005 John Champion, Jerry Vos and Bob Kaye // //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 //============================================================================= using System; using System.Drawing; using System.Collections; using ZedGraph; namespace ZedGraph.Demo { /// <summary> /// Summary description for SimpleDemo. /// </summary> public class PercentStkBarDemo : DemoBase { public PercentStkBarDemo() : base( " A Stack Bar Chart where a bar's height represents " + "its percentage of the total of all bar values.", "Percent Stack Bar Chart", DemoType.Bar ) { GraphPane myPane = base.GraphPane; // Make up some data points string [] quarters = {"Q1-'04", "Q2-'04", "Q3-'04", "Q4-'04" } ; double[] y4 = { 20, 15, 90, 70 }; double[] y3 = { 0, 35, 40,10 }; double[] y2 = { 60, 70, 20,30 }; double[] y5 = new double [4] ; // Set the pane title myPane.Title.Text = "% Product Sales by Quarter by Type"; // Position the legend and fill the background myPane.Legend.Position = LegendPos.TopCenter ; myPane.Legend.Fill.Color = Color.LightCyan ; // Fill the pane background with a solid color myPane.Fill.Color = Color.Cornsilk ; // Fill the axis background with a solid color myPane.Chart.Fill.Type = FillType.Solid ; myPane.Chart.Fill.Color = Color.LightCyan ; // Set the bar type to percent stack, which makes the bars sum up to 100% myPane.BarSettings.Type = BarType.PercentStack ; // Set the X axis title myPane.XAxis.Title.Text = "Quarter"; myPane.XAxis.Type = AxisType.Text ; myPane.XAxis.Scale.TextLabels = quarters ; // Set the Y2 axis properties myPane.Y2Axis.Title.Text = "2004 Total Sales ($M)" ; myPane.Y2Axis.IsVisible = true; myPane.Y2Axis.MinorTic.IsOpposite = false; myPane.Y2Axis.MajorTic.IsOpposite = false; myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Red ; // Set the Y axis properties myPane.YAxis.Title.Text = "" ; myPane.YAxis.Scale.Max = 120 ; myPane.YAxis.MinorTic.IsOpposite = false; myPane.YAxis.MajorTic.IsOpposite = false; // get total values into array for Line for ( int x = 0 ; x < 4 ; x++ ) y5[x] = y4[x] + y3[x] + y2[x] ; // Add a curve to the graph LineItem curve; curve = myPane.AddCurve( "Total Sales", null, y5, Color.Black, SymbolType.Circle ); // Associate the curve with the Y2 axis curve.IsY2Axis = true ; curve.Line.Width = 1.5F; // Make the symbols solid red curve.Line.Color = Color.Red ; curve.Symbol.Fill = new Fill( Color.Red ); myPane.Y2Axis.Title.FontSpec.FontColor = Color.Red ; curve.Symbol.Size = 8; // Add a gradient blue bar BarItem bar = myPane.AddBar( "Components", null, y4, Color.RoyalBlue ); bar.Bar.Fill = new Fill( Color.RoyalBlue, Color.White, Color.RoyalBlue ); // Add a gradient green bar bar = myPane.AddBar( "Misc", null, y3, Color.LimeGreen ); bar.Bar.Fill = new Fill( Color.LimeGreen, Color.White, Color.LimeGreen ); // Add a gradient yellow bar bar = myPane.AddBar( "Assemblies",null, y2, Color.Yellow ); bar.Bar.Fill = new Fill( Color.Yellow, Color.White, Color.Yellow ); base.ZedGraphControl.AxisChange(); } } }
lgpl-2.1
chemila/doctrine
tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php
12532
<?php namespace Doctrine\Tests\ORM\Mapping; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Events; require_once __DIR__ . '/../../TestInit.php'; class ClassMetadataTest extends \Doctrine\Tests\OrmTestCase { public function testClassMetadataInstanceSerialization() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); // Test initial state $this->assertTrue(count($cm->getReflectionProperties()) == 0); $this->assertTrue($cm->reflClass instanceof \ReflectionClass); $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name); $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->rootEntityName); $this->assertEquals(array(), $cm->subClasses); $this->assertEquals(array(), $cm->parentClasses); $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm->inheritanceType); // Customize state $cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE); $cm->setSubclasses(array("One", "Two", "Three")); $cm->setParentClasses(array("UserParent")); $cm->setCustomRepositoryClass("UserRepository"); $cm->setDiscriminatorColumn(array('name' => 'disc', 'type' => 'integer')); $cm->mapOneToOne(array('fieldName' => 'phonenumbers', 'targetEntity' => 'Bar', 'mappedBy' => 'foo')); $this->assertEquals(1, count($cm->associationMappings)); $serialized = serialize($cm); $cm = unserialize($serialized); // Check state $this->assertTrue(count($cm->getReflectionProperties()) > 0); $this->assertEquals('Doctrine\Tests\Models\CMS', $cm->namespace); $this->assertTrue($cm->reflClass instanceof \ReflectionClass); $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name); $this->assertEquals('UserParent', $cm->rootEntityName); $this->assertEquals(array('Doctrine\Tests\Models\CMS\One', 'Doctrine\Tests\Models\CMS\Two', 'Doctrine\Tests\Models\CMS\Three'), $cm->subClasses); $this->assertEquals(array('UserParent'), $cm->parentClasses); $this->assertEquals('UserRepository', $cm->customRepositoryClassName); $this->assertEquals(array('name' => 'disc', 'type' => 'integer', 'fieldName' => 'disc'), $cm->discriminatorColumn); $this->assertTrue($cm->associationMappings['phonenumbers']['type'] == ClassMetadata::ONE_TO_ONE); $this->assertEquals(1, count($cm->associationMappings)); $oneOneMapping = $cm->getAssociationMapping('phonenumbers'); $this->assertTrue($oneOneMapping['fetch'] == ClassMetadata::FETCH_LAZY); $this->assertEquals('phonenumbers', $oneOneMapping['fieldName']); $this->assertEquals('Doctrine\Tests\Models\CMS\Bar', $oneOneMapping['targetEntity']); } public function testFieldIsNullable() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); // Explicit Nullable $cm->mapField(array('fieldName' => 'status', 'nullable' => true, 'type' => 'string', 'length' => 50)); $this->assertTrue($cm->isNullable('status')); // Explicit Not Nullable $cm->mapField(array('fieldName' => 'username', 'nullable' => false, 'type' => 'string', 'length' => 50)); $this->assertFalse($cm->isNullable('username')); // Implicit Not Nullable $cm->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 50)); $this->assertFalse($cm->isNullable('name'), "By default a field should not be nullable."); } /** * @group DDC-115 */ public function testMapAssocationInGlobalNamespace() { require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; $cm = new ClassMetadata('DoctrineGlobal_Article'); $cm->mapManyToMany(array( 'fieldName' => 'author', 'targetEntity' => 'DoctrineGlobal_User', 'joinTable' => array( 'name' => 'bar', 'joinColumns' => array(array('name' => 'bar_id', 'referencedColumnName' => 'id')), 'inverseJoinColumns' => array(array('name' => 'baz_id', 'referencedColumnName' => 'id')), ), )); $this->assertEquals("DoctrineGlobal_User", $cm->associationMappings['author']['targetEntity']); } public function testMapManyToManyJoinTableDefaults() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->mapManyToMany( array( 'fieldName' => 'groups', 'targetEntity' => 'CmsGroup' )); $assoc = $cm->associationMappings['groups']; //$this->assertTrue($assoc instanceof \Doctrine\ORM\Mapping\ManyToManyMapping); $this->assertEquals(array( 'name' => 'cmsuser_cmsgroup', 'joinColumns' => array(array('name' => 'cmsuser_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE')), 'inverseJoinColumns' => array(array('name' => 'cmsgroup_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE')) ), $assoc['joinTable']); $this->assertTrue($assoc['isOnDeleteCascade']); } public function testSerializeManyToManyJoinTableCascade() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->mapManyToMany( array( 'fieldName' => 'groups', 'targetEntity' => 'CmsGroup' )); /* @var $assoc \Doctrine\ORM\Mapping\ManyToManyMapping */ $assoc = $cm->associationMappings['groups']; $assoc = unserialize(serialize($assoc)); $this->assertTrue($assoc['isOnDeleteCascade']); } /** * @group DDC-115 */ public function testSetDiscriminatorMapInGlobalNamespace() { require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; $cm = new ClassMetadata('DoctrineGlobal_User'); $cm->setDiscriminatorMap(array('descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User')); $this->assertEquals("DoctrineGlobal_Article", $cm->discriminatorMap['descr']); $this->assertEquals("DoctrineGlobal_User", $cm->discriminatorMap['foo']); } /** * @group DDC-115 */ public function testSetSubClassesInGlobalNamespace() { require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; $cm = new ClassMetadata('DoctrineGlobal_User'); $cm->setSubclasses(array('DoctrineGlobal_Article')); $this->assertEquals("DoctrineGlobal_Article", $cm->subClasses[0]); } /** * @group DDC-268 */ public function testSetInvalidVersionMapping_ThrowsException() { $field = array(); $field['fieldName'] = 'foo'; $field['type'] = 'string'; $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->setVersionMapping($field); } public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->isIdentifierComposite = true; $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->getSingleIdentifierFieldName(); } public function testDuplicateAssociationMappingException() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $a1 = array('fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo'); $a2 = array('fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo'); $cm->addInheritedAssociationMapping($a1); $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->addInheritedAssociationMapping($a2); } public function testDuplicateColumnName_ThrowsMappingException() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->mapField(array('fieldName' => 'username', 'columnName' => 'name')); } public function testDuplicateColumnName_DiscriminatorColumn_ThrowsMappingException() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->setDiscriminatorColumn(array('name' => 'name')); } public function testDuplicateColumnName_DiscriminatorColumn2_ThrowsMappingException() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->setDiscriminatorColumn(array('name' => 'name')); $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); } public function testDuplicateFieldAndAssocationMapping1_ThrowsException() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->mapOneToOne(array('fieldName' => 'name', 'targetEntity' => 'CmsUser')); } public function testDuplicateFieldAndAssocationMapping2_ThrowsException() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->mapOneToOne(array('fieldName' => 'name', 'targetEntity' => 'CmsUser')); $this->setExpectedException('Doctrine\ORM\Mapping\MappingException'); $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); } public function testDefaultTableName() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); // When table's name is not given $primaryTable = array(); $cm->setPrimaryTable($primaryTable); $this->assertEquals('CmsUser', $cm->getTableName()); $this->assertEquals('CmsUser', $cm->table['name']); $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); // When joinTable's name is not given $cm->mapManyToMany(array( 'fieldName' => 'user', 'targetEntity' => 'CmsUser', 'inversedBy' => 'users', 'joinTable' => array('joinColumns' => array(array('referencedColumnName' => 'id')), 'inverseJoinColumns' => array(array('referencedColumnName' => 'id'))))); $this->assertEquals('cmsaddress_cmsuser', $cm->associationMappings['user']['joinTable']['name']); } public function testDefaultJoinColumnName() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); // this is really dirty, but it's the simpliest way to test whether // joinColumn's name will be automatically set to user_id $cm->mapOneToOne(array( 'fieldName' => 'user', 'targetEntity' => 'CmsUser', 'joinColumns' => array(array('referencedColumnName' => 'id')))); $this->assertEquals('user_id', $cm->associationMappings['user']['joinColumns'][0]['name']); $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); $cm->mapManyToMany(array( 'fieldName' => 'user', 'targetEntity' => 'CmsUser', 'inversedBy' => 'users', 'joinTable' => array('name' => 'user_CmsUser', 'joinColumns' => array(array('referencedColumnName' => 'id')), 'inverseJoinColumns' => array(array('referencedColumnName' => 'id'))))); $this->assertEquals('cmsaddress_id', $cm->associationMappings['user']['joinTable']['joinColumns'][0]['name']); $this->assertEquals('cmsuser_id', $cm->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']); } /** * @group DDC-886 */ public function testSetMultipleIdentifierSetsComposite() { $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); $cm->mapField(array('fieldName' => 'name')); $cm->mapField(array('fieldName' => 'username')); $cm->setIdentifier(array('name', 'username')); $this->assertTrue($cm->isIdentifierComposite); } }
lgpl-2.1
xpressengine/xe-module-live
lang/en.lang.php
1803
<?php /** * @file ko.lang.php * @author NHN (developers@xpressengine.com) * @brief 게시판(livxe) 모듈의 기본 언어팩 **/ $lang->livexe = 'liveXE'; $lang->rss_url = 'RSS 주소'; $lang->tag_pop = '인기 태그'; $lang->feed_item = '피드 목록'; // 버튼에 사용되는 언어 $lang->cmd_module_config = '공통 설정'; $lang->cmd_view_info = '정보'; $lang->new_rss_list = '최신 RSS'; $lang->my_rss_list = '내 RSS'; $lang->popular_tag_period = '태그 출력 기간'; $lang->about_popular_tag_period = '인기태그를 출력할때 최근 며칠내의 태그들을 대상으로 할지 결정할 수 있습니다. (단위 일, 기본 30일)'; // 주절 주절.. $lang->about_livexe = '회원들이 RSS를 등록하고 등록된 RSS를 수집/ 서비스하는 메타 사이트를 구축할 수 있는 모듈입니다'; $lang->about_insert_rss = '원하는 RSS주소를 등록할 수 있습니다.<br/>꼭 제목, RSS주소, 홈페이지 주소를 입력해주세요 (RSS2.0/ATOM 포맷 지원)'; $lang->about_livexe_web_crawler = '이 페이지는 liveXE에 등록된 RSS 주소들을 웹에서 수집하도록 합니다.<br />아래 refresh 주기를 지정하시고 웹브라우저를 계속 켜 놓으시면 각 RSS의 발행주기에 맞게 수집합니다. (단위: 시간)'; $lang->rss_url_already_registed = '이미 등록된 RSS Url입니다'; $lang->about_reg_livexe = '권한이 없어서 RSS 등록을 할 수 없습니다'; $lang->cmd_start_crawl = '등록된 RSS 글 수집'; $lang->cmd_cancel_search = '사이트 검색 취소'; $lang->msg_not_supported_rss = 'RSS 2.0, Atom Feed만 지원을 하고 있습니다.'; ?>
lgpl-2.1
LibreOffice/noa-libre
src/ag/ion/noa/script/IScriptingService.java
3300
/**************************************************************************** * * * NOA (Nice Office Access) * * ------------------------------------------------------------------------ * * * * The Contents of this file are made available subject to * * the terms of GNU Lesser General Public License Version 2.1. * * * * GNU Lesser General Public License Version 2.1 * * ======================================================================== * * Copyright 2003-2006 by IOn AG * * * * 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. * * * * 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 * * * * Contact us: * * http://www.ion.ag * * http://ubion.ion.ag * * info@ion.ag * * * ****************************************************************************/ /* * Last changes made by $Author: andreas $, $Date: 2006-10-04 14:14:28 +0200 (Mi, 04 Okt 2006) $ */ package ag.ion.noa.script; import ag.ion.noa.NOAException; /** * Service of the office scripting framework. * * @author Andreas Bröker * @version $Revision: 10398 $ * @date 13.06.2006 */ public interface IScriptingService { //---------------------------------------------------------------------------- /** * Returns script provider. * * @return script provider * * @throws NOAException if the script provider can not be provided * * @author Andreas Bröker * @date 13.06.2006 */ public IScriptProvider getScriptProvider() throws NOAException; //---------------------------------------------------------------------------- }
lgpl-2.1
volfste2/tuxguitar
TuxGuitar/src/org/herac/tuxguitar/app/editors/TGPainterUtils.java
474
package org.herac.tuxguitar.app.editors; import org.herac.tuxguitar.app.TuxGuitar; import org.herac.tuxguitar.app.system.config.TGConfigKeys; public class TGPainterUtils { /** On swt-carbon (and maybe another platform) advanced mode must be allways true **/ public static final boolean FORCE_OS_DEFAULTS = getValue(TGConfigKeys.FORCE_OS_DEFAULTS); private static boolean getValue(String key){ return TuxGuitar.getInstance().getConfig().getBooleanValue(key); } }
lgpl-2.1
aeslaughter/libmesh
doc/statistics/libmesh_citations.py
2369
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np # Number of "papers using libmesh" by year. # # Note 1: this does not count citations "only," the authors must have actually # used libmesh in part of their work. Therefore, these counts do not include # things like Wolfgang citing us in his papers to show how Deal.II is # superior... # # Note 2: I typically update this data after regenerating the web page, # since bibtex2html renumbers the references starting from "1" each year. # # Note 3: These citations include anything that is not a dissertation/thesis. # So, some are conference papers, some are journal articles, etc. # # Note 4: The libmesh paper came out in 2006, but there are some citations # prior to that date, obviously. These counts include citations of the # website libmesh.sf.net as well... # # Note 5: Preprints are listed as the "current year + 1" and are constantly # being moved to their respective years after being published. data = [ '2004', 5, '\'05', 2, '\'06', 13, '\'07', 8, '\'08', 24, '\'09', 30, '\'10', 24, '\'11', 37, '\'12', 50, '\'13', 80, '\'14', 63, '\'15', 73, '\'16', 49, 'P', 12, # Preprints 'T', 51 # Theses ] # Extract the x-axis labels from the data array xlabels = data[0::2] # Extract the publication counts from the data array n_papers = data[1::2] # The number of data points N = len(xlabels); # Get a reference to the figure fig = plt.figure() # 111 is equivalent to Matlab's subplot(1,1,1) command ax = fig.add_subplot(111) # Create an x-axis for plotting x = np.linspace(1, N, N) # Width of the bars width = 0.8 # Make the bar chart. Plot years in blue, preprints and theses in green. ax.bar(x[0:N-2], n_papers[0:N-2], width, color='b') ax.bar(x[N-2:N], n_papers[N-2:N], width, color='g') # Label the x-axis plt.xlabel('P=Preprints, T=Theses') # Set up the xtick locations and labels. Note that you have to offset # the position of the ticks by width/2, where width is the width of # the bars. ax.set_xticks(np.linspace(1,N,N) + width/2) ax.set_xticklabels(xlabels) # Create a title string title_string = 'Papers by People Using LibMesh, (' + str(sum(n_papers)) + ' Total)' fig.suptitle(title_string) # Save as PDF plt.savefig('libmesh_citations.pdf') # Local Variables: # python-indent: 2 # End:
lgpl-2.1
threerings/nenya
core/src/main/java/com/threerings/resource/FileResourceBundle.java
13361
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2012 Three Rings Design, Inc., All Rights Reserved // https://github.com/threerings/nenya // // 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.threerings.resource; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.awt.image.BufferedImage; import com.samskivert.io.StreamUtil; import com.samskivert.util.FileUtil; import com.samskivert.util.StringUtil; import static com.threerings.resource.Log.log; /** * A resource bundle provides access to the resources in a jar file. */ public class FileResourceBundle extends ResourceBundle { /** * Constructs a resource bundle with the supplied jar file. * * @param source a file object that references our source jar file. */ public FileResourceBundle (File source) { this(source, false, false); } /** * Constructs a resource bundle with the supplied jar file. * * @param source a file object that references our source jar file. * @param delay if true, the bundle will wait until someone calls {@link #sourceIsReady} * before allowing access to its resources. * @param unpack if true the bundle will unpack itself into a temporary directory */ public FileResourceBundle (File source, boolean delay, boolean unpack) { _source = source; if (unpack) { String root = stripSuffix(source.getPath()); _unpacked = new File(root + ".stamp"); _cache = new File(root); } if (!delay) { sourceIsReady(); } } @Override public String getIdent () { return _source.getPath(); } @Override public InputStream getResource (String path) throws IOException { // unpack our resources into a temp directory so that we can load // them quickly and the file system can cache them sensibly File rfile = getResourceFile(path); return (rfile == null) ? null : new FileInputStream(rfile); } @Override public BufferedImage getImageResource (String path, boolean useFastIO) throws IOException { return ResourceManager.loadImage(getResourceFile(path), useFastIO); } /** * Returns the {@link File} from which resources are fetched for this bundle. */ public File getSource () { return _source; } /** * @return true if the bundle is fully downloaded and successfully unpacked. */ public boolean isUnpacked () { return (_source.exists() && _unpacked != null && _unpacked.lastModified() == _source.lastModified()); } /** * Called by the resource manager once it has ensured that our resource jar file is up to date * and ready for reading. * * @return true if we successfully unpacked our resources, false if we encountered errors in * doing so. */ public boolean sourceIsReady () { // make a note of our source's last modification time _sourceLastMod = _source.lastModified(); // if we are unpacking files, the time to do so is now if (_unpacked != null && _unpacked.lastModified() != _sourceLastMod) { try { resolveJarFile(); } catch (IOException ioe) { log.warning("Failure resolving jar file", "source", _source, ioe); wipeBundle(true); return false; } log.info("Unpacking into " + _cache + "..."); if (!_cache.exists()) { if (!_cache.mkdir()) { log.warning("Failed to create bundle cache directory", "dir", _cache); closeJar(); // we are hopelessly fucked return false; } } else { FileUtil.recursiveClean(_cache); } // unpack the jar file (this will close the jar when it's done) if (!FileUtil.unpackJar(_jarSource, _cache)) { // if something went awry, delete everything in the hopes // that next time things will work wipeBundle(true); return false; } // if everything unpacked smoothly, create our unpack stamp try { _unpacked.createNewFile(); if (!_unpacked.setLastModified(_sourceLastMod)) { log.warning("Failed to set last mod on stamp file", "file", _unpacked); } } catch (IOException ioe) { log.warning("Failure creating stamp file", "file", _unpacked, ioe); // no need to stick a fork in things at this point } } return true; } /** * Clears out everything associated with this resource bundle in the hopes that we can * download it afresh and everything will work the next time around. */ public void wipeBundle (boolean deleteJar) { // clear out our cache directory if (_cache != null) { FileUtil.recursiveClean(_cache); } // delete our unpack stamp file if (_unpacked != null) { _unpacked.delete(); } // clear out any .jarv file that Getdown might be maintaining so // that we ensure that it is revalidated File vfile = new File(FileUtil.resuffix(_source, ".jar", ".jarv")); if (vfile.exists() && !vfile.delete()) { log.warning("Failed to delete vfile", "file", vfile); } // close and delete our source jar file if (deleteJar && _source != null) { closeJar(); if (!_source.delete()) { log.warning("Failed to delete source", "source", _source, "exists", _source.exists()); } } } /** * Returns a file from which the specified resource can be loaded. This method will unpack the * resource into a temporary directory and return a reference to that file. * * @param path the path to the resource in this jar file. * * @return a file from which the resource can be loaded or null if no such resource exists. */ public File getResourceFile (String path) throws IOException { if (resolveJarFile()) { return null; } // if we have been unpacked, return our unpacked file if (_cache != null) { File cfile = new File(_cache, path); if (cfile.exists()) { return cfile; } else { return null; } } // otherwise, we unpack resources as needed into a temp directory String tpath = StringUtil.md5hex(_source.getPath() + "%" + path); File tfile = new File(getCacheDir(), tpath); if (tfile.exists() && (tfile.lastModified() > _sourceLastMod)) { return tfile; } JarEntry entry = _jarSource.getJarEntry(path); if (entry == null) { // log.info("Couldn't locate path in jar", "path", path, "jar", _jarSource); return null; } // copy the resource into the temporary file BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(tfile)); InputStream jin = _jarSource.getInputStream(entry); StreamUtil.copy(jin, fout); jin.close(); fout.close(); return tfile; } /** * Returns true if this resource bundle contains the resource with the specified path. This * avoids actually loading the resource, in the event that the caller only cares to know that * the resource exists. */ public boolean containsResource (String path) { try { if (resolveJarFile()) { return false; } return (_jarSource.getJarEntry(path) != null); } catch (IOException ioe) { return false; } } @Override public String toString () { try { resolveJarFile(); return (_jarSource == null) ? "[file=" + _source + "]" : "[path=" + _jarSource.getName() + "]"; } catch (IOException ioe) { return "[file=" + _source + ", ioe=" + ioe + "]"; } } /** * Creates the internal jar file reference if we've not already got it; we do this lazily so * as to avoid any jar- or zip-file-related antics until and unless doing so is required, and * because the resource manager would like to be able to create bundles before the associated * files have been fully downloaded. * * @return true if the jar file could not yet be resolved because we haven't yet heard from * the resource manager that it is ready for us to access, false if all is cool. */ protected boolean resolveJarFile () throws IOException { // if we don't yet have our resource bundle's last mod time, we // have not yet been notified that it is ready if (_sourceLastMod == -1) { return true; } if (!_source.exists()) { throw new IOException("Missing jar file for resource bundle: " + _source + "."); } try { if (_jarSource == null) { _jarSource = new JarFile(_source); } return false; } catch (IOException ioe) { String msg = "Failed to resolve resource bundle jar file '" + _source + "'"; log.warning(msg + ".", ioe); throw (IOException) new IOException(msg).initCause(ioe); } } /** * Closes our (possibly opened) jar file. */ protected void closeJar () { try { if (_jarSource != null) { _jarSource.close(); } } catch (Exception ioe) { log.warning("Failed to close jar file", "path", _source, "error", ioe); } } /** * Returns the cache directory used for unpacked resources. */ public static File getCacheDir () { if (_tmpdir == null) { String tmpdir = System.getProperty("java.io.tmpdir"); if (tmpdir == null) { log.info("No system defined temp directory. Faking it."); tmpdir = System.getProperty("user.home"); } setCacheDir(new File(tmpdir)); } return _tmpdir; } /** * Specifies the directory in which our temporary resource files should be stored. */ public static void setCacheDir (File tmpdir) { String rando = Long.toHexString((long)(Math.random() * Long.MAX_VALUE)); _tmpdir = new File(tmpdir, "narcache_" + rando); if (!_tmpdir.exists()) { if (_tmpdir.mkdirs()) { log.debug("Created narya temp cache directory '" + _tmpdir + "'."); } else { log.warning("Failed to create temp cache directory '" + _tmpdir + "'."); } } // add a hook to blow away the temp directory when we exit Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run () { log.info("Clearing narya temp cache '" + _tmpdir + "'."); FileUtil.recursiveDelete(_tmpdir); } }); } /** Strips the .jar off of jar file paths. */ protected static String stripSuffix (String path) { if (path.endsWith(".jar")) { return path.substring(0, path.length()-4); } else { // we have to change the path somehow return path + "-cache"; } } /** The file from which we construct our jar file. */ protected File _source; /** The last modified time of our source jar file. */ protected long _sourceLastMod = -1; /** A file whose timestamp indicates whether or not our existing jar file has been unpacked. */ protected File _unpacked; /** A directory into which we unpack files from our bundle. */ protected File _cache; /** The jar file from which we load resources. */ protected JarFile _jarSource; /** A directory in which we temporarily unpack our resource files. */ protected static File _tmpdir; }
lgpl-2.1
eadthem/ossmmorpg
speedTests/stdAtomics_std.cpp
154
#include <atomic> int main(void) { { std::atomic_long x; long out; for (int i = 0; i < 500000000; i++) { //x += 0x3; out = x; } } }
lgpl-2.1
youfoh/webkit-efl
Source/WebCore/loader/appcache/ApplicationCacheGroup.cpp
47725
/* * Copyright (C) 2008, 2009, 2010 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS 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. */ #include "config.h" #include "ApplicationCacheGroup.h" #include "ApplicationCache.h" #include "ApplicationCacheHost.h" #include "ApplicationCacheResource.h" #include "ApplicationCacheStorage.h" #include "Chrome.h" #include "ChromeClient.h" #include "Console.h" #include "DOMApplicationCache.h" #include "DOMWindow.h" #include "DocumentLoader.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "InspectorInstrumentation.h" #include "MainResourceLoader.h" #include "ManifestParser.h" #include "Page.h" #include "ScriptProfile.h" #include "SecurityOrigin.h" #include "Settings.h" #include <wtf/HashMap.h> #include <wtf/MainThread.h> #include <wtf/UnusedParam.h> #if ENABLE(INSPECTOR) #include "ProgressTracker.h" #endif namespace WebCore { ApplicationCacheGroup::ApplicationCacheGroup(const KURL& manifestURL, bool isCopy) : m_manifestURL(manifestURL) , m_origin(SecurityOrigin::create(manifestURL)) , m_updateStatus(Idle) , m_downloadingPendingMasterResourceLoadersCount(0) , m_progressTotal(0) , m_progressDone(0) , m_frame(0) , m_storageID(0) , m_isObsolete(false) , m_completionType(None) , m_isCopy(isCopy) , m_calledReachedMaxAppCacheSize(false) , m_availableSpaceInQuota(ApplicationCacheStorage::unknownQuota()) , m_originQuotaExceededPreviously(false) { } ApplicationCacheGroup::~ApplicationCacheGroup() { if (m_isCopy) { ASSERT(m_newestCache); ASSERT(m_caches.size() == 1); ASSERT(m_caches.contains(m_newestCache.get())); ASSERT(!m_cacheBeingUpdated); ASSERT(m_associatedDocumentLoaders.isEmpty()); ASSERT(m_pendingMasterResourceLoaders.isEmpty()); ASSERT(m_newestCache->group() == this); return; } ASSERT(!m_newestCache); ASSERT(m_caches.isEmpty()); stopLoading(); cacheStorage().cacheGroupDestroyed(this); } ApplicationCache* ApplicationCacheGroup::cacheForMainRequest(const ResourceRequest& request, DocumentLoader*) { if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return 0; KURL url(request.url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); if (ApplicationCacheGroup* group = cacheStorage().cacheGroupForURL(url)) { ASSERT(group->newestCache()); ASSERT(!group->isObsolete()); return group->newestCache(); } return 0; } ApplicationCache* ApplicationCacheGroup::fallbackCacheForMainRequest(const ResourceRequest& request, DocumentLoader*) { if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return 0; KURL url(request.url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); if (ApplicationCacheGroup* group = cacheStorage().fallbackCacheGroupForURL(url)) { ASSERT(group->newestCache()); ASSERT(!group->isObsolete()); return group->newestCache(); } return 0; } void ApplicationCacheGroup::selectCache(Frame* frame, const KURL& passedManifestURL) { ASSERT(frame && frame->page()); if (!frame->settings() || !frame->settings()->offlineWebApplicationCacheEnabled()) return; DocumentLoader* documentLoader = frame->loader()->documentLoader(); ASSERT(!documentLoader->applicationCacheHost()->applicationCache()); if (passedManifestURL.isNull()) { selectCacheWithoutManifestURL(frame); return; } KURL manifestURL(passedManifestURL); if (manifestURL.hasFragmentIdentifier()) manifestURL.removeFragmentIdentifier(); ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache(); if (mainResourceCache) { if (manifestURL == mainResourceCache->group()->m_manifestURL) { // The cache may have gotten obsoleted after we've loaded from it, but before we parsed the document and saw cache manifest. if (mainResourceCache->group()->isObsolete()) return; mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache); mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext); } else { // The main resource was loaded from cache, so the cache must have an entry for it. Mark it as foreign. KURL resourceURL(documentLoader->responseURL()); if (resourceURL.hasFragmentIdentifier()) resourceURL.removeFragmentIdentifier(); ApplicationCacheResource* resource = mainResourceCache->resourceForURL(resourceURL); bool inStorage = resource->storageID(); resource->addType(ApplicationCacheResource::Foreign); if (inStorage) cacheStorage().storeUpdatedType(resource, mainResourceCache); // Restart the current navigation from the top of the navigation algorithm, undoing any changes that were made // as part of the initial load. // The navigation will not result in the same resource being loaded, because "foreign" entries are never picked during navigation. frame->navigationScheduler()->scheduleLocationChange(frame->document()->securityOrigin(), documentLoader->url(), frame->loader()->referrer()); } return; } // The resource was loaded from the network, check if it is a HTTP/HTTPS GET. const ResourceRequest& request = frame->loader()->activeDocumentLoader()->request(); if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return; // Check that the resource URL has the same scheme/host/port as the manifest URL. if (!protocolHostAndPortAreEqual(manifestURL, request.url())) return; // Don't change anything on disk if private browsing is enabled. if (frame->settings()->privateBrowsingEnabled()) { postListenerTask(ApplicationCacheHost::CHECKING_EVENT, documentLoader); postListenerTask(ApplicationCacheHost::ERROR_EVENT, documentLoader); return; } ApplicationCacheGroup* group = cacheStorage().findOrCreateCacheGroup(manifestURL); documentLoader->applicationCacheHost()->setCandidateApplicationCacheGroup(group); group->m_pendingMasterResourceLoaders.add(documentLoader); group->m_downloadingPendingMasterResourceLoadersCount++; ASSERT(!group->m_cacheBeingUpdated || group->m_updateStatus != Idle); group->update(frame, ApplicationCacheUpdateWithBrowsingContext); } void ApplicationCacheGroup::selectCacheWithoutManifestURL(Frame* frame) { if (!frame->settings() || !frame->settings()->offlineWebApplicationCacheEnabled()) return; DocumentLoader* documentLoader = frame->loader()->documentLoader(); ASSERT(!documentLoader->applicationCacheHost()->applicationCache()); ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache(); if (mainResourceCache) { mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache); mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext); } } void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader* loader) { ASSERT(m_pendingMasterResourceLoaders.contains(loader)); ASSERT(m_completionType == None || m_pendingEntries.isEmpty()); KURL url = loader->url(); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); switch (m_completionType) { case None: // The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later. return; case NoUpdate: ASSERT(!m_cacheBeingUpdated); associateDocumentLoaderWithCache(loader, m_newestCache.get()); if (ApplicationCacheResource* resource = m_newestCache->resourceForURL(url)) { if (!(resource->type() & ApplicationCacheResource::Master)) { resource->addType(ApplicationCacheResource::Master); ASSERT(!resource->storageID()); } } else m_newestCache->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData())); break; case Failure: // Cache update has been a failure, so there is no reason to keep the document associated with the incomplete cache // (its main resource was not cached yet, so it is likely that the application changed significantly server-side). ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading(). loader->applicationCacheHost()->setApplicationCache(0); // Will unset candidate, too. m_associatedDocumentLoaders.remove(loader); postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; case Completed: ASSERT(m_associatedDocumentLoaders.contains(loader)); if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) { if (!(resource->type() & ApplicationCacheResource::Master)) { resource->addType(ApplicationCacheResource::Master); ASSERT(!resource->storageID()); } } else m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData())); // The "cached" event will be posted to all associated documents once update is complete. break; } ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0); m_downloadingPendingMasterResourceLoadersCount--; checkIfLoadIsComplete(); } void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader* loader) { ASSERT(m_pendingMasterResourceLoaders.contains(loader)); ASSERT(m_completionType == None || m_pendingEntries.isEmpty()); switch (m_completionType) { case None: // The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later. return; case NoUpdate: ASSERT(!m_cacheBeingUpdated); // The manifest didn't change, and we have a relevant cache - but the main resource download failed mid-way, so it cannot be stored to the cache, // and the loader does not get associated to it. If there are other main resources being downloaded for this cache group, they may still succeed. postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; case Failure: // Cache update failed, too. ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading(). ASSERT(!loader->applicationCacheHost()->applicationCache() || loader->applicationCacheHost()->applicationCache() == m_cacheBeingUpdated); loader->applicationCacheHost()->setApplicationCache(0); // Will unset candidate, too. m_associatedDocumentLoaders.remove(loader); postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; case Completed: // The cache manifest didn't list this main resource, and all cache entries were already updated successfully - but the main resource failed to load, // so it cannot be stored to the cache. If there are other main resources being downloaded for this cache group, they may still succeed. ASSERT(m_associatedDocumentLoaders.contains(loader)); ASSERT(loader->applicationCacheHost()->applicationCache() == m_cacheBeingUpdated); ASSERT(!loader->applicationCacheHost()->candidateApplicationCacheGroup()); m_associatedDocumentLoaders.remove(loader); loader->applicationCacheHost()->setApplicationCache(0); postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; } ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0); m_downloadingPendingMasterResourceLoadersCount--; checkIfLoadIsComplete(); } void ApplicationCacheGroup::stopLoading() { if (m_manifestHandle) { ASSERT(!m_currentHandle); ASSERT(m_manifestHandle->client() == this); m_manifestHandle->setClient(0); m_manifestHandle->cancel(); m_manifestHandle = 0; } if (m_currentHandle) { ASSERT(!m_manifestHandle); ASSERT(m_cacheBeingUpdated); ASSERT(m_currentHandle->client() == this); m_currentHandle->setClient(0); m_currentHandle->cancel(); m_currentHandle = 0; } // FIXME: Resetting just a tiny part of the state in this function is confusing. Callers have to take care of a lot more. m_cacheBeingUpdated = 0; m_pendingEntries.clear(); } void ApplicationCacheGroup::disassociateDocumentLoader(DocumentLoader* loader) { HashSet<DocumentLoader*>::iterator it = m_associatedDocumentLoaders.find(loader); if (it != m_associatedDocumentLoaders.end()) m_associatedDocumentLoaders.remove(it); m_pendingMasterResourceLoaders.remove(loader); loader->applicationCacheHost()->setApplicationCache(0); // Will set candidate to 0, too. if (!m_associatedDocumentLoaders.isEmpty() || !m_pendingMasterResourceLoaders.isEmpty()) return; if (m_caches.isEmpty()) { // There is an initial cache attempt in progress. ASSERT(!m_newestCache); // Delete ourselves, causing the cache attempt to be stopped. delete this; return; } ASSERT(m_caches.contains(m_newestCache.get())); // Release our reference to the newest cache. This could cause us to be deleted. // Any ongoing updates will be stopped from destructor. m_newestCache.release(); } void ApplicationCacheGroup::cacheDestroyed(ApplicationCache* cache) { if (!m_caches.contains(cache)) return; m_caches.remove(cache); if (m_caches.isEmpty()) { ASSERT(m_associatedDocumentLoaders.isEmpty()); ASSERT(m_pendingMasterResourceLoaders.isEmpty()); delete this; } } void ApplicationCacheGroup::stopLoadingInFrame(Frame* frame) { if (frame != m_frame) return; cacheUpdateFailed(); } void ApplicationCacheGroup::setNewestCache(PassRefPtr<ApplicationCache> newestCache) { m_newestCache = newestCache; m_caches.add(m_newestCache.get()); m_newestCache->setGroup(this); } void ApplicationCacheGroup::makeObsolete() { if (isObsolete()) return; m_isObsolete = true; cacheStorage().cacheGroupMadeObsolete(this); ASSERT(!m_storageID); } void ApplicationCacheGroup::update(Frame* frame, ApplicationCacheUpdateOption updateOption) { if (m_updateStatus == Checking || m_updateStatus == Downloading) { if (updateOption == ApplicationCacheUpdateWithBrowsingContext) { postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader()->documentLoader()); if (m_updateStatus == Downloading) postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, frame->loader()->documentLoader()); } return; } // Don't change anything on disk if private browsing is enabled. if (!frame->settings() || frame->settings()->privateBrowsingEnabled()) { ASSERT(m_pendingMasterResourceLoaders.isEmpty()); ASSERT(m_pendingEntries.isEmpty()); ASSERT(!m_cacheBeingUpdated); postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader()->documentLoader()); postListenerTask(ApplicationCacheHost::NOUPDATE_EVENT, frame->loader()->documentLoader()); return; } ASSERT(!m_frame); m_frame = frame; setUpdateStatus(Checking); postListenerTask(ApplicationCacheHost::CHECKING_EVENT, m_associatedDocumentLoaders); if (!m_newestCache) { ASSERT(updateOption == ApplicationCacheUpdateWithBrowsingContext); postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader()->documentLoader()); } ASSERT(!m_manifestHandle); ASSERT(!m_manifestResource); ASSERT(!m_currentHandle); ASSERT(!m_currentResource); ASSERT(m_completionType == None); // FIXME: Handle defer loading m_manifestHandle = createResourceHandle(m_manifestURL, m_newestCache ? m_newestCache->manifestResource() : 0); } void ApplicationCacheGroup::abort(Frame* frame) { if (m_updateStatus == Idle) return; ASSERT(m_updateStatus == Checking || (m_updateStatus == Downloading && m_cacheBeingUpdated)); if (m_completionType != None) return; frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, TipMessageLevel, "Application Cache download process was aborted."); cacheUpdateFailed(); } PassRefPtr<ResourceHandle> ApplicationCacheGroup::createResourceHandle(const KURL& url, ApplicationCacheResource* newestCachedResource) { ResourceRequest request(url); m_frame->loader()->applyUserAgent(request); request.setHTTPHeaderField("Cache-Control", "max-age=0"); if (newestCachedResource) { const String& lastModified = newestCachedResource->response().httpHeaderField("Last-Modified"); const String& eTag = newestCachedResource->response().httpHeaderField("ETag"); if (!lastModified.isEmpty() || !eTag.isEmpty()) { if (!lastModified.isEmpty()) request.setHTTPHeaderField("If-Modified-Since", lastModified); if (!eTag.isEmpty()) request.setHTTPHeaderField("If-None-Match", eTag); } } #if PLATFORM(BLACKBERRY) ResourceRequest::TargetType target = ResourceRequest::TargetIsUnspecified; if (newestCachedResource) { const String& mimeType = newestCachedResource->response().mimeType(); if (!mimeType.isEmpty()) target = ResourceRequest::targetTypeFromMimeType(mimeType); } if (target == ResourceRequest::TargetIsUnspecified) { String mimeType = mimeTypeFromDataURL(url); if (!mimeType.isEmpty()) target = ResourceRequest::targetTypeFromMimeType(mimeType); } request.setTargetType(target); #endif RefPtr<ResourceHandle> handle = ResourceHandle::create(m_frame->loader()->networkingContext(), request, this, false, true); #if ENABLE(INSPECTOR) // Because willSendRequest only gets called during redirects, we initialize // the identifier and the first willSendRequest here. m_currentResourceIdentifier = m_frame->page()->progress()->createUniqueIdentifier(); ResourceResponse redirectResponse = ResourceResponse(); InspectorInstrumentation::willSendRequest(m_frame, m_currentResourceIdentifier, m_frame->loader()->documentLoader(), request, redirectResponse); #endif return handle; } void ApplicationCacheGroup::didReceiveResponse(ResourceHandle* handle, const ResourceResponse& response) { #if ENABLE(INSPECTOR) DocumentLoader* loader = (handle == m_manifestHandle) ? 0 : m_frame->loader()->documentLoader(); InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame, m_currentResourceIdentifier, response); InspectorInstrumentation::didReceiveResourceResponse(cookie, m_currentResourceIdentifier, loader, response); #endif if (handle == m_manifestHandle) { didReceiveManifestResponse(response); return; } ASSERT(handle == m_currentHandle); KURL url(handle->firstRequest().url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); ASSERT(!m_currentResource); ASSERT(m_pendingEntries.contains(url)); unsigned type = m_pendingEntries.get(url); // If this is an initial cache attempt, we should not get master resources delivered here. if (!m_newestCache) ASSERT(!(type & ApplicationCacheResource::Master)); if (m_newestCache && response.httpStatusCode() == 304) { // Not modified. ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(url); if (newestCachedResource) { m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, newestCachedResource->data(), newestCachedResource->path())); m_pendingEntries.remove(m_currentHandle->firstRequest().url()); m_currentHandle->cancel(); m_currentHandle = 0; // Load the next resource, if any. startLoadingEntry(); return; } // The server could return 304 for an unconditional request - in this case, we handle the response as a normal error. } if (response.httpStatusCode() / 100 != 2 || response.url() != m_currentHandle->firstRequest().url()) { if ((type & ApplicationCacheResource::Explicit) || (type & ApplicationCacheResource::Fallback)) { m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because " + m_currentHandle->firstRequest().url().string() + ((response.httpStatusCode() / 100 != 2) ? " could not be fetched." : " was redirected.")); // Note that cacheUpdateFailed() can cause the cache group to be deleted. cacheUpdateFailed(); } else if (response.httpStatusCode() == 404 || response.httpStatusCode() == 410) { // Skip this resource. It is dropped from the cache. m_currentHandle->cancel(); m_currentHandle = 0; m_pendingEntries.remove(url); // Load the next resource, if any. startLoadingEntry(); } else { // Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act // as if that was the fetched resource, ignoring the resource obtained from the network. ASSERT(m_newestCache); ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(handle->firstRequest().url()); ASSERT(newestCachedResource); m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, newestCachedResource->data(), newestCachedResource->path())); m_pendingEntries.remove(m_currentHandle->firstRequest().url()); m_currentHandle->cancel(); m_currentHandle = 0; // Load the next resource, if any. startLoadingEntry(); } return; } m_currentResource = ApplicationCacheResource::create(url, response, type); } void ApplicationCacheGroup::didReceiveData(ResourceHandle* handle, const char* data, int length, int encodedDataLength) { UNUSED_PARAM(encodedDataLength); #if ENABLE(INSPECTOR) InspectorInstrumentation::didReceiveData(m_frame, m_currentResourceIdentifier, 0, length, 0); #endif if (handle == m_manifestHandle) { didReceiveManifestData(data, length); return; } ASSERT(handle == m_currentHandle); ASSERT(m_currentResource); m_currentResource->data()->append(data, length); } void ApplicationCacheGroup::didFinishLoading(ResourceHandle* handle, double finishTime) { #if ENABLE(INSPECTOR) InspectorInstrumentation::didFinishLoading(m_frame, m_frame->loader()->documentLoader(), m_currentResourceIdentifier, finishTime); #endif if (handle == m_manifestHandle) { didFinishLoadingManifest(); return; } ASSERT(m_currentHandle == handle); ASSERT(m_pendingEntries.contains(handle->firstRequest().url())); m_pendingEntries.remove(handle->firstRequest().url()); ASSERT(m_cacheBeingUpdated); m_cacheBeingUpdated->addResource(m_currentResource.release()); m_currentHandle = 0; // While downloading check to see if we have exceeded the available quota. // We can stop immediately if we have already previously failed // due to an earlier quota restriction. The client was already notified // of the quota being reached and decided not to increase it then. // FIXME: Should we break earlier and prevent redownloading on later page loads? if (m_originQuotaExceededPreviously && m_availableSpaceInQuota < m_cacheBeingUpdated->estimatedSizeInStorage()) { m_currentResource = 0; m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because size quota was exceeded."); cacheUpdateFailed(); return; } // Load the next resource, if any. startLoadingEntry(); } void ApplicationCacheGroup::didFail(ResourceHandle* handle, const ResourceError& error) { #if ENABLE(INSPECTOR) InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader()->documentLoader(), m_currentResourceIdentifier, error); #endif if (handle == m_manifestHandle) { // A network error is logged elsewhere, no need to log again. Also, it's normal for manifest fetching to fail when working offline. cacheUpdateFailed(); return; } ASSERT(handle == m_currentHandle); unsigned type = m_currentResource ? m_currentResource->type() : m_pendingEntries.get(handle->firstRequest().url()); KURL url(handle->firstRequest().url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); ASSERT(!m_currentResource || !m_pendingEntries.contains(url)); m_currentResource = 0; m_pendingEntries.remove(url); if ((type & ApplicationCacheResource::Explicit) || (type & ApplicationCacheResource::Fallback)) { m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because " + url.string() + " could not be fetched."); // Note that cacheUpdateFailed() can cause the cache group to be deleted. cacheUpdateFailed(); } else { // Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act // as if that was the fetched resource, ignoring the resource obtained from the network. ASSERT(m_newestCache); ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(url); ASSERT(newestCachedResource); m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, newestCachedResource->data(), newestCachedResource->path())); // Load the next resource, if any. startLoadingEntry(); } } void ApplicationCacheGroup::didReceiveManifestResponse(const ResourceResponse& response) { ASSERT(!m_manifestResource); ASSERT(m_manifestHandle); if (response.httpStatusCode() == 404 || response.httpStatusCode() == 410) { manifestNotFound(); return; } if (response.httpStatusCode() == 304) return; if (response.httpStatusCode() / 100 != 2) { m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be fetched."); cacheUpdateFailed(); return; } if (response.url() != m_manifestHandle->firstRequest().url()) { m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be fetched, because a redirection was attempted."); cacheUpdateFailed(); return; } m_manifestResource = ApplicationCacheResource::create(m_manifestHandle->firstRequest().url(), response, ApplicationCacheResource::Manifest); } void ApplicationCacheGroup::didReceiveManifestData(const char* data, int length) { if (m_manifestResource) m_manifestResource->data()->append(data, length); } void ApplicationCacheGroup::didFinishLoadingManifest() { bool isUpgradeAttempt = m_newestCache; if (!isUpgradeAttempt && !m_manifestResource) { // The server returned 304 Not Modified even though we didn't send a conditional request. m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be fetched because of an unexpected 304 Not Modified server response."); cacheUpdateFailed(); return; } m_manifestHandle = 0; // Check if the manifest was not modified. if (isUpgradeAttempt) { ApplicationCacheResource* newestManifest = m_newestCache->manifestResource(); ASSERT(newestManifest); if (!m_manifestResource || // The resource will be null if HTTP response was 304 Not Modified. (newestManifest->data()->size() == m_manifestResource->data()->size() && !memcmp(newestManifest->data()->data(), m_manifestResource->data()->data(), newestManifest->data()->size()))) { m_completionType = NoUpdate; m_manifestResource = 0; deliverDelayedMainResources(); return; } } Manifest manifest; if (!parseManifest(m_manifestURL, m_manifestResource->data()->data(), m_manifestResource->data()->size(), manifest)) { // At the time of this writing, lack of "CACHE MANIFEST" signature is the only reason for parseManifest to fail. m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be parsed. Does it start with CACHE MANIFEST?"); cacheUpdateFailed(); return; } #if ENABLE(TIZEN_APPLICATION_CACHE) if(!m_frame->page()->chrome()->client()->requestApplicationCachePermission(m_frame)) { cacheUpdateFailed(); return; } #endif ASSERT(!m_cacheBeingUpdated); m_cacheBeingUpdated = ApplicationCache::create(); m_cacheBeingUpdated->setGroup(this); HashSet<DocumentLoader*>::const_iterator masterEnd = m_pendingMasterResourceLoaders.end(); for (HashSet<DocumentLoader*>::const_iterator iter = m_pendingMasterResourceLoaders.begin(); iter != masterEnd; ++iter) associateDocumentLoaderWithCache(*iter, m_cacheBeingUpdated.get()); // We have the manifest, now download the resources. setUpdateStatus(Downloading); postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, m_associatedDocumentLoaders); ASSERT(m_pendingEntries.isEmpty()); if (isUpgradeAttempt) { ApplicationCache::ResourceMap::const_iterator end = m_newestCache->end(); for (ApplicationCache::ResourceMap::const_iterator it = m_newestCache->begin(); it != end; ++it) { unsigned type = it->second->type(); if (type & ApplicationCacheResource::Master) addEntry(it->first, type); } } HashSet<String>::const_iterator end = manifest.explicitURLs.end(); for (HashSet<String>::const_iterator it = manifest.explicitURLs.begin(); it != end; ++it) addEntry(*it, ApplicationCacheResource::Explicit); size_t fallbackCount = manifest.fallbackURLs.size(); for (size_t i = 0; i < fallbackCount; ++i) addEntry(manifest.fallbackURLs[i].second, ApplicationCacheResource::Fallback); m_cacheBeingUpdated->setOnlineWhitelist(manifest.onlineWhitelistedURLs); m_cacheBeingUpdated->setFallbackURLs(manifest.fallbackURLs); m_cacheBeingUpdated->setAllowsAllNetworkRequests(manifest.allowAllNetworkRequests); m_progressTotal = m_pendingEntries.size(); m_progressDone = 0; recalculateAvailableSpaceInQuota(); startLoadingEntry(); } void ApplicationCacheGroup::didReachMaxAppCacheSize() { ASSERT(m_frame); ASSERT(m_cacheBeingUpdated); m_frame->page()->chrome()->client()->reachedMaxAppCacheSize(cacheStorage().spaceNeeded(m_cacheBeingUpdated->estimatedSizeInStorage())); m_calledReachedMaxAppCacheSize = true; checkIfLoadIsComplete(); } void ApplicationCacheGroup::didReachOriginQuota(int64_t totalSpaceNeeded) { // Inform the client the origin quota has been reached, they may decide to increase the quota. // We expect quota to be increased synchronously while waiting for the call to return. m_frame->page()->chrome()->client()->reachedApplicationCacheOriginQuota(m_origin.get(), totalSpaceNeeded); } void ApplicationCacheGroup::cacheUpdateFailed() { stopLoading(); m_manifestResource = 0; // Wait for master resource loads to finish. m_completionType = Failure; deliverDelayedMainResources(); } void ApplicationCacheGroup::recalculateAvailableSpaceInQuota() { if (!cacheStorage().calculateRemainingSizeForOriginExcludingCache(m_origin.get(), m_newestCache.get(), m_availableSpaceInQuota)) { // Failed to determine what is left in the quota. Fallback to allowing anything. m_availableSpaceInQuota = ApplicationCacheStorage::noQuota(); } } void ApplicationCacheGroup::manifestNotFound() { makeObsolete(); postListenerTask(ApplicationCacheHost::OBSOLETE_EVENT, m_associatedDocumentLoaders); postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_pendingMasterResourceLoaders); stopLoading(); ASSERT(m_pendingEntries.isEmpty()); m_manifestResource = 0; while (!m_pendingMasterResourceLoaders.isEmpty()) { HashSet<DocumentLoader*>::iterator it = m_pendingMasterResourceLoaders.begin(); ASSERT((*it)->applicationCacheHost()->candidateApplicationCacheGroup() == this); ASSERT(!(*it)->applicationCacheHost()->applicationCache()); (*it)->applicationCacheHost()->setCandidateApplicationCacheGroup(0); m_pendingMasterResourceLoaders.remove(it); } m_downloadingPendingMasterResourceLoadersCount = 0; setUpdateStatus(Idle); m_frame = 0; if (m_caches.isEmpty()) { ASSERT(m_associatedDocumentLoaders.isEmpty()); ASSERT(!m_cacheBeingUpdated); delete this; } } void ApplicationCacheGroup::checkIfLoadIsComplete() { if (m_manifestHandle || !m_pendingEntries.isEmpty() || m_downloadingPendingMasterResourceLoadersCount) return; // We're done, all resources have finished downloading (successfully or not). bool isUpgradeAttempt = m_newestCache; switch (m_completionType) { case None: ASSERT_NOT_REACHED(); return; case NoUpdate: ASSERT(isUpgradeAttempt); ASSERT(!m_cacheBeingUpdated); // The storage could have been manually emptied by the user. if (!m_storageID) cacheStorage().storeNewestCache(this); postListenerTask(ApplicationCacheHost::NOUPDATE_EVENT, m_associatedDocumentLoaders); break; case Failure: ASSERT(!m_cacheBeingUpdated); postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders); if (m_caches.isEmpty()) { ASSERT(m_associatedDocumentLoaders.isEmpty()); delete this; return; } break; case Completed: { // FIXME: Fetch the resource from manifest URL again, and check whether it is identical to the one used for update (in case the application was upgraded server-side in the meanwhile). (<rdar://problem/6467625>) ASSERT(m_cacheBeingUpdated); if (m_manifestResource) m_cacheBeingUpdated->setManifestResource(m_manifestResource.release()); else { // We can get here as a result of retrying the Complete step, following // a failure of the cache storage to save the newest cache due to hitting // the maximum size. In such a case, m_manifestResource may be 0, as // the manifest was already set on the newest cache object. ASSERT(cacheStorage().isMaximumSizeReached() && m_calledReachedMaxAppCacheSize); } RefPtr<ApplicationCache> oldNewestCache = (m_newestCache == m_cacheBeingUpdated) ? RefPtr<ApplicationCache>() : m_newestCache; // If we exceeded the origin quota while downloading we can request a quota // increase now, before we attempt to store the cache. int64_t totalSpaceNeeded; if (!cacheStorage().checkOriginQuota(this, oldNewestCache.get(), m_cacheBeingUpdated.get(), totalSpaceNeeded)) didReachOriginQuota(totalSpaceNeeded); ApplicationCacheStorage::FailureReason failureReason; setNewestCache(m_cacheBeingUpdated.release()); if (cacheStorage().storeNewestCache(this, oldNewestCache.get(), failureReason)) { // New cache stored, now remove the old cache. if (oldNewestCache) cacheStorage().remove(oldNewestCache.get()); // Fire the final progress event. ASSERT(m_progressDone == m_progressTotal); postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders); // Fire the success event. postListenerTask(isUpgradeAttempt ? ApplicationCacheHost::UPDATEREADY_EVENT : ApplicationCacheHost::CACHED_EVENT, m_associatedDocumentLoaders); // It is clear that the origin quota was not reached, so clear the flag if it was set. m_originQuotaExceededPreviously = false; } else { if (failureReason == ApplicationCacheStorage::OriginQuotaReached) { // We ran out of space for this origin. Fall down to the normal error handling // after recording this state. m_originQuotaExceededPreviously = true; m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because size quota was exceeded."); } if (failureReason == ApplicationCacheStorage::TotalQuotaReached && !m_calledReachedMaxAppCacheSize) { // FIXME: Should this be handled more like Origin Quotas? Does this fail properly? // We ran out of space. All the changes in the cache storage have // been rolled back. We roll back to the previous state in here, // as well, call the chrome client asynchronously and retry to // save the new cache. // Save a reference to the new cache. m_cacheBeingUpdated = m_newestCache.release(); if (oldNewestCache) { // Reinstate the oldNewestCache. setNewestCache(oldNewestCache.release()); } scheduleReachedMaxAppCacheSizeCallback(); return; } // Run the "cache failure steps" // Fire the error events to all pending master entries, as well any other cache hosts // currently associated with a cache in this group. postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders); // Disassociate the pending master entries from the failed new cache. Note that // all other loaders in the m_associatedDocumentLoaders are still associated with // some other cache in this group. They are not associated with the failed new cache. // Need to copy loaders, because the cache group may be destroyed at the end of iteration. Vector<DocumentLoader*> loaders; copyToVector(m_pendingMasterResourceLoaders, loaders); size_t count = loaders.size(); for (size_t i = 0; i != count; ++i) disassociateDocumentLoader(loaders[i]); // This can delete this group. // Reinstate the oldNewestCache, if there was one. if (oldNewestCache) { // This will discard the failed new cache. setNewestCache(oldNewestCache.release()); } else { // We must have been deleted by the last call to disassociateDocumentLoader(). return; } } break; } } // Empty cache group's list of pending master entries. m_pendingMasterResourceLoaders.clear(); m_completionType = None; setUpdateStatus(Idle); m_frame = 0; m_availableSpaceInQuota = ApplicationCacheStorage::unknownQuota(); m_calledReachedMaxAppCacheSize = false; } void ApplicationCacheGroup::startLoadingEntry() { ASSERT(m_cacheBeingUpdated); if (m_pendingEntries.isEmpty()) { m_completionType = Completed; deliverDelayedMainResources(); return; } EntryMap::const_iterator it = m_pendingEntries.begin(); postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders); m_progressDone++; ASSERT(!m_currentHandle); m_currentHandle = createResourceHandle(KURL(ParsedURLString, it->first), m_newestCache ? m_newestCache->resourceForURL(it->first) : 0); } void ApplicationCacheGroup::deliverDelayedMainResources() { // Need to copy loaders, because the cache group may be destroyed at the end of iteration. Vector<DocumentLoader*> loaders; copyToVector(m_pendingMasterResourceLoaders, loaders); size_t count = loaders.size(); for (size_t i = 0; i != count; ++i) { DocumentLoader* loader = loaders[i]; if (loader->isLoadingMainResource()) continue; const ResourceError& error = loader->mainDocumentError(); if (error.isNull()) finishedLoadingMainResource(loader); else failedLoadingMainResource(loader); } if (!count) checkIfLoadIsComplete(); } void ApplicationCacheGroup::addEntry(const String& url, unsigned type) { ASSERT(m_cacheBeingUpdated); ASSERT(!KURL(ParsedURLString, url).hasFragmentIdentifier()); // Don't add the URL if we already have an master resource in the cache // (i.e., the main resource finished loading before the manifest). if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) { ASSERT(resource->type() & ApplicationCacheResource::Master); ASSERT(!m_frame->loader()->documentLoader()->isLoadingMainResource()); resource->addType(type); return; } // Don't add the URL if it's the same as the manifest URL. ASSERT(m_manifestResource); if (m_manifestResource->url() == url) { m_manifestResource->addType(type); return; } EntryMap::AddResult result = m_pendingEntries.add(url, type); if (!result.isNewEntry) result.iterator->second |= type; } void ApplicationCacheGroup::associateDocumentLoaderWithCache(DocumentLoader* loader, ApplicationCache* cache) { // If teardown started already, revive the group. if (!m_newestCache && !m_cacheBeingUpdated) m_newestCache = cache; ASSERT(!m_isObsolete); loader->applicationCacheHost()->setApplicationCache(cache); ASSERT(!m_associatedDocumentLoaders.contains(loader)); m_associatedDocumentLoaders.add(loader); } class ChromeClientCallbackTimer: public TimerBase { public: ChromeClientCallbackTimer(ApplicationCacheGroup* cacheGroup) : m_cacheGroup(cacheGroup) { } private: virtual void fired() { m_cacheGroup->didReachMaxAppCacheSize(); delete this; } // Note that there is no need to use a RefPtr here. The ApplicationCacheGroup instance is guaranteed // to be alive when the timer fires since invoking the ChromeClient callback is part of its normal // update machinery and nothing can yet cause it to get deleted. ApplicationCacheGroup* m_cacheGroup; }; void ApplicationCacheGroup::scheduleReachedMaxAppCacheSizeCallback() { ASSERT(isMainThread()); ChromeClientCallbackTimer* timer = new ChromeClientCallbackTimer(this); timer->startOneShot(0); // The timer will delete itself once it fires. } class CallCacheListenerTask : public ScriptExecutionContext::Task { public: static PassOwnPtr<CallCacheListenerTask> create(PassRefPtr<DocumentLoader> loader, ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone) { return adoptPtr(new CallCacheListenerTask(loader, eventID, progressTotal, progressDone)); } virtual void performTask(ScriptExecutionContext* context) { ASSERT_UNUSED(context, context->isDocument()); Frame* frame = m_documentLoader->frame(); if (!frame) return; ASSERT(frame->loader()->documentLoader() == m_documentLoader.get()); m_documentLoader->applicationCacheHost()->notifyDOMApplicationCache(m_eventID, m_progressTotal, m_progressDone); } private: CallCacheListenerTask(PassRefPtr<DocumentLoader> loader, ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone) : m_documentLoader(loader) , m_eventID(eventID) , m_progressTotal(progressTotal) , m_progressDone(progressDone) { } RefPtr<DocumentLoader> m_documentLoader; ApplicationCacheHost::EventID m_eventID; int m_progressTotal; int m_progressDone; }; void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, const HashSet<DocumentLoader*>& loaderSet) { HashSet<DocumentLoader*>::const_iterator loaderSetEnd = loaderSet.end(); for (HashSet<DocumentLoader*>::const_iterator iter = loaderSet.begin(); iter != loaderSetEnd; ++iter) postListenerTask(eventID, progressTotal, progressDone, *iter); } void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, DocumentLoader* loader) { Frame* frame = loader->frame(); if (!frame) return; ASSERT(frame->loader()->documentLoader() == loader); frame->document()->postTask(CallCacheListenerTask::create(loader, eventID, progressTotal, progressDone)); } void ApplicationCacheGroup::setUpdateStatus(UpdateStatus status) { m_updateStatus = status; } void ApplicationCacheGroup::clearStorageID() { m_storageID = 0; HashSet<ApplicationCache*>::const_iterator end = m_caches.end(); for (HashSet<ApplicationCache*>::const_iterator it = m_caches.begin(); it != end; ++it) (*it)->clearStorageID(); } }
lgpl-2.1
reimandlab/ActiveDriverDB
website/models/bio/gene.py
6206
from typing import List from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.declarative.base import declared_attr from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import backref from werkzeug.utils import cached_property from database import db, count_expression from database.types import ScalarSet from .model import BioModel, make_association_table from .protein import Protein from .sites import SiteType class GeneListEntry(BioModel): gene_list_id = db.Column(db.Integer, db.ForeignKey('genelist.id')) p = db.Column(db.Float(precision=53)) fdr = db.Column(db.Float(precision=53)) gene_id = db.Column(db.Integer, db.ForeignKey('gene.id')) gene = db.relationship('Gene') class ListModel: name = db.Column(db.String(255), nullable=False, unique=True, index=True) # lists are specific only to one type of mutations: mutation_source_name = db.Column(db.String(256), nullable=False) # and/or to only one type of PTM site @declared_attr def site_type_id(self): return db.Column(db.Integer, db.ForeignKey('sitetype.id')) @declared_attr def site_type(self): return db.relationship(SiteType) class GeneList(ListModel, BioModel): entries = db.relationship(GeneListEntry) class PathwaysListEntry(BioModel): pathways_list_id = db.Column(db.Integer, db.ForeignKey('pathwayslist.id')) # adjusted.p.val fdr = db.Column(db.Float(precision=53)) pathway_id = db.Column(db.Integer, db.ForeignKey('pathway.id')) pathway = db.relationship('Pathway') # the overlap as reported by ActivePathways overlap = db.Column(ScalarSet(), default=set) # pathway size at the time of the computation of the ActivePathways (term.size) # just so we can check it in an unlikely case of the the pathways going out of # sync with the ActivePathways results pathway_size = db.Column(db.Integer) class PathwaysList(ListModel, BioModel): entries = db.relationship(PathwaysListEntry) class Gene(BioModel): """Gene is uniquely identified although has multiple protein isoforms. The isoforms are always located on the same chromosome, strand and are a product of the same gene. The major function of this model is to group isoforms classified as belonging to the same gene and to verify consistency of chromosomes and strands information across the database. """ # HGNC symbols are allowed to be varchar(255) but 40 is still safe # as for storing symbols that are currently in use. Let's use 2 x 40. name = db.Column(db.String(80), unique=True, index=True) # Full name from HGNC full_name = db.Column(db.Text) # TRUE represent positive (+) strand, FALSE represents negative (-) strand # As equivalent to (?) from Generic Feature Format NULL could be used. strand = db.Column(db.Boolean()) # Chromosome - up to two digits (1-22 inclusive), X and Y and eventually MT chrom = db.Column(db.CHAR(2)) # "Records in Entrez Gene are assigned unique, stable and tracked integers as identifiers" # ncbi.nlm.nih.gov/pmc/articles/PMC3013746, doi: 10.1093/nar/gkq1237 # as for Jun 8 2017, there are 18 151 636 genes in Entrez (ncbi.nlm.nih.gov/gene/statistics) # an integer should suffice up to 2,147,483,647 genes. entrez_id = db.Column(db.Integer) isoforms: List['Protein'] = db.relationship( 'Protein', backref=backref('gene', lazy='immediate'), foreign_keys='Protein.gene_id' ) preferred_isoform_id = db.Column( db.Integer, db.ForeignKey('protein.id', name='fk_preferred_isoform') ) preferred_isoform = db.relationship( 'Protein', uselist=False, foreign_keys=preferred_isoform_id, post_update=True ) preferred_refseq = association_proxy('preferred_isoform', 'refseq') drugs = association_proxy('targeted_by', 'drug') @cached_property def alternative_isoforms(self): return [ isoform for isoform in self.isoforms if isoform.id != self.preferred_isoform_id ] @hybrid_property def isoforms_count(self): return len(self.isoforms) @isoforms_count.expression def isoforms_count(cls): return count_expression(cls, Protein) @hybrid_property def is_known_kinase(self): return bool(self.preferred_isoform.kinase) def __repr__(self): return f'<Gene {self.name}, with {len(self.isoforms)} isoforms>' def to_json(self): return { 'name': self.name, 'preferred_isoform': ( self.preferred_refseq if self.preferred_isoform else None ), 'isoforms_count': self.isoforms_count } class Pathway(BioModel): description = db.Column(db.Text) gene_ontology = db.Column(db.Integer, unique=True) reactome = db.Column(db.Integer, unique=True) association_table = make_association_table('pathway.id', Gene.id) genes = db.relationship( 'Gene', secondary=association_table, backref='pathways' ) @hybrid_property def gene_count(self): return len(self.genes) @gene_count.expression def gene_count(cls): return count_expression(cls, Gene, Gene.pathways) def to_json(self): return { 'id': self.id, 'description': self.description, 'reactome': self.reactome, 'gene_ontology': self.gene_ontology, 'gene_count': self.gene_count, 'genes': [ { 'name': gene, 'preferred_isoform': {'refseq': refseq} if refseq else None } for gene, refseq in ( db.session.query(Gene.name, Protein.refseq) .select_from(Pathway) .filter(Pathway.id == self.id) .join(Pathway.association_table) .join(Gene) .outerjoin(Protein, Gene.preferred_isoform_id == Protein.id) ) ] }
lgpl-2.1
xwiki/xwiki-platform
xwiki-platform-core/xwiki-platform-refactoring/xwiki-platform-refactoring-api/src/main/java/org/xwiki/refactoring/job/RestoreRequest.java
1260
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.refactoring.job; /** * A job request that can be used to restore a list of deleted documents and/or an entire batch of deleted documents * from the recycle bin. * * @version $Id$ * @since 9.4RC1 */ public class RestoreRequest extends AbstractDeletedDocumentsRequest { private static final long serialVersionUID = 7738465742607715013L; }
lgpl-2.1
xwiki/xwiki-platform
xwiki-platform-core/xwiki-platform-search/xwiki-platform-search-solr/xwiki-platform-search-solr-api/src/main/java/org/xwiki/search/solr/internal/SolrIndexAvailableLocalesListener.java
7121
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.search.solr.internal; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.LocaleUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.StreamingResponseCallback; import org.apache.solr.common.SolrDocument; import org.slf4j.Logger; import org.xwiki.bridge.event.AbstractDocumentEvent; import org.xwiki.bridge.event.ApplicationReadyEvent; import org.xwiki.bridge.event.DocumentCreatedEvent; import org.xwiki.bridge.event.DocumentUpdatedEvent; import org.xwiki.bridge.event.WikiReadyEvent; import org.xwiki.component.annotation.Component; import org.xwiki.model.EntityType; import org.xwiki.model.reference.DocumentReferenceResolver; import org.xwiki.observation.EventListener; import org.xwiki.observation.event.Event; import org.xwiki.observation.event.filter.RegexEventFilter; import org.xwiki.search.solr.internal.api.FieldUtils; import org.xwiki.search.solr.internal.api.SolrIndexer; import org.xwiki.search.solr.internal.api.SolrInstance; import com.xpn.xwiki.XWikiContext; /** * Update already indexed entries when new available locales are added. * * @version $Id$ * @since 5.1RC1 */ @Component @Named("solr.availablelocales") @Singleton public class SolrIndexAvailableLocalesListener implements EventListener { /** * The regex used to match preferences documents. */ private static final String PREFERENCEDOCUMENT_REGEX = ".*:XWiki.XWikiPreferences"; /** * The events to listen to that trigger the index update. */ private static final List<Event> EVENTS = Arrays.asList( new DocumentUpdatedEvent(new RegexEventFilter(PREFERENCEDOCUMENT_REGEX)), new DocumentCreatedEvent(new RegexEventFilter(PREFERENCEDOCUMENT_REGEX)), new ApplicationReadyEvent(), new WikiReadyEvent() ); /** * The currently available locales for each running wiki. */ private Map<String, Set<Locale>> localesCache = new ConcurrentHashMap<String, Set<Locale>>(); /** * Logging framework. */ @Inject private Logger logger; /** * Provider for the {@link SolrInstance} that allows communication with the Solr server. */ @Inject private SolrInstance solrInstance; /** * The solr index. * <p> * Lazily initialize the {@link SolrIndexer} to not initialize it too early. */ @Inject private Provider<SolrIndexer> solrIndexer; /** * Used to extract a document reference from a {@link SolrDocument}. */ @Inject private DocumentReferenceResolver<SolrDocument> solrDocumentReferenceResolver; @Override public List<Event> getEvents() { return EVENTS; } @Override public String getName() { return this.getClass().getName(); } @Override public void onEvent(Event event, Object source, Object data) { XWikiContext xcontext = (XWikiContext) data; String wiki = xcontext.getWikiId(); Set<Locale> oldLocales = this.localesCache.get(wiki); List<Locale> availableLocales = xcontext.getWiki().getAvailableLocales(xcontext); // Update the cache this.localesCache.put(wiki, new HashSet<Locale>(availableLocales)); try { // oldLocales may be null in case the XWikiPreferences has been modified as part of a mandatory document // initialization if (oldLocales != null && event instanceof AbstractDocumentEvent) { Collection<Locale> newLocales = CollectionUtils.subtract(availableLocales, oldLocales); if (!newLocales.isEmpty()) { StringBuilder builder = new StringBuilder(); for (Locale newLocale : newLocales) { for (Locale locale : getParentLocales(newLocale)) { if (builder.length() > 0) { builder.append(" OR "); } builder.append(FieldUtils.DOCUMENT_LOCALE); builder.append(':'); builder.append('"'); builder.append(locale.toString()); builder.append('"'); } } SolrQuery solrQuery = new SolrQuery(builder.toString()); solrQuery .setFields(FieldUtils.WIKI, FieldUtils.SPACES, FieldUtils.NAME, FieldUtils.DOCUMENT_LOCALE); solrQuery.addFilterQuery(FieldUtils.TYPE + ':' + EntityType.DOCUMENT.name()); StreamingResponseCallback callback = new StreamingResponseCallback() { @Override public void streamSolrDocument(SolrDocument doc) { solrIndexer.get().index(solrDocumentReferenceResolver.resolve(doc), true); } @Override public void streamDocListInfo(long numFound, long start, Float maxScore) { // Do nothing. } }; this.solrInstance.queryAndStreamResponse(solrQuery, callback); } } } catch (Exception e) { this.logger.error("Failed to handle event [{}] with source [{}]", event, source.toString(), e); } } /** * @param locale the locale * @return the parents of the locale */ private Set<Locale> getParentLocales(Locale locale) { Set<Locale> parentLocales = new HashSet<Locale>(LocaleUtils.localeLookupList(locale, Locale.ROOT)); parentLocales.remove(locale); return parentLocales; } }
lgpl-2.1
jondo2010/OpenSG
Source/Contrib/ComplexSceneManager/GLUT/OSGCSMGLUTWindowBase.cpp
11233
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2013 by the OpenSG Forum * * * * www.opensg.org * * * * contact: dirk@opensg.org, gerrit.voss@vossg.org, carsten_neumann@gmx.net * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * 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, version 2. * * * * 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 along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ /*****************************************************************************\ ***************************************************************************** ** ** ** This file is automatically generated. ** ** ** ** Any changes made to this file WILL be lost when it is ** ** regenerated, which can become necessary at any time. ** ** ** ** Do not change this file, changes should be done in the derived ** ** class CSMGLUTWindow! ** ** ***************************************************************************** \*****************************************************************************/ #include <cstdlib> #include <cstdio> #include "OSGConfig.h" #include "OSGCSMGLUTWindowBase.h" #include "OSGCSMGLUTWindow.h" #include <boost/bind.hpp> #ifdef WIN32 // turn off 'this' : used in base member initializer list warning #pragma warning(disable:4355) #endif OSG_BEGIN_NAMESPACE /***************************************************************************\ * Description * \***************************************************************************/ /*! \class OSG::CSMGLUTWindow */ /***************************************************************************\ * Field Documentation * \***************************************************************************/ /***************************************************************************\ * FieldType/FieldTrait Instantiation * \***************************************************************************/ #if !defined(OSG_DO_DOC) || defined(OSG_DOC_DEV) PointerType FieldTraits<CSMGLUTWindow *, nsOSG>::_type( "CSMGLUTWindowPtr", "CSMWindowPtr", CSMGLUTWindow::getClassType(), nsOSG); #endif OSG_FIELDTRAITS_GETTYPE_NS(CSMGLUTWindow *, nsOSG) OSG_EXPORT_PTR_SFIELD_FULL(PointerSField, CSMGLUTWindow *, nsOSG) OSG_EXPORT_PTR_MFIELD_FULL(PointerMField, CSMGLUTWindow *, nsOSG) /***************************************************************************\ * Field Description * \***************************************************************************/ void CSMGLUTWindowBase::classDescInserter(TypeObject &oType) { } CSMGLUTWindowBase::TypeObject CSMGLUTWindowBase::_type( CSMGLUTWindowBase::getClassname(), Inherited::getClassname(), "NULL", nsOSG, //Namespace reinterpret_cast<PrototypeCreateF>(&CSMGLUTWindowBase::createEmptyLocal), CSMGLUTWindow::initMethod, CSMGLUTWindow::exitMethod, reinterpret_cast<InitalInsertDescFunc>(&CSMGLUTWindow::classDescInserter), false, 0, "<?xml version=\"1.0\"?>\n" "\n" "<FieldContainer\n" " name=\"CSMGLUTWindow\"\n" " parent=\"CSMWindow\"\n" " library=\"ContribCSM\"\n" " pointerfieldtypes=\"both\"\n" " structure=\"concrete\"\n" " systemcomponent=\"true\"\n" " parentsystemcomponent=\"true\"\n" " decoratable=\"false\"\n" " useLocalIncludes=\"false\"\n" " isNodeCore=\"false\"\n" " isBundle=\"true\"\n" ">\n" "</FieldContainer>\n", "" ); /*------------------------------ get -----------------------------------*/ FieldContainerType &CSMGLUTWindowBase::getType(void) { return _type; } const FieldContainerType &CSMGLUTWindowBase::getType(void) const { return _type; } UInt32 CSMGLUTWindowBase::getContainerSize(void) const { return sizeof(CSMGLUTWindow); } /*------------------------- decorator get ------------------------------*/ /*------------------------------ access -----------------------------------*/ SizeT CSMGLUTWindowBase::getBinSize(ConstFieldMaskArg whichField) { SizeT returnValue = Inherited::getBinSize(whichField); return returnValue; } void CSMGLUTWindowBase::copyToBin(BinaryDataHandler &pMem, ConstFieldMaskArg whichField) { Inherited::copyToBin(pMem, whichField); } void CSMGLUTWindowBase::copyFromBin(BinaryDataHandler &pMem, ConstFieldMaskArg whichField) { Inherited::copyFromBin(pMem, whichField); } //! create a new instance of the class CSMGLUTWindowTransitPtr CSMGLUTWindowBase::createLocal(BitVector bFlags) { CSMGLUTWindowTransitPtr fc; if(getClassType().getPrototype() != NULL) { FieldContainerTransitPtr tmpPtr = getClassType().getPrototype()-> shallowCopyLocal(bFlags); fc = dynamic_pointer_cast<CSMGLUTWindow>(tmpPtr); } return fc; } //! create a new instance of the class, copy the container flags CSMGLUTWindowTransitPtr CSMGLUTWindowBase::createDependent(BitVector bFlags) { CSMGLUTWindowTransitPtr fc; if(getClassType().getPrototype() != NULL) { FieldContainerTransitPtr tmpPtr = getClassType().getPrototype()-> shallowCopyDependent(bFlags); fc = dynamic_pointer_cast<CSMGLUTWindow>(tmpPtr); } return fc; } //! create a new instance of the class CSMGLUTWindowTransitPtr CSMGLUTWindowBase::create(void) { return createLocal(); } CSMGLUTWindow *CSMGLUTWindowBase::createEmptyLocal(BitVector bFlags) { CSMGLUTWindow *returnValue; newPtr<CSMGLUTWindow>(returnValue, bFlags); returnValue->_pFieldFlags->_bNamespaceMask &= ~bFlags; return returnValue; } //! create an empty new instance of the class, do not copy the prototype CSMGLUTWindow *CSMGLUTWindowBase::createEmpty(void) { return createEmptyLocal(); } FieldContainerTransitPtr CSMGLUTWindowBase::shallowCopyLocal( BitVector bFlags) const { CSMGLUTWindow *tmpPtr; newPtr(tmpPtr, dynamic_cast<const CSMGLUTWindow *>(this), bFlags); FieldContainerTransitPtr returnValue(tmpPtr); tmpPtr->_pFieldFlags->_bNamespaceMask &= ~bFlags; return returnValue; } FieldContainerTransitPtr CSMGLUTWindowBase::shallowCopyDependent( BitVector bFlags) const { CSMGLUTWindow *tmpPtr; newPtr(tmpPtr, dynamic_cast<const CSMGLUTWindow *>(this), ~bFlags); FieldContainerTransitPtr returnValue(tmpPtr); tmpPtr->_pFieldFlags->_bNamespaceMask = bFlags; return returnValue; } FieldContainerTransitPtr CSMGLUTWindowBase::shallowCopy(void) const { return shallowCopyLocal(); } /*------------------------- constructors ----------------------------------*/ CSMGLUTWindowBase::CSMGLUTWindowBase(void) : Inherited() { } CSMGLUTWindowBase::CSMGLUTWindowBase(const CSMGLUTWindowBase &source) : Inherited(source) { } /*-------------------------- destructors ----------------------------------*/ CSMGLUTWindowBase::~CSMGLUTWindowBase(void) { } #ifdef OSG_MT_CPTR_ASPECT void CSMGLUTWindowBase::execSyncV( FieldContainer &oFrom, ConstFieldMaskArg whichField, AspectOffsetStore &oOffsets, ConstFieldMaskArg syncMode, const UInt32 uiSyncInfo) { CSMGLUTWindow *pThis = static_cast<CSMGLUTWindow *>(this); pThis->execSync(static_cast<CSMGLUTWindow *>(&oFrom), whichField, oOffsets, syncMode, uiSyncInfo); } #endif #ifdef OSG_MT_CPTR_ASPECT FieldContainer *CSMGLUTWindowBase::createAspectCopy( const FieldContainer *pRefAspect) const { CSMGLUTWindow *returnValue; newAspectCopy(returnValue, dynamic_cast<const CSMGLUTWindow *>(pRefAspect), dynamic_cast<const CSMGLUTWindow *>(this)); return returnValue; } #endif void CSMGLUTWindowBase::resolveLinks(void) { Inherited::resolveLinks(); } OSG_END_NAMESPACE
lgpl-2.1
qkrcjfgus33/heakang
files/cache/template_compiled/4f19fcac947d023f76e840e29e6a22d5.compiled.php
5287
<?php if(!defined("__XE__"))exit;?><script type="text/javascript"> jQuery(function($){ $('#loading').hide(); $('#writ_form #submit').on('click', function(){ $('#writ_form #submit').attr('disabled', true); $('#loading').show(); var params = {}; $('#writ_form input[name]').add('#writ_form select[name]').each(function(){ params[$(this).attr('name')] = $(this).val(); }); console.log(params); $.exec_json('achievement.procAchievementContentUpdate', params, complete); }); function complete(data){ $('#writ_form #submit').attr('disabled', false); $('#loading').hide(); if(data.message == 'success'){ alert('등록되었습니다.'); var url = current_url.setQuery('act','dispAchievementContentList').setQuery('achievement_srl',''); location.href = url; }else{ alert('등록실패.'); $('#writ_form #submit').attr('disabled', false); $('#loading').hide(); } } $('#writ_form input[type=date]') .datetimepicker({ lang:'ko', timepicker:false, format:'Y-m-d' }); }); </script> <?php $__tpl=TemplateHandler::getInstance();echo $__tpl->compile('modules/achievement/skins/default','_header.html') ?> <h2>주요공사 실적 수정</h2> <form action="./" method="post" id="writ_form"><input type="hidden" name="error_return_url" value="<?php echo htmlspecialchars(getRequestUriByServerEnviroment(), ENT_COMPAT | ENT_HTML401, 'UTF-8', false) ?>" /><input type="hidden" name="act" value="<?php echo $__Context->act ?>" /><input type="hidden" name="mid" value="<?php echo $__Context->mid ?>" /><input type="hidden" name="vid" value="<?php echo $__Context->vid ?>" /> <input type="hidden" name="module_srl" value="<?php echo $__Context->module_srl ?>" /> <input type="hidden" name="achievement_srl" value="<?php echo $__Context->achievement_info->achievement_srl ?>" /> <table border="0" class="achievementTable"> <tr> <th><?php echo $__Context->lang->achievement_title ?></th> <td class="left"><input type="text" name="achievement_title" value="<?php echo $__Context->achievement_info->achievement_title ?>" size="40" /></td> </tr> <tr> <th><?php echo $__Context->lang->achieve_class_title ?></th> <td class="left"> <?php $__Context->achieve_class_srl = $__Context->achievement_info->achievement_class_srl ?> <select name="achievement_class_srl"> <option value="1"<?php if($__Context->achieve_class_srl == 1){ ?> seleted<?php } ?>>철근콘크리트공사업</option> <option value="2"<?php if($__Context->achieve_class_srl == 2){ ?> seleted<?php } ?>>비계구조물해체공사업</option> <option value="3"<?php if($__Context->achieve_class_srl == 3){ ?> seleted<?php } ?>>토공사업</option> <option value="4"<?php if($__Context->achieve_class_srl == 4){ ?> seleted<?php } ?>>어장정화 정비업</option> <option value="5"<?php if($__Context->achieve_class_srl == 5){ ?> seleted<?php } ?>>선박관리업</option> <option value="6"<?php if($__Context->achieve_class_srl == 6){ ?> seleted<?php } ?>>건설기계대여업</option> <option value="7"<?php if($__Context->achieve_class_srl == 7){ ?> seleted<?php } ?>>건설폐기물 수집운반업</option> <option value="8"<?php if($__Context->achieve_class_srl == 8){ ?> seleted<?php } ?>>선박해체·제거업</option> <option value="9"<?php if($__Context->achieve_class_srl == 9){ ?> seleted<?php } ?>>상하수도설비공사</option> </select> </td> </tr> <tr> <th><?php echo $__Context->lang->achievement_date ?></th> <td class="left"> <input type="date" name="achievement_start_date" value="<?php echo $__Context->achievement_info->achievement_start_date ?>" size="40" />- <input type="date" name="achievement_end_date" value="<?php echo $__Context->achievement_info->achievement_end_date ?>" size="40" /></td> </tr> <tr> <th><?php echo $__Context->lang->achievement_position ?></th> <td class="left"><input type="text" name="achievement_position" value="<?php echo $__Context->achievement_info->achievement_position ?>" size="20" /></td> </tr> <tr> <th><?php echo $__Context->lang->achievement_owner ?></th> <td class="left"><input type="text" name="achievement_owner" value="<?php echo $__Context->achievement_info->achievement_owner ?>" size="20" /></td> </tr> <tr> <th><?php echo $__Context->lang->achievement_woncheongsa ?></th> <td class="left"><input type="text" name="achievement_woncheongsa" value="<?php echo $__Context->achievement_info->achievement_woncheongsa ?>" size="20" /></td> </tr> <tr> <th><?php echo $__Context->lang->achievement_photos ?></th> <td class="left"> <?php echo $__Context->editor ?> </tr> </table> <div class="btn"> <span class="button"><input type="button" value="<?php echo $__Context->lang->cmd_back ?>" onclick="history.back(); return false;" /></span> <span class="button red strong"> <input id="submit" type="button" value="<?php echo $__Context->lang->cmd_input ?>"/> </span> </div> <span id="loading">DB에 등록 중 입니다. <img src="/modules/achievement/skins/default/loading.gif" style=" width: 30px; vertical-align: middle; "> </span> </form> <?php $__tpl=TemplateHandler::getInstance();echo $__tpl->compile('modules/achievement/skins/default','_footer.html') ?>
lgpl-2.1
mono-soc-2011/axiom
Projects/AxiomDemos/Source/Demos/BezierPatch.cs
5825
#region Namespace Declarations using System; using Axiom.Core; using Axiom.Graphics; using Axiom.Math; using System.Runtime.InteropServices; #endregion Namespace Declarations namespace Axiom.Demos { public class BezierPatch : TechDemo { #region Protected Fields protected VertexDeclaration patchDeclaration; protected float timeLapse; protected float factor; protected bool isWireframe; protected PatchMesh patch; protected Entity patchEntity; protected Pass patchPass; #endregion Protected Fields #region Private Structs private struct PatchVertex { public float X, Y, Z; public float Nx, Ny, Nz; public float U, V; } #endregion Private Structs // --- Protected Override Methods --- #region CreateScene() // Just override the mandatory create scene method public override void CreateScene() { // Set ambient light scene.AmbientLight = new ColorEx( 0.2f, 0.2f, 0.2f ); // Create point light Light light = scene.CreateLight( "MainLight" ); // Accept default settings: point light, white diffuse, just set position. // I could attach the light to a SceneNode if I wanted it to move automatically with // other objects, but I don't. light.Type = LightType.Directional; light.Direction = new Vector3( -0.5f, -0.5f, 0 ); // Create patch with positions, normals, and 1 set of texcoords patchDeclaration = HardwareBufferManager.Instance.CreateVertexDeclaration(); patchDeclaration.AddElement( 0, 0, VertexElementType.Float3, VertexElementSemantic.Position ); patchDeclaration.AddElement( 0, 12, VertexElementType.Float3, VertexElementSemantic.Normal ); patchDeclaration.AddElement( 0, 24, VertexElementType.Float2, VertexElementSemantic.TexCoords, 0 ); // Patch data PatchVertex[] patchVertices = new PatchVertex[ 9 ]; patchVertices[ 0 ].X = -500; patchVertices[ 0 ].Y = 200; patchVertices[ 0 ].Z = -500; patchVertices[ 0 ].Nx = -0.5f; patchVertices[ 0 ].Ny = 0.5f; patchVertices[ 0 ].Nz = 0; patchVertices[ 0 ].U = 0; patchVertices[ 0 ].V = 0; patchVertices[ 1 ].X = 0; patchVertices[ 1 ].Y = 500; patchVertices[ 1 ].Z = -750; patchVertices[ 1 ].Nx = 0; patchVertices[ 1 ].Ny = 0.5f; patchVertices[ 1 ].Nz = 0; patchVertices[ 1 ].U = 0.5f; patchVertices[ 1 ].V = 0; patchVertices[ 2 ].X = 500; patchVertices[ 2 ].Y = 1000; patchVertices[ 2 ].Z = -500; patchVertices[ 2 ].Nx = 0.5f; patchVertices[ 2 ].Ny = 0.5f; patchVertices[ 2 ].Nz = 0; patchVertices[ 2 ].U = 1; patchVertices[ 2 ].V = 0; patchVertices[ 3 ].X = -500; patchVertices[ 3 ].Y = 0; patchVertices[ 3 ].Z = 0; patchVertices[ 3 ].Nx = -0.5f; patchVertices[ 3 ].Ny = 0.5f; patchVertices[ 3 ].Nz = 0; patchVertices[ 3 ].U = 0; patchVertices[ 3 ].V = 0.5f; patchVertices[ 4 ].X = 0; patchVertices[ 4 ].Y = 500; patchVertices[ 4 ].Z = 0; patchVertices[ 4 ].Nx = 0; patchVertices[ 4 ].Ny = 0.5f; patchVertices[ 4 ].Nz = 0; patchVertices[ 4 ].U = 0.5f; patchVertices[ 4 ].V = 0.5f; patchVertices[ 5 ].X = 500; patchVertices[ 5 ].Y = -50; patchVertices[ 5 ].Z = 0; patchVertices[ 5 ].Nx = 0.5f; patchVertices[ 5 ].Ny = 0.5f; patchVertices[ 5 ].Nz = 0; patchVertices[ 5 ].U = 1; patchVertices[ 5 ].V = 0.5f; patchVertices[ 6 ].X = -500; patchVertices[ 6 ].Y = 0; patchVertices[ 6 ].Z = 500; patchVertices[ 6 ].Nx = -0.5f; patchVertices[ 6 ].Ny = 0.5f; patchVertices[ 6 ].Nz = 0; patchVertices[ 6 ].U = 0; patchVertices[ 6 ].V = 1; patchVertices[ 7 ].X = 0; patchVertices[ 7 ].Y = 500; patchVertices[ 7 ].Z = 500; patchVertices[ 7 ].Nx = 0; patchVertices[ 7 ].Ny = 0.5f; patchVertices[ 7 ].Nz = 0; patchVertices[ 7 ].U = 0.5f; patchVertices[ 7 ].V = 1; patchVertices[ 8 ].X = 500; patchVertices[ 8 ].Y = 200; patchVertices[ 8 ].Z = 800; patchVertices[ 8 ].Nx = 0.5f; patchVertices[ 8 ].Ny = 0.5f; patchVertices[ 8 ].Nz = 0; patchVertices[ 8 ].U = 1; patchVertices[ 8 ].V = 1; patch = MeshManager.Instance.CreateBezierPatch( "Bezier1", ResourceGroupManager.DefaultResourceGroupName, patchVertices, patchDeclaration, 3, 3, 5, 5, VisibleSide.Both, BufferUsage.StaticWriteOnly, BufferUsage.DynamicWriteOnly, true, true ); // Start patch at 0 detail patch.Subdivision = 0; // Create entity based on patch patchEntity = scene.CreateEntity( "Entity1", "Bezier1" ); Material material = (Material)MaterialManager.Instance.Create( "TextMat", ResourceGroupManager.DefaultResourceGroupName, null ); material.GetTechnique( 0 ).GetPass( 0 ).CreateTextureUnitState( "BumpyMetal.jpg" ); patchEntity.MaterialName = "TextMat"; patchPass = material.GetTechnique( 0 ).GetPass( 0 ); // Attach the entity to the root of the scene scene.RootSceneNode.AttachObject( patchEntity ); camera.Position = new Vector3( 500, 500, 1500 ); camera.LookAt( new Vector3( 0, 200, -300 ) ); } #endregion CreateScene() // --- Protected Override Event Handlers --- #region bool OnFrameStarted(Object source, FrameEventArgs e) // Event handler to add ability to alter subdivision protected override void OnFrameRenderingQueued( Object source, FrameEventArgs evt ) { timeLapse += evt.TimeSinceLastFrame; // Progressively grow the patch if ( timeLapse > 1.0f ) { factor += 0.2f; if ( factor > 1.0f ) { isWireframe = !isWireframe; patchPass.PolygonMode = ( isWireframe ? PolygonMode.Wireframe : PolygonMode.Solid ); factor = 0.0f; } patch.Subdivision = factor; debugText = "Bezier subdivision factor: " + factor; timeLapse = 0.0f; } // Call default base.OnFrameStarted( source, evt ); } #endregion bool OnFrameStarted(Object source, FrameEventArgs e) } }
lgpl-2.1
alexpagnoni/jphp
var/jphp/jphp/sql/drivers/mysql/MySQLConnection.php
1018
<?php /** * @version 2.0 * @author Nicolas BUI <nbui@wanadoo.fr> * * This source file is part of JPHP Library Project. * Copyright: 2002 Vitry sur Seine/FRANCE * * The latest version can be obtained from: * http://www.jphplib.org */ JPHP::import('jphp.sql.interface.IConnection'); JPHP::import('jphp.sql.drivers.mysql.MySQLStatement'); class MySQLConnection extends IConnection { var $dbport_default = 3306; function startConnection() { $this->dblink = @mysql_connect($this->getHost().':'.$this->getPort(), $this->getUser(), $this->getPass()); if ($this->dblink) { @mysql_select_db ($this->getDatabaseName(), $this->getDatabaseLink()); return TRUE; } else { return FALSE; } } function endConnection() { if ($this->getDatabaseLink()) { @mysql_close($this->getDatabaseLink()); } } function createStatement() { return $this->getDatabaseLink() ? new MySQLStatement($this) : NULL; } } ?>
lgpl-2.1
giorgiosironi/NakedPhp
library/NakedPhp/Mvc/View/Helper/IconLoader.php
934
<?php /** * Naked Php is a framework that implements the Naked Objects pattern. * @copyright Copyright (C) 2009 Giorgio Sironi * @license http://www.gnu.org/licenses/lgpl-2.1.txt * * 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. * * @category NakedPhp * @package NakedPhp_Mvc */ namespace NakedPhp\Mvc\View\Helper; class IconLoader extends \Zend_View_Helper_Abstract { /** * TODO: try renaming to loadIcon() */ public function __call($name, $args) { list ($className, ) = $args; $html = ".icon.$className {\nbackground: url(/graphic/icons/$className.png) no-repeat left 50%;\npadding-left: 32px;\n}\n"; $this->view->headStyle()->appendStyle($html); } }
lgpl-2.1
xwiki/xwiki-platform
xwiki-platform-core/xwiki-platform-refactoring/xwiki-platform-refactoring-api/src/main/java/org/xwiki/refactoring/RefactoringConfiguration.java
1324
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.refactoring; import org.xwiki.component.annotation.Role; /** * Provides the configurations for the refactoring module. * * @version $Id$ * @since 12.8RC1 */ @Role public interface RefactoringConfiguration { /** * @return {@code true} if the configuration allows advanced users to skip the recycle bin and delete documents * permanently */ boolean isRecycleBinSkippingActivated(); }
lgpl-2.1
mono-soc-2011/axiom
Projects/Axiom/Engine/Animating/AnimationState.cs
8836
#region LGPL License /* Axiom Graphics Engine Library Copyright © 2003-2011 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. 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 */ #endregion #region SVN Version Information // <file> // <license see="http://axiom3d.net/wiki/index.php/license.txt"/> // <id value="$Id$"/> // </file> #endregion SVN Version Information #region Namespace Declarations using System; using Axiom.Controllers; using Axiom.Collections; #endregion Namespace Declarations #region Ogre Synchronization Information // <ogresynchronization> // <file name="AnimationState.h" revision="1.16" lastUpdated="10/15/2005" lastUpdatedBy="DanielH" /> // <file name="AnimationState.cpp" revision="1.17" lastUpdated="10/15/2005" lastUpdatedBy="DanielH" /> // </ogresynchronization> #endregion namespace Axiom.Animating { /// <summary> /// Represents the state of an animation and the weight of it's influence. /// </summary> /// <remarks> /// Other classes can hold instances of this class to store the state of any animations /// they are using. /// This class implements the IControllerValue interface to enable automatic update of /// animation state through controllers. /// </remarks> public class AnimationState : IControllerValue<float>, IComparable { #region Member variables /// <summary>Name of this animation track.</summary> protected string animationName; /// <summary></summary> protected float time; /// <summary></summary> protected float length; /// <summary></summary> protected float inverseLength; /// <summary></summary> protected float weight; /// <summary></summary> protected bool isEnabled; /// <summary></summary> protected AnimationStateSet parent; protected bool loop; #endregion #region Constructors /// <summary> /// /// </summary> /// <param name="animationName"></param> /// <param name="parent">The animation state set parent</param> /// <param name="time"></param> /// <param name="length"></param> /// <param name="weight"></param> /// <param name="isEnabled"></param> public AnimationState( string animationName, AnimationStateSet parent, float time, float length, float weight, bool isEnabled ) { this.animationName = animationName; this.parent = parent; this.time = time; this.weight = weight; // Set using Property this.IsEnabled = isEnabled; // set using the Length property this.Length = length; this.loop = true; parent.NotifyDirty(); } /// <summary> /// /// </summary> /// <param name="animationName"></param> /// <param name="animationStates">The animation state set parent</param> /// <param name="time"></param> /// <param name="length"></param> public AnimationState( string animationName, AnimationStateSet animationStates, float time, float length ) : this( animationName, animationStates, time, length, 1.0f, false ) { } /// <summary> /// The moral equivalent of a copy constructor /// </summary> /// <param name="parent">The animation state set parent</param> /// <param name="source">An animation state to copy from</param> public AnimationState( AnimationStateSet parent, AnimationState source ) { this.parent = parent; this.CopyFrom( source ); parent.NotifyDirty(); } #endregion #region Properties /// <summary> /// Gets the name of the animation to which this state applies /// </summary> public string Name { get { return animationName; } set { animationName = value; } } /// <summary> /// Gets/Sets the time position for this animation. /// </summary> public float Time { get { return time; } set { time = value; if ( loop ) { // Wrap time = (float)System.Math.IEEERemainder( time, length ); if ( time < 0 ) time += length; } else { // Clamp if ( time < 0 ) time = 0; else if ( time > length ) time = length; } } } /// <summary> /// Gets/Sets the total length of this animation (may be shorter than whole animation) /// </summary> public float Length { get { return length; } set { length = value; // update the inverse length of the animation if ( length != 0 ) inverseLength = 1.0f / length; else inverseLength = 0.0f; } } /// <summary> /// Gets/Sets the weight (influence) of this animation /// </summary> public float Weight { get { return weight; } set { weight = value; } } /// <summary> /// Gets/Sets whether this animation is enabled or not. /// </summary> public bool IsEnabled { get { return isEnabled; } set { isEnabled = value; parent.NotifyAnimationStateEnabled( this, isEnabled ); } } public bool Loop { get { return loop; } set { loop = value; } } /// <summary> /// Gets/Sets the animation state set owning this animation /// </summary> public AnimationStateSet Parent { get { return parent; } set { parent = value; } } #endregion #region Public methods /// <summary> /// Modifies the time position, adjusting for animation length. /// </summary> /// <param name="offset">Offset from the current time position.</param> public void AddTime( float offset ) { Time += offset; } /// <summary> /// Copies the states from another animation state, preserving the animation name /// (unlike CopyTo) but copying everything else. /// </summary> /// <param name="source">animation state which will use as source.</param> public void CopyFrom( AnimationState source ) { source.isEnabled = isEnabled; source.inverseLength = inverseLength; source.length = length; source.time = time; source.weight = weight; source.loop = loop; parent.NotifyDirty(); } #endregion #region Implementation of IControllerValue /// <summary> /// Gets/Sets the value to be used in a ControllerFunction. /// </summary> public float Value { get { return time * inverseLength; } set { time = value * length; } } #endregion #region Object overloads public static bool operator !=( AnimationState left, AnimationState right ) { return !( left == right ); } public override bool Equals( object obj ) { return obj is AnimationState && this == (AnimationState)obj; } public static bool operator ==( AnimationState left, AnimationState right ) { if ( object.ReferenceEquals( left, null ) && object.ReferenceEquals( right, null ) ) return true; if ( object.ReferenceEquals( left, null ) || object.ReferenceEquals( right, null ) ) return false; if ( left.animationName == right.animationName && left.isEnabled == right.isEnabled && left.time == right.time && left.weight == right.weight && left.length == right.length && left.loop == right.loop ) { return true; } else { return false; } } /// <summary> /// Override GetHashCode. /// </summary> /// <remarks> /// Done mainly to quash warnings, no real need for it. /// </remarks> /// <returns></returns> public override int GetHashCode() { return animationName.GetHashCode(); } #endregion Object overloads #region IComparable Members /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns>0 if they are the same, -1 otherwise.</returns> public int CompareTo( object obj ) { AnimationState other = obj as AnimationState; if ( animationName == other.animationName && isEnabled == other.isEnabled && time == other.time && weight == other.weight && length == other.length ) { return 0; } else { return -1; } } #endregion } }
lgpl-2.1
grzegorzmazur/yacas
cyacas/libyacas/src/lispeval.cpp
12339
#include "yacas/lispeval.h" #include "yacas/lispuserfunc.h" #include "yacas/standard.h" #include "yacas/errors.h" #include "yacas/infixparser.h" #include "yacas/lispio.h" #include "yacas/platfileio.h" #include <regex> #include <sstream> LispUserFunction* GetUserFunction(LispEnvironment& aEnvironment, LispPtr* subList) { LispObject* head = (*subList); LispUserFunction* userFunc = aEnvironment.UserFunction(*subList); if (userFunc) { return userFunc; } else if (head->String() != nullptr) { LispMultiUserFunction* multiUserFunc = aEnvironment.MultiUserFunction(head->String()); if (multiUserFunc->iFileToOpen != nullptr) { LispDefFile* def = multiUserFunc->iFileToOpen; multiUserFunc->iFileToOpen = nullptr; InternalUse(aEnvironment, def->FileName()); } userFunc = aEnvironment.UserFunction(*subList); } return userFunc; } UserStackInformation& LispEvaluatorBase::StackInformation() { return iBasicInfo; } void LispEvaluatorBase::ResetStack() {} void LispEvaluatorBase::ShowStack(LispEnvironment& aEnvironment, std::ostream& aOutput) { } // Eval: evaluates an expression. The result of this operation must // be a unique (copied) element! Eg. its Nixed might be set... void BasicEvaluator::Eval(LispEnvironment& aEnvironment, LispPtr& aResult, LispPtr& aExpression) { assert(aExpression); if (aEnvironment.stop_evaluation) { aEnvironment.stop_evaluation = false; ShowStack(aEnvironment, aEnvironment.CurrentOutput()); throw LispErrUserInterrupt(); } aEnvironment.iEvalDepth++; if (aEnvironment.iEvalDepth >= aEnvironment.iMaxEvalDepth) { ShowStack(aEnvironment, aEnvironment.CurrentOutput()); throw LispErrMaxRecurseDepthReached(); } const LispString* str = aExpression->String(); // Evaluate an atom: find the bound value (treat it as a variable) if (str) { if (str->front() == '\"') { aResult = aExpression->Copy(); goto FINISH; } LispPtr val; aEnvironment.GetVariable(str, val); if (!!val) { aResult = (val->Copy()); goto FINISH; } aResult = (aExpression->Copy()); goto FINISH; } { LispPtr* subList = aExpression->SubList(); if (subList) { LispObject* head = (*subList); if (head) { if (head->String()) { { const auto i = aEnvironment.CoreCommands().find(head->String()); if (i != aEnvironment.CoreCommands().end()) { i->second.Evaluate(aResult, aEnvironment, *subList); goto FINISH; } } { LispUserFunction* userFunc; userFunc = GetUserFunction(aEnvironment, subList); if (userFunc) { userFunc->Evaluate(aResult, aEnvironment, *subList); goto FINISH; } } } else { LispPtr oper((*subList)); LispPtr args2((*subList)->Nixed()); InternalApplyPure(oper, args2, aResult, aEnvironment); goto FINISH; } ReturnUnEvaluated(aResult, *subList, aEnvironment); goto FINISH; } } aResult = (aExpression->Copy()); } FINISH: aEnvironment.iEvalDepth--; } void ShowExpression(LispString& outString, LispEnvironment& aEnvironment, LispPtr& aExpression) { InfixPrinter infixprinter(aEnvironment.PreFix(), aEnvironment.InFix(), aEnvironment.PostFix(), aEnvironment.Bodied()); // Print out the current expression std::ostringstream stream; infixprinter.Print(aExpression, stream, aEnvironment); outString.append(stream.str()); std::regex_replace( outString, std::regex("(^\")|([^\\\\]\")"), std::string("\\\"")); } static void TraceShowExpression(LispEnvironment& aEnvironment, LispPtr& aExpression) { LispString outString; ShowExpression(outString, aEnvironment, aExpression); aEnvironment.CurrentOutput().write(outString.c_str(), outString.size()); } void TraceShowArg(LispEnvironment& aEnvironment, LispPtr& aParam, LispPtr& aValue) { for (int i = 0; i < aEnvironment.iEvalDepth + 2; i++) aEnvironment.CurrentOutput().write(" ", 2); aEnvironment.CurrentOutput() << "TrArg(\""; TraceShowExpression(aEnvironment, aParam); aEnvironment.CurrentOutput() << "\",\""; TraceShowExpression(aEnvironment, aValue); aEnvironment.CurrentOutput() << "\");\n"; } void TraceShowEnter(LispEnvironment& aEnvironment, LispPtr& aExpression) { for (int i = 0; i < aEnvironment.iEvalDepth; i++) aEnvironment.CurrentOutput().write(" ", 2); aEnvironment.CurrentOutput() << "TrEnter(\""; { const char* function = ""; if (aExpression->SubList()) { LispPtr* sub = aExpression->SubList(); if ((*sub)->String()) function = (*sub)->String()->c_str(); } aEnvironment.CurrentOutput() << function; } aEnvironment.CurrentOutput() << "\",\""; TraceShowExpression(aEnvironment, aExpression); aEnvironment.CurrentOutput() << "\",\""; aEnvironment.CurrentOutput() << ""; // file aEnvironment.CurrentOutput() << "\","; aEnvironment.CurrentOutput() << "0"; // line aEnvironment.CurrentOutput() << ");\n"; } void TraceShowLeave(LispEnvironment& aEnvironment, LispPtr& aResult, LispPtr& aExpression) { for (int i = 0; i < aEnvironment.iEvalDepth; i++) aEnvironment.CurrentOutput().write(" ", 2); aEnvironment.CurrentOutput().write("TrLeave(\"", 9); TraceShowExpression(aEnvironment, aExpression); aEnvironment.CurrentOutput().write("\",\"", 3); TraceShowExpression(aEnvironment, aResult); aEnvironment.CurrentOutput().write("\");\n", 4); } void TracedStackEvaluator::PushFrame() { UserStackInformation* op = new UserStackInformation; objs.push_back(op); } void TracedStackEvaluator::PopFrame() { assert(!objs.empty()); delete objs.back(); objs.pop_back(); } void TracedStackEvaluator::ResetStack() { while (!objs.empty()) PopFrame(); } UserStackInformation& TracedStackEvaluator::StackInformation() { return *objs.back(); } TracedStackEvaluator::~TracedStackEvaluator() { ResetStack(); } void TracedStackEvaluator::ShowStack(LispEnvironment& aEnvironment, std::ostream& aOutput) { LispLocalEvaluator local(aEnvironment, new BasicEvaluator); const std::size_t upto = objs.size(); for (std::size_t i = 0; i < upto; ++i) { aEnvironment.CurrentOutput() << i << ": "; aEnvironment.CurrentPrinter().Print( objs[i]->iOperator, aEnvironment.CurrentOutput(), aEnvironment); int internal; internal = aEnvironment.CoreCommands().find(objs[i]->iOperator->String()) != aEnvironment.CoreCommands().end(); if (internal) { aEnvironment.CurrentOutput() << " (Internal function) "; } else { if (objs[i]->iRulePrecedence >= 0) { aEnvironment.CurrentOutput() << " (Rule # " << objs[i]->iRulePrecedence; if (objs[i]->iSide) aEnvironment.CurrentOutput() << " in body) "; else aEnvironment.CurrentOutput() << " in pattern) "; } else aEnvironment.CurrentOutput() << " (User function) "; } if (!!objs[i]->iExpression) { aEnvironment.CurrentOutput() << "\n "; if (aEnvironment.iEvalDepth > (aEnvironment.iMaxEvalDepth - 10)) { LispString expr; PrintExpression(expr, objs[i]->iExpression, aEnvironment, 60); aEnvironment.CurrentOutput() << expr; } else { LispPtr* subList = objs[i]->iExpression->SubList(); if (!!subList && !!(*subList)) { LispString expr; LispPtr out(objs[i]->iExpression); PrintExpression(expr, out, aEnvironment, 60); aEnvironment.CurrentOutput() << expr; } } } aEnvironment.CurrentOutput() << '\n'; } } void TracedStackEvaluator::Eval(LispEnvironment& aEnvironment, LispPtr& aResult, LispPtr& aExpression) { if (aEnvironment.iEvalDepth >= aEnvironment.iMaxEvalDepth) { ShowStack(aEnvironment, aEnvironment.CurrentOutput()); throw LispErrMaxRecurseDepthReached(); } LispPtr* subList = aExpression->SubList(); const LispString* str = nullptr; if (subList) { LispObject* head = (*subList); if (head) { str = head->String(); if (str) { PushFrame(); UserStackInformation& st = StackInformation(); st.iOperator = LispAtom::New(aEnvironment, *str); st.iExpression = aExpression; } } } BasicEvaluator::Eval(aEnvironment, aResult, aExpression); if (str) { PopFrame(); } } void TracedEvaluator::Eval(LispEnvironment& aEnvironment, LispPtr& aResult, LispPtr& aExpression) { if (!aEnvironment.iDebugger) throw LispErrGeneric("Internal error: debugging failing"); if (aEnvironment.iDebugger->Stopped()) throw LispErrGeneric(""); REENTER: errorOutput.clear(); errorOutput.str(""); try { aEnvironment.iDebugger->Enter(aEnvironment, aExpression); } catch (const LispError& error) { HandleError(error, aEnvironment, errorOutput); } if (aEnvironment.iDebugger->Stopped()) throw LispErrGeneric(""); if (!errorOutput.str().empty()) { aEnvironment.CurrentOutput() << errorOutput.str(); aEnvironment.iEvalDepth = 0; goto REENTER; } errorOutput.clear(); errorOutput.str(""); try { BasicEvaluator::Eval(aEnvironment, aResult, aExpression); } catch (const LispError& error) { HandleError(error, aEnvironment, errorOutput); } if (!errorOutput.str().empty()) { aEnvironment.CurrentOutput() << errorOutput.str(); aEnvironment.iEvalDepth = 0; aEnvironment.iDebugger->Error(aEnvironment); goto REENTER; } if (aEnvironment.iDebugger->Stopped()) throw LispErrGeneric(""); aEnvironment.iDebugger->Leave(aEnvironment, aResult, aExpression); if (aEnvironment.iDebugger->Stopped()) throw LispErrGeneric(""); } void DefaultDebugger::Start() {} void DefaultDebugger::Finish() {} void DefaultDebugger::Enter(LispEnvironment& aEnvironment, LispPtr& aExpression) { LispLocalEvaluator local(aEnvironment, new BasicEvaluator); iTopExpr = (aExpression->Copy()); LispPtr result; defaultEval.Eval(aEnvironment, result, iEnter); } void DefaultDebugger::Leave(LispEnvironment& aEnvironment, LispPtr& aResult, LispPtr& aExpression) { LispLocalEvaluator local(aEnvironment, new BasicEvaluator); LispPtr result; iTopExpr = (aExpression->Copy()); iTopResult = (aResult); defaultEval.Eval(aEnvironment, result, iLeave); } bool DefaultDebugger::Stopped() { return iStopped; } void DefaultDebugger::Error(LispEnvironment& aEnvironment) { LispLocalEvaluator local(aEnvironment, new BasicEvaluator); LispPtr result; defaultEval.Eval(aEnvironment, result, iError); }
lgpl-2.1
livioc/nhibernate-core
src/NHibernate/Type/PersistentEnumType.cs
7555
using System; using System.Collections.Generic; using System.Data.Common; using NHibernate.Engine; using NHibernate.SqlTypes; namespace NHibernate.Type { /// <summary> /// PersistentEnumType /// </summary> [Serializable] public class PersistentEnumType : AbstractEnumType { #region Converters // OLD TODO: ORACLE - An convert is needed because right now everything that Oracle is // sending to NHibernate is a decimal - not the correct underlying type and I don't know why public interface IEnumConverter { object ToObject(System.Type enumClass, object code); object ToEnumValue(object value); SqlType SqlType { get; } } [Serializable] private abstract class AbstractEnumConverter<T> : IEnumConverter { public object ToObject(System.Type enumClass, object code) { return Enum.ToObject(enumClass, Convert(code)); } public object ToEnumValue(object value) { return Convert(value); } public abstract T Convert(object input); public abstract SqlType SqlType { get; } } [Serializable] private class SystemByteEnumConverter : AbstractEnumConverter<Byte> { public override byte Convert(object input) { return System.Convert.ToByte(input); } public override SqlType SqlType { get { return SqlTypeFactory.Byte; } } } [Serializable] private class SystemSByteEnumConverter : AbstractEnumConverter<SByte> { public override sbyte Convert(object input) { return System.Convert.ToSByte(input); } public override SqlType SqlType { get { return SqlTypeFactory.SByte; } } } [Serializable] private class SystemInt16EnumConverter : AbstractEnumConverter<Int16> { public override short Convert(object input) { return System.Convert.ToInt16(input); } public override SqlType SqlType { get { return SqlTypeFactory.Int16; } } } [Serializable] private class SystemInt32EnumConverter : AbstractEnumConverter<Int32> { public override int Convert(object input) { return System.Convert.ToInt32(input); } public override SqlType SqlType { get { return SqlTypeFactory.Int32; } } } [Serializable] private class SystemInt64EnumConverter : AbstractEnumConverter<Int64> { public override long Convert(object input) { return System.Convert.ToInt64(input); } public override SqlType SqlType { get { return SqlTypeFactory.Int64; } } } [Serializable] private class SystemUInt16EnumConverter : AbstractEnumConverter<UInt16> { public override ushort Convert(object input) { return System.Convert.ToUInt16(input); } public override SqlType SqlType { get { return SqlTypeFactory.UInt16; } } } [Serializable] private class SystemUInt32EnumConverter : AbstractEnumConverter<UInt32> { public override uint Convert(object input) { return System.Convert.ToUInt32(input); } public override SqlType SqlType { get { return SqlTypeFactory.UInt32; } } } [Serializable] private class SystemUInt64EnumConverter : AbstractEnumConverter<UInt64> { public override ulong Convert(object input) { return System.Convert.ToUInt64(input); } public override SqlType SqlType { get { return SqlTypeFactory.UInt64; } } } #endregion static PersistentEnumType() { converters = new Dictionary<System.Type, IEnumConverter>(8); converters.Add(typeof (Int32), new SystemInt32EnumConverter()); converters.Add(typeof (Int16), new SystemInt16EnumConverter()); converters.Add(typeof (Int64), new SystemInt64EnumConverter()); converters.Add(typeof (Byte), new SystemByteEnumConverter()); converters.Add(typeof (SByte), new SystemSByteEnumConverter()); converters.Add(typeof (UInt16), new SystemUInt16EnumConverter()); converters.Add(typeof (UInt32), new SystemUInt32EnumConverter()); converters.Add(typeof (UInt64), new SystemUInt64EnumConverter()); } private static readonly Dictionary<System.Type, IEnumConverter> converters; private readonly IEnumConverter converter; public PersistentEnumType(System.Type enumClass) : base(GetEnumCoverter(enumClass).SqlType,enumClass) { converter = GetEnumCoverter(enumClass); } public static IEnumConverter GetEnumCoverter(System.Type enumClass) { System.Type underlyingType = Enum.GetUnderlyingType(enumClass); IEnumConverter result; if (!converters.TryGetValue(underlyingType, out result)) { throw new HibernateException("Unknown UnderlyingDbType for Enum; type:" + enumClass.FullName); } return result; } public override object Get(DbDataReader rs, int index, ISessionImplementor session) { object code = rs[index]; if (code == DBNull.Value || code == null) { return null; } return GetInstance(code); } /// <summary> /// Gets an instance of the Enum /// </summary> /// <param name="code">The underlying value of an item in the Enum.</param> /// <returns> /// An instance of the Enum set to the <c>code</c> value. /// </returns> public virtual object GetInstance(object code) { try { return converter.ToObject(this.ReturnedClass, code); } catch (ArgumentException ae) { throw new HibernateException("ArgumentException occurred inside Enum.ToObject()", ae); } } /// <summary> /// Gets the correct value for the Enum. /// </summary> /// <param name="code">The value to convert (an enum instance).</param> /// <returns>A boxed version of the code, converted to the correct type.</returns> /// <remarks> /// This handles situations where the DataProvider returns the value of the Enum /// from the db in the wrong underlying type. It uses <see cref="Convert"/> to /// convert it to the correct type. /// </remarks> public virtual object GetValue(object code) { return converter.ToEnumValue(code); } public override void Set(DbCommand cmd, object value, int index, ISessionImplementor session) { cmd.Parameters[index].Value = value != null ? GetValue(value) : DBNull.Value; } public override object Get(DbDataReader rs, string name, ISessionImplementor session) { return Get(rs, rs.GetOrdinal(name), session); } public override string Name { get { return ReturnedClass.FullName; } } public override string ToString(object value) { return (value == null) ? null : GetValue(value).ToString(); } public override object FromStringValue(string xml) { return GetInstance(long.Parse(xml)); } public override object Assemble(object cached, ISessionImplementor session, object owner) { return cached == null ? null : GetInstance(cached); } public override object Disassemble(object value, ISessionImplementor session, object owner) { return (value == null) ? null : GetValue(value); } public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { return GetValue(value).ToString(); } public override bool Equals(object obj) { if (!base.Equals(obj)) { return false; } return ((PersistentEnumType)obj).ReturnedClass == ReturnedClass; } public override int GetHashCode() { return ReturnedClass.GetHashCode(); } } [Serializable] public class EnumType<T> : PersistentEnumType { private readonly string typeName; public EnumType() : base(typeof (T)) { System.Type type = GetType(); typeName = type.FullName + ", " + type.Assembly.GetName().Name; } public override string Name { get { return typeName; } } } }
lgpl-2.1
clescot/jguard
jguard-core/src/main/java/net/sf/jguard/core/enforcement/MockGuestPolicyEnforcementPointFilter.java
2484
/* * jGuard is a security framework based on top of jaas (java authentication and authorization security). * it is written for web applications, to resolve simply, access control problems. * version $Name$ * http://sourceforge.net/projects/jguard/ * * Copyright (C) 2004-2011 Charles Lescot * * 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 * * * jGuard project home page: * http://sourceforge.net/projects/jguard/ */ package net.sf.jguard.core.enforcement; import net.sf.jguard.core.authentication.Guest; import net.sf.jguard.core.authentication.filters.AuthenticationFilter; import net.sf.jguard.core.authorization.filters.AuthorizationFilter; import net.sf.jguard.core.lifecycle.MockRequestAdapter; import net.sf.jguard.core.lifecycle.MockResponseAdapter; import javax.inject.Inject; import java.util.List; /** * @author <a href="mailto:diabolo512@users.sourceforge.net">Charles Lescot</a> */ public class MockGuestPolicyEnforcementPointFilter extends GuestPolicyEnforcementPointFilter<MockRequestAdapter, MockResponseAdapter> { @Inject public MockGuestPolicyEnforcementPointFilter(@Guest List<AuthenticationFilter<MockRequestAdapter, MockResponseAdapter>> guestAuthenticationFilters, @Guest List<AuthorizationFilter<MockRequestAdapter, MockResponseAdapter>> guestAuthorizationFilters, List<AuthenticationFilter<MockRequestAdapter, MockResponseAdapter>> restfulAuthenticationFilters, List<AuthorizationFilter<MockRequestAdapter, MockResponseAdapter>> restfulAuthorizationFilters) { super(guestAuthenticationFilters, guestAuthorizationFilters, restfulAuthenticationFilters, restfulAuthorizationFilters); } }
lgpl-2.1
XFireEyeZ/Magical-Tech
src/main/java/ic2/api/energy/tile/IExplosionPowerOverride.java
882
package ic2.api.energy.tile; /** * Implement with an {@link IEnergySink} tile entity to change the force of the explosion when overpowered. */ public interface IExplosionPowerOverride { /** * Checks if the electric tile should explode. If you return false here, * the explosion will just not happen at all and the block will stay. * This is NOT recommended. * @return Whether the block should explode. * * @note It should not be dependent on the tier of the power injected, consider {@link IOverloadHandler} if necessary. */ boolean shouldExplode(); /** * The explosion force when too much power is received. * @param tier The tier of power, that was injected into the energy sink, that caused it to explode. * @param defaultPower The default explosion power. * @return The explosion power */ float getExplosionPower(int tier, float defaultPower); }
lgpl-2.1