repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
georgi-georgiev/FMIjs
BattleGame/BattleGame.Server/Data/UserMessagesType.cs
850
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BattleGame.Server.Data { using System; using System.Collections.Generic; public partial class UserMessagesType { public UserMessagesType() { this.UserMessages = new HashSet<UserMessage>(); } public long Id { get; set; } public string Type { get; set; } public virtual ICollection<UserMessage> UserMessages { get; set; } } }
mit
SekulKamberov/Telerik-Academy
Programming with C#/3. C# Object-Oriented Programming/07. Design Patterns/Behavioral Patterns/Visitor/Element.cs
202
namespace Visitor { /// <summary> /// The 'Element' abstract class /// </summary> internal abstract class Element { public abstract void Accept(IVisitor visitor); } }
mit
pedroaxl/Haraka
smtp_client.js
15266
// SMTP client object and class. This allows for every part of the client // protocol to be hooked for different levels of control, such as // smtp_forward and smtp_proxy queue plugins. var events = require('events'); var util = require('util'); var generic_pool = require('generic-pool'); var line_socket = require('./line_socket'); var logger = require('./logger'); var uuid = require('./utils').uuid; var base64 = require('./plugins/auth/auth_base').base64; var smtp_regexp = /^([0-9]{3})([ -])(.*)/; var STATE_IDLE = 1; var STATE_ACTIVE = 2; var STATE_RELEASED = 3; var STATE_DEAD = 4; var STATE_DESTROYED = 5; var tls_key; var tls_cert; function SMTPClient(port, host, connect_timeout, idle_timeout) { events.EventEmitter.call(this); this.uuid = uuid(); this.socket = line_socket.connect(port, host); this.socket.setTimeout(((connect_timeout === undefined) ? 30 : connect_timeout) * 1000); this.socket.setKeepAlive(true); this.state = STATE_IDLE; this.command = 'greeting'; this.response = [] this.connected = false; this.authenticated = false; this.auth_capabilities = []; var self = this; this.socket.on('line', function (line) { self.emit('server_protocol', line); var matches = smtp_regexp.exec(line); if (!matches) { self.emit('error', self.uuid + ': Unrecognised response from upstream server: ' + line); self.destroy(); return; } var code = matches[1], cont = matches[2], msg = matches[3]; self.response.push(msg); if (cont !== ' ') { return; } if (self.command === 'ehlo') { if (code.match(/^5/)) { // Handle fallback to HELO if EHLO is rejected self.emit('greeting', 'HELO'); return; } self.emit('capabilities'); if (self.command != 'ehlo') { return; } } if (self.command === 'xclient' && code.match(/^5/)) { // XCLIENT command was rejected (no permission?) // Carry on without XCLIENT self.command = 'helo'; } else if (code.match(/^[45]/)) { self.emit('bad_code', code, self.response.join(' ')); if (self.state != STATE_ACTIVE) { return; } } switch (self.command) { case 'xclient': self.xclient = true; self.emit('xclient', 'EHLO'); break; case 'starttls': if (tls_key && tls_cert) { this.upgrade({key: tls_key, cert: tls_cert}); } break; case 'greeting': self.connected = true; self.emit('greeting', 'EHLO'); break; case 'ehlo': self.emit('helo'); break; case 'helo': case 'mail': case 'rcpt': case 'data': case 'dot': case 'rset': case 'auth': self.emit(self.command); break; case 'quit': self.emit('quit'); self.destroy(); break; default: throw new Error("Unknown command: " + self.command); } }); this.socket.on('connect', function () { // Remove connection timeout and set idle timeout self.socket.setTimeout(((idle_timeout) ? idle_timeout : 300) * 1000); }); var closed = function (msg) { return function (error) { if (!error) { error = ''; } if (self.state === STATE_ACTIVE) { self.emit('error', self.uuid + ': SMTP connection ' + msg + ' ' + error); self.destroy(); } else { logger.logdebug('[smtp_client_pool] ' + self.uuid + ': SMTP connection ' + msg + ' ' + error + ' (state=' + self.state + ')'); if (self.state === STATE_IDLE) { self.state = STATE_DEAD; self.destroy(); } else if (self.state === STATE_RELEASED) { self.destroy(); } } }; }; this.socket.on('error', closed('errored')); this.socket.on('timeout', closed('timed out')); this.socket.on('close', closed('closed')); this.socket.on('end', closed('ended')); } util.inherits(SMTPClient, events.EventEmitter); SMTPClient.prototype.send_command = function (command, data) { var line = (command === 'dot') ? '.' : command + (data ? (' ' + data) : ''); this.emit('client_protocol', line); this.command = command.toLowerCase(); this.response = []; this.socket.write(line + "\r\n"); }; SMTPClient.prototype.start_data = function (data) { this.response = []; this.command = 'dot'; data.pipe(this.socket, { dot_stuffing: true, ending_dot: true, end: false }); }; SMTPClient.prototype.release = function () { if (!this.connected || this.command === 'data' || this.command === 'mailbody') { // Destroy here, we can't reuse a connection that was mid-data. this.destroy(); return; } logger.logdebug('[smtp_client_pool] ' + this.uuid + ' resetting, state=' + this.state); if (this.state === STATE_DESTROYED) { return; } this.state = STATE_RELEASED; this.removeAllListeners('greeting'); this.removeAllListeners('capabilities'); this.removeAllListeners('xclient'); this.removeAllListeners('helo'); this.removeAllListeners('mail'); this.removeAllListeners('rcpt'); this.removeAllListeners('data'); this.removeAllListeners('dot'); this.removeAllListeners('rset'); this.removeAllListeners('auth'); this.removeAllListeners('client_protocol'); this.removeAllListeners('server_protocol'); this.removeAllListeners('error'); this.removeAllListeners('bad_code'); this.on('bad_code', function (code, msg) { this.destroy(); }); this.on('rset', function () { logger.logdebug('[smtp_client_pool] ' + this.uuid + ' releasing, state=' + this.state); if (this.state === STATE_DESTROYED) { return; } this.state = STATE_IDLE; this.removeAllListeners('rset'); this.removeAllListeners('bad_code'); this.pool.release(this); }); this.send_command('RSET'); }; SMTPClient.prototype.destroy = function () { if (this.state !== STATE_DESTROYED) { this.pool.destroy(this); } }; SMTPClient.prototype.is_dead_sender = function (plugin, connection) { if (!connection.transaction) { // This likely means the sender went away on us, cleanup. connection.logwarn( plugin, "transaction went away, releasing smtp_client" ); this.release(); return true; } return false; }; // Separate pools are kept for each set of server attributes. exports.get_pool = function (server, port, host, connect_timeout, pool_timeout, max) { var port = port || 25; var host = host || 'localhost'; var connect_timeout = (connect_timeout === undefined) ? 30 : connect_timeout; var pool_timeout = (pool_timeout === undefined) ? 300 : pool_timeout; var name = port + ':' + host + ':' + pool_timeout; if (!server.notes.pool) { server.notes.pool = {}; } if (!server.notes.pool[name]) { var pool = generic_pool.Pool({ name: name, create: function (callback) { var smtp_client = new SMTPClient(port, host, connect_timeout); logger.logdebug('[smtp_client_pool] uuid=' + smtp_client.uuid + ' host=' + host + ' port=' + port + ' pool_timeout=' + pool_timeout + ' created'); callback(null, smtp_client); }, destroy: function(smtp_client) { logger.logdebug('[smtp_client_pool] ' + smtp_client.uuid + ' destroyed, state=' + smtp_client.state); smtp_client.state = STATE_DESTROYED; smtp_client.socket.destroy(); // Remove pool object from server notes once empty var size = pool.getPoolSize(); if (size === 0) { delete server.notes.pool[name]; } }, max: max || 1000, idleTimeoutMillis: pool_timeout * 1000, log: function (str, level) { level = (level === 'verbose') ? 'debug' : level; logger['log' + level]('[smtp_client_pool] [' + name + '] ' + str); } }); var acquire = pool.acquire; pool.acquire = function (callback, priority) { var callback_wrapper = function (err, smtp_client) { smtp_client.pool = pool; if (smtp_client.state === STATE_DEAD) { smtp_client.destroy(); pool.acquire(callback, priority); return; } smtp_client.state = STATE_ACTIVE; callback(err, smtp_client); }; acquire.call(pool, callback_wrapper, priority); }; server.notes.pool[name] = pool; } return server.notes.pool[name]; }; // Get a smtp_client for the given attributes. exports.get_client = function (server, callback, port, host, connect_timeout, pool_timeout, max) { var pool = exports.get_pool(server, port, host, connect_timeout, pool_timeout, max); pool.acquire(callback); }; // Get a smtp_client for the given attributes and set it up the common // config and listeners for plugins. Currently this is what smtp_proxy and // smtp_forward have in common. exports.get_client_plugin = function (plugin, connection, config, callback) { var enable_tls = /(true|yes|1)/i.exec(config.main.enable_tls) != null; var pool = exports.get_pool(connection.server, config.main.port, config.main.host, config.main.connect_timeout, config.main.timeout, config.main.max_connections); pool.acquire(function (err, smtp_client) { connection.logdebug(plugin, 'Got smtp_client: ' + smtp_client.uuid); var secured = false; smtp_client.call_next = function (retval, msg) { if (this.next) { var next = this.next; delete this.next; next(retval, msg); } }; smtp_client.on('client_protocol', function (line) { connection.logprotocol(plugin, 'C: ' + line); }); smtp_client.on('server_protocol', function (line) { connection.logprotocol(plugin, 'S: ' + line); }); var helo = function (command) { if (smtp_client.xclient) { smtp_client.send_command(command, connection.hello_host); } else { smtp_client.send_command(command, plugin.config.get('me')); } }; smtp_client.on('greeting', helo); smtp_client.on('xclient', helo); smtp_client.on('capabilities', function () { for (var line in smtp_client.response) { if (smtp_client.response[line].match(/^XCLIENT/)) { if(!smtp_client.xclient) { smtp_client.send_command('XCLIENT', 'ADDR=' + connection.remote_ip); return; } } if (smtp_client.response[line].match(/^STARTTLS/) && !secured) { tls_key = plugin.config.get('tls_key.pem', 'binary'); tls_cert = plugin.config.get('tls_cert.pem', 'binary'); if (tls_key && tls_cert && enable_tls) { smtp_client.socket.on('secure', function () { secured = true; smtp_client.emit('greeting', 'EHLO'); }); smtp_client.send_command('STARTTLS'); return; } } var auth_matches; if (auth_matches = smtp_client.response[line].match(/^AUTH (.*)$/)) { smtp_client.auth_capabilities = []; auth_matches = auth_matches[1].split(' '); for (var i = 0; i < auth_matches.length; i++) { smtp_client.auth_capabilities.push(auth_matches[i].toLowerCase()); } } } }); smtp_client.on('helo', function () { if (config.auth && !smtp_client.authenticated) { if (config.auth.type === null || typeof(config.auth.type) === 'undefined') { return; } // Ignore blank var auth_type = config.auth.type.toLowerCase(); if (smtp_client.auth_capabilities.indexOf(auth_type) == -1) { throw new Error("Auth type \"" + auth_type + "\" not supported by server (supports: " + smtp_client.auth_capabilities.join(',') + ")") } switch (auth_type) { case 'plain': if (!config.auth.user || !config.auth.pass) { throw new Error("Must include auth.user and auth.pass for PLAIN auth."); } logger.logdebug('[smtp_client_pool] uuid=' + smtp_client.uuid + ' authenticating as "' + config.auth.user + '"'); smtp_client.send_command('AUTH', 'PLAIN ' + base64(config.auth.user + "\0" + config.auth.user + "\0" + config.auth.pass) ); break; case 'cram-md5': throw new Error("Not implemented"); default: throw new Error("Unknown AUTH type: " + auth_type); } } else { if (smtp_client.is_dead_sender(plugin, connection)) { return; } smtp_client.send_command('MAIL', 'FROM:' + connection.transaction.mail_from); } }); smtp_client.on('auth', function () { if (smtp_client.is_dead_sender(plugin, connection)) { return; } smtp_client.authenticated = true; smtp_client.send_command('MAIL', 'FROM:' + connection.transaction.mail_from); }); smtp_client.on('error', function (msg) { connection.logwarn(plugin, msg); smtp_client.call_next(); }); if (smtp_client.connected) { if (smtp_client.xclient) { smtp_client.send_command('XCLIENT', 'ADDR=' + connection.remote_ip); } else { smtp_client.emit('helo'); } } callback(err, smtp_client); }); };
mit
mocheng/react-and-redux
chapter-05/todo_perf/src/index.js
278
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import TodoApp from './TodoApp'; import store from './Store.js'; ReactDOM.render( <Provider store={store}> <TodoApp /> </Provider>, document.getElementById('root') );
mit
janusnic/laravel.io
src/ServiceProviders/CommentServiceProvider.php
286
<?php namespace Lio\ServiceProviders; use Illuminate\Support\ServiceProvider; class CommentServiceProvider extends ServiceProvider { public function register() {} public function boot() { \Lio\Comments\Comment::observe(new \Lio\Comments\CommentObserver); } }
mit
sherousee/three.js
src/extras/core/Path.d.ts
1697
import { Vector2 } from './../../math/Vector2'; import { CurvePath } from './CurvePath'; export enum PathActions { MOVE_TO, LINE_TO, QUADRATIC_CURVE_TO, // Bezier quadratic curve BEZIER_CURVE_TO, // Bezier cubic curve CSPLINE_THRU, // Catmull-rom spline ARC, // Circle ELLIPSE, } export interface PathAction { action: PathActions; args: any; } /** * a 2d path representation, comprising of points, lines, and cubes, similar to the html5 2d canvas api. It extends CurvePath. */ export class Path extends CurvePath<Vector2> { constructor( points?: Vector2[] ); currentPoint: Vector2; /** * @deprecated Use {@link Path#setFromPoints .setFromPoints()} instead. */ fromPoints( vectors: Vector2[] ): void; setFromPoints( vectors: Vector2[] ): void; moveTo( x: number, y: number ): void; lineTo( x: number, y: number ): void; quadraticCurveTo( aCPx: number, aCPy: number, aX: number, aY: number ): void; bezierCurveTo( aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number ): void; splineThru( pts: Vector2[] ): void; arc( aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ): void; absarc( aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ): void; ellipse( aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number ): void; absellipse( aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number ): void; }
mit
RallySoftware/eclipselink.runtime
sdo/org.eclipse.persistence.sdo/src/org/eclipse/persistence/sdo/types/SDODataType.java
2229
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * bdoughan - May 6/2008 - 1.0M7 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.sdo.types; import commonj.sdo.Type; import org.eclipse.persistence.exceptions.SDOException; import org.eclipse.persistence.sdo.SDOType; import org.eclipse.persistence.sdo.helper.SDOTypeHelper;; public class SDODataType extends SDOType implements Type { private Object pseudoDefault; public SDODataType(String aUri, String aName, SDOTypeHelper sdoTypeHelper) { super(aUri, aName, sdoTypeHelper, null); isDataType = true; } public SDODataType(String aUri, String aName, Class aClass, SDOTypeHelper sdoTypeHelper) { this(aUri, aName, sdoTypeHelper); setInstanceClass(aClass); } public SDODataType(String aUri, String aName, Class aClass, SDOTypeHelper sdoTypeHelper, Object aPseudoDefault) { this(aUri, aName, aClass, sdoTypeHelper); this.pseudoDefault = aPseudoDefault; } public boolean isAbstract() { return false; } public boolean isDataType() { return true; } public boolean isInstance(Object object) { return getInstanceClass().isInstance(object); } public boolean isOpen() { return false; } public boolean isSequenced() { return false; } public Object getPseudoDefault() { return pseudoDefault; } protected void addOpenMappings() { } public void setOpen(boolean bOpen) { if(bOpen) { throw SDOException.typeCannotBeOpenAndDataType(getURI(), getName()); } } }
epl-1.0
cemalkilic/che
plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/push/PushToRemoteView.java
3299
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.git.client.push; import org.eclipse.che.api.git.shared.Remote; import org.eclipse.che.ide.api.mvp.View; import java.util.List; import javax.validation.constraints.NotNull; /** * The view of {@link PushToRemotePresenter}. * * @author Andrey Plotnikov * @author Sergii Leschenko */ public interface PushToRemoteView extends View<PushToRemoteView.ActionDelegate> { /** Needs for delegate some function into PushToRemote view. */ public interface ActionDelegate { /** Performs any actions appropriate in response to the user having pressed the Push button. */ void onPushClicked(); /** Performs any actions appropriate in response to the user having pressed the Cancel button. */ void onCancelClicked(); /** Performs any actions appropriate in response to the local branch value changed. */ void onLocalBranchChanged(); /** Performs any actions appropriate in response to the repository value changed. */ void onRepositoryChanged(); } /** * Returns selected repository. * * @return repository. */ @NotNull String getRepository(); /** * Sets available repositories. * * @param repositories * available repositories */ void setRepositories(@NotNull List<Remote> repositories); /** @return local branch */ @NotNull String getLocalBranch(); /** * Set local branches into view. * * @param branches * local branches */ void setLocalBranches(@NotNull List<String> branches); /** @return remote branches */ @NotNull String getRemoteBranch(); /** * Set remote branches into view. * * @param branches * remote branches */ void setRemoteBranches(@NotNull List<String> branches); /** * Add remote branch into view. * * @param branch * remote branch * @return {@code true} if branch added and {@code false} if branch already exist */ boolean addRemoteBranch(@NotNull String branch); /** * Selects pointed local branch * * @param branch * local branch to select */ void selectLocalBranch(@NotNull String branch); /** * Selects pointed remote branch * * @param branch * remote branch to select */ void selectRemoteBranch(@NotNull String branch); /** * Change the enable state of the push button. * * @param enabled * {@code true} to enable the button, {@code false} to disable it */ void setEnablePushButton(boolean enabled); /** Close dialog. */ void close(); /** Show dialog. */ void showDialog(); }
epl-1.0
RallySoftware/eclipselink.runtime
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/generic/Class41.java
918
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.models.generic; import org.eclipse.persistence.testing.models.generic.ClassI41; public class Class41 implements ClassI41 { int id; int value; }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/ui/util/RowLayouter.java
5356
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.util; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Control; import org.eclipse.core.runtime.Assert; /** * Helper class to layout a number of children if the composite uses a <code>GridLayout</code>. * If the numbers of widgets to be layouted into one row is smaller than the number of columns * defined for the grid layout the helper class assigns a corresponing value to the <code> * GridData.horizontalSpan</code> field. * * Additionally a row layouter manages a default <code>GridData</code> object for each column. * If set this grid data is used for the widget if it doesn't manage its own grid data object. * * Call one of the <code>perform</code> methods to assign the correct grid data objects to * a set of widgets according to the number of columns passed to the layouter's constructor. */ public class RowLayouter { public int spanHorizontalAlignment= -1; public int spanGrabExcessHorizontalSpace= -1; public int spanHorizontalSpan= -1; public int spanHorizontalIndent= -1; public int spanWidthHint= -1; public int spanVerticalAlignment= -1; public int spanGrabExcessVerticalSpace= -1; public int spanVerticalSpan= -1; public int spanHeightHint= -1; private int fNumColumns; private boolean fOrder; private Control fLastControl; private GridData[] fDefaultGridDatas= new GridData[4]; public RowLayouter(int numColumns) { this(numColumns, false); } public RowLayouter(int numColumns, boolean order) { fNumColumns= numColumns; fOrder= order; } public void setDefaultSpan() { spanHorizontalAlignment= GridData.FILL; spanGrabExcessHorizontalSpace= 1; } public void perform(Control c1) { perform(new Control[] {c1}, 0); } public void perform(Control c1, Control c2, int span) { perform(new Control[] {c1, c2}, span); } public void perform(Control c1, Control c2, Control c3, int span) { perform(new Control[] {c1, c2, c3}, span); } public void perform(Control[] controls, int spanColumn) { int numColumns= numColumns(); Assert.isTrue(controls.length <= numColumns); order(controls); int gridIndex= 0; for (int i= 0; i < controls.length; i++) { Control control= controls[i]; GridData gd= (GridData)control.getLayoutData(); if (gd == null) gd= getGridData(gridIndex); if (i == spanColumn) { int span= numColumns - (controls.length - 1); gridIndex+= span; if (gd == null) gd= new GridData(); applyDelta(gd); gd.horizontalSpan= span; } else { gridIndex++; } control.setLayoutData(gd); } } private void applyDelta(GridData gd) { if (spanHorizontalAlignment != -1) gd.horizontalAlignment= spanHorizontalAlignment; if (spanGrabExcessHorizontalSpace != -1) { if (spanGrabExcessHorizontalSpace == 0) gd.grabExcessHorizontalSpace= false; else gd.grabExcessHorizontalSpace= true; } if (spanHorizontalSpan != -1) gd.horizontalSpan= spanHorizontalSpan; if (spanHorizontalIndent != -1) gd.horizontalIndent= spanHorizontalIndent; if (spanWidthHint != -1) gd.widthHint= spanWidthHint; if (spanVerticalAlignment != -1) gd.verticalAlignment= spanVerticalAlignment; if (spanGrabExcessVerticalSpace != -1) { if (spanGrabExcessVerticalSpace == 0) gd.grabExcessVerticalSpace= false; else gd.grabExcessVerticalSpace= true; } if (spanVerticalSpan != -1) gd.verticalSpan= spanVerticalSpan; if (spanHeightHint != -1) gd.heightHint= spanHeightHint; } public void setDefaultGridData(GridData gd, int index) { if (index >= fDefaultGridDatas.length) { GridData[] newDatas= new GridData[index + 4]; System.arraycopy(fDefaultGridDatas, 0, newDatas, 0, fDefaultGridDatas.length); fDefaultGridDatas= newDatas; } fDefaultGridDatas[index]= gd; } public GridData getGridData(int index) { if (index > fDefaultGridDatas.length) return null; return cloneGridData(fDefaultGridDatas[index]); } public int numColumns() { return fNumColumns; } protected void order(Control[] controls) { if (!fOrder) return; for (int i= 0; i < controls.length; i++) { Control control= controls[i]; control.moveBelow(fLastControl); fLastControl= control; } } protected GridData cloneGridData(GridData gd) { if (gd == null) return null; GridData result= new GridData(); result.horizontalAlignment= gd.horizontalAlignment; result.grabExcessHorizontalSpace= gd.grabExcessHorizontalSpace; result.horizontalSpan= gd.horizontalSpan; result.horizontalIndent= gd.horizontalIndent; result.widthHint= gd.widthHint; result.verticalAlignment= gd.verticalAlignment; result.grabExcessVerticalSpace= gd.grabExcessVerticalSpace; result.verticalSpan= gd.verticalSpan; result.heightHint= gd.heightHint; return result; } }
epl-1.0
RallySoftware/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/ConversionManager.java
3140
/******************************************************************************* * Copyright (c) 2013, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Blaise Doughan - 2.6 - initial implementation ******************************************************************************/ package org.eclipse.persistence.internal.oxm; import javax.xml.namespace.QName; import org.eclipse.persistence.internal.core.queries.CoreContainerPolicy; import org.eclipse.persistence.internal.core.sessions.CoreAbstractSession; import org.eclipse.persistence.internal.oxm.record.AbstractUnmarshalRecord; public interface ConversionManager { public String buildBase64StringFromBytes(byte[] bytes); public QName buildQNameFromString(String stringValue, AbstractUnmarshalRecord record); /** * Removes all leading and trailing whitespaces, and replaces any sequences of whitespaces * that occur in the string with a single ' ' character. * @since EclipseLink 2.6.0 */ public String collapseStringValue(String value); /** * Convert the given object to the appropriate type by invoking the appropriate * ConversionManager method. * * @param sourceObject - will always be a string if read from XML * @param javaClass - the class that the object must be converted to * @param schemaTypeQName - the XML schema that the object is being converted from * @return - the newly converted object */ public Object convertObject(Object sourceObject, Class javaClass, QName schemaTypeQName); /** * @since EclipseLink 2.6.0 */ public Object convertSchemaBase64ListToByteArrayList(Object sourceObject, CoreContainerPolicy containerPolicy, CoreAbstractSession session); public Object convertHexBinaryListToByteArrayList(Object sourceObject, CoreContainerPolicy containerPolicy, CoreAbstractSession session); /** * INTERNAL: * Converts a String which is in Base64 format to a Byte[] */ public byte[] convertSchemaBase64ToByteArray(Object sourceObject); /** * @since EclipseLink 2.6.0 * @param schemaType The type you want to find a corresponding Java class for. * @return the Java class for the XML schema type. */ public Class<?> javaType(QName schemaType); /** * Replaces any CR, Tab or LF characters in the string with a single ' ' character. * @since EclipseLink 2.6.0 */ public String normalizeStringValue(String value); /** * @since EclipseLink 2.6.0 * @param javaType The type you want to find a corresponding schema type for. * @return the schema type for the Java class. */ public QName schemaType(Class<?> javaType); }
epl-1.0
RallySoftware/eclipselink.runtime
foundation/eclipselink.extension.nosql.test/src/org/eclipse/persistence/testing/tests/eis/cobol/SimpleCobolParsingTest.java
2098
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.tests.eis.cobol; import java.io.*; import java.util.*; import org.eclipse.persistence.internal.eis.cobol.*; import org.eclipse.persistence.testing.framework.*; public class SimpleCobolParsingTest extends CobolTest { Vector records; public SimpleCobolParsingTest() { super(); } public String description() { return "This test parses a simple Cobol Copybook, and checks that the parser builds the " + "appropriate hierarchical record field structure."; } protected void test() { ByteArrayInputStream inputStream = new ByteArrayInputStream(CobolTestModel.getSimpleCopyBookString().getBytes()); CopyBookParser parser = new CopyBookParser(); try { records = parser.parse(inputStream); } catch (Exception exception) { TestErrorException testException = new TestErrorException(exception.getMessage()); setTestException(testException); } } protected void verify() throws TestException { RecordMetaData record = (RecordMetaData)records.firstElement(); if (!CobolTestModel.compareCompositeObjects(record, CobolTestModel.getSimpleRecord())) { TestErrorException exception = new TestErrorException("The records do not match."); setTestException(exception); } } }
epl-1.0
RallySoftware/eclipselink.runtime
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/unmarshaller/space/TestObject.java
1329
/******************************************************************************* * Copyright (c) 2012, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Denise Smith - 2.4 - January 2012 ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.unmarshaller.space; import java.util.List; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class TestObject { public String theString; @XmlAnyElement public List<Object> theAny; public boolean equals(Object theObject){ if(theObject instanceof TestObject){ if(theString == null){ return ((TestObject)theObject).theString == null; } return theString.equals(((TestObject)theObject).theString); } return false; } }
epl-1.0
tx1103mark/controller
opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/Runtime.java
4559
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.config.facade.xml.runtime; import com.google.common.base.Optional; import com.google.common.collect.HashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.management.ObjectName; import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; import org.opendaylight.controller.config.facade.xml.mapping.config.Config; import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig; import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver; import org.opendaylight.controller.config.util.xml.XmlMappingConstants; import org.opendaylight.controller.config.util.xml.XmlUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Runtime { private final Map<String, Map<String, ModuleRuntime>> moduleRuntimes; private final Map<String, Map<String, ModuleConfig>> moduleConfigs; public Runtime(Map<String, Map<String, ModuleRuntime>> moduleRuntimes, Map<String, Map<String, ModuleConfig>> moduleConfigs) { this.moduleRuntimes = moduleRuntimes; this.moduleConfigs = moduleConfigs; } private Map<String, Multimap<String, ObjectName>> mapInstancesToModules(Set<ObjectName> instancesToMap) { Map<String, Multimap<String, ObjectName>> retVal = Maps.newHashMap(); // TODO map to namepsace, prevent module name conflicts // this code does not support same module names from different namespaces // Namespace should be present in ObjectName for (ObjectName objectName : instancesToMap) { String moduleName = ObjectNameUtil.getFactoryName(objectName); Multimap<String, ObjectName> multimap = retVal.get(moduleName); if (multimap == null) { multimap = HashMultimap.create(); retVal.put(moduleName, multimap); } String instanceName = ObjectNameUtil.getInstanceName(objectName); multimap.put(instanceName, objectName); } return retVal; } public Element toXml(Set<ObjectName> instancesToMap, Set<ObjectName> configBeans, Document document, final EnumResolver enumResolver) { Element root = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent()); Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY, Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG)); root.appendChild(modulesElement); Map<String, Multimap<String, ObjectName>> moduleToRuntimeInstance = mapInstancesToModules(instancesToMap); Map<String, Map<String, Collection<ObjectName>>> moduleToConfigInstance = Config .getMappedInstances(configBeans, moduleConfigs); for (String localNamespace : moduleConfigs.keySet()) { Map<String, Collection<ObjectName>> instanceToMbe = moduleToConfigInstance.get(localNamespace); for (String moduleName : moduleConfigs.get(localNamespace).keySet()) { Multimap<String, ObjectName> instanceToRbe = moduleToRuntimeInstance.get(moduleName); for (ObjectName instanceON : instanceToMbe.get(moduleName)) { String instanceName = ObjectNameUtil.getInstanceName(instanceON); Element runtimeXml; ModuleConfig moduleConfig = moduleConfigs.get(localNamespace).get(moduleName); if(instanceToRbe==null || !instanceToRbe.containsKey(instanceName)) { runtimeXml = moduleConfig.toXml(instanceON, document, localNamespace, enumResolver); } else { ModuleRuntime moduleRuntime = moduleRuntimes.get(localNamespace).get(moduleName); runtimeXml = moduleRuntime.toXml(localNamespace, instanceToRbe.get(instanceName), document, moduleConfig, instanceON, enumResolver); } modulesElement.appendChild(runtimeXml); } } } return root; } }
epl-1.0
RallySoftware/eclipselink.runtime
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/direct/DirectMappingXmlValueTestCases.java
3762
/******************************************************************************* * Copyright (c) 2011, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dmccann - January 28/2010 - 2.1 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.externalizedmetadata.mappings.direct; import java.io.InputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases; public class DirectMappingXmlValueTestCases extends JAXBWithJSONTestCases { private static final String XML_RESOURCE = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/direct/price.xml"; private static final String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/direct/price.json"; private static final String CURRENCY = "CAD"; private static final double PRICE = 123.456; public DirectMappingXmlValueTestCases(String name) throws Exception { super(name); setControlDocument(XML_RESOURCE); setControlJSON(JSON_RESOURCE); setClasses(new Class[]{Price.class}); } public Map getProperties(){ InputStream inputStream = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/direct/eclipselink-oxm-xml-value.xml"); HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>(); metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.mappings.direct", new StreamSource(inputStream)); Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>(); properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap); return properties; } public void testSchemaGen() throws Exception{ List controlSchemas = new ArrayList(); InputStream is = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/direct/price.xsd"); controlSchemas.add(is); super.testSchemaGen(controlSchemas); InputStream srcInputStream = ClassLoader.getSystemResourceAsStream(XML_RESOURCE); InputStream schemaInputStream = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/jaxb/externalizedmetadata/mappings/direct/price.xsd"); String result = validateAgainstSchema(srcInputStream, new StreamSource(schemaInputStream)); assertTrue("Instance doc validation (price.xml) failed unxepectedly: " + result, result == null); } public Object getWriteControlObject() { Price ctrlPrice = new Price(); ctrlPrice.currency = CURRENCY; ctrlPrice.price = new BigDecimal(PRICE); return ctrlPrice; } protected Object getControlObject() { Price ctrlPrice = new Price(); ctrlPrice.currency = CURRENCY; return ctrlPrice; } public void testRoundTrip(){ //not applicable with write only mappings } }
epl-1.0
clanko8285/openhab
bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/converter/ZWaveThermostatFanStateConverter.java
3917
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.zwave.internal.converter; import java.util.Map; import org.openhab.binding.zwave.internal.converter.state.BigDecimalDecimalTypeConverter; import org.openhab.binding.zwave.internal.converter.state.ZWaveStateConverter; import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.ZWaveController; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveThermostatFanStateCommandClass; import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent; import org.openhab.core.events.EventPublisher; import org.openhab.core.items.Item; import org.openhab.core.types.Command; import org.openhab.core.types.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ZWaveThermostatFanStateConverter class. Converter for communication with the * {@link ZWaveThermostatFanStateCommandClass}. Implements polling of the fan * state and receiving of fan state events. * @author Dan Cunningham * @since 1.6.0 */ public class ZWaveThermostatFanStateConverter extends ZWaveCommandClassConverter<ZWaveThermostatFanStateCommandClass> { private static final Logger logger = LoggerFactory.getLogger(ZWaveThermostatFanStateConverter.class); private static final int REFRESH_INTERVAL = 0; // refresh interval in seconds for the thermostat setpoint; /** * Constructor. Creates a new instance of the {@link ZWaveThermostatFanStateConverter} class. * @param controller the {@link ZWaveController} to use for sending messages. * @param eventPublisher the {@link EventPublisher} to use to publish events. */ public ZWaveThermostatFanStateConverter(ZWaveController controller, EventPublisher eventPublisher) { super(controller, eventPublisher); this.addStateConverter(new BigDecimalDecimalTypeConverter()); } /** * {@inheritDoc} */ @Override void executeRefresh(ZWaveNode node, ZWaveThermostatFanStateCommandClass commandClass, int endpointId, Map<String, String> arguments) { logger.debug("NODE {}: Generating poll message for {} endpoint {}", node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId); SerialMessage serialMessage = node.encapsulate(commandClass.getValueMessage(), commandClass, endpointId); if (serialMessage == null) { logger.warn("NODE {}: Generating message failed for command class = {}, endpoint = {}", node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId); return; } this.getController().sendData(serialMessage); } /** * {@inheritDoc} */ @Override void handleEvent(ZWaveCommandClassValueEvent event, Item item, Map<String, String> arguments) { ZWaveStateConverter<?,?> converter = this.getStateConverter(item, event.getValue()); if (converter == null) { logger.warn("NODE {}: No converter found for item = {} endpoint = {}, ignoring event.", event.getNodeId(), item.getName(),event.getEndpoint()); return; } State state = converter.convertFromValueToState(event.getValue()); this.getEventPublisher().postUpdate(item.getName(), state); } /** * {@inheritDoc} */ @Override void receiveCommand(Item item, Command command, ZWaveNode node, ZWaveThermostatFanStateCommandClass commandClass, int endpointId, Map<String, String> arguments) { logger.warn("NODE {}: We do not take commands: item = {} endpoint = {}, ignoring.", node.getNodeId(), item.getName(),endpointId); } /** * {@inheritDoc} */ @Override int getRefreshInterval() { return REFRESH_INTERVAL; } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.lametrictime/src/3rdparty/java/org/openhab/binding/lametrictime/api/model/Icons.java
3140
/** * Copyright 2017-2018 Gregory Moyer and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openhab.binding.lametrictime.api.model; import java.io.File; import java.net.URI; import java.nio.file.Path; import org.openhab.binding.lametrictime.api.impl.DataIcon; import org.openhab.binding.lametrictime.api.impl.FileIcon; import org.openhab.binding.lametrictime.api.impl.HTTPIcon; import org.openhab.binding.lametrictime.api.impl.KeyIcon; public class Icons { public static Icon key(String key) { return new KeyIcon(key); } public static Icon http(String uri) { return http(URI.create(uri)); } public static Icon http(URI uri) { return new HTTPIcon(uri); } public static Icon path(Path path) { return new FileIcon(path); } public static Icon file(File file) { return new FileIcon(file); } public static Icon data(String mimeType, byte[] data) { return new DataIcon(mimeType, data); } // @formatter:off public static Icon dollar() { return key("i34"); } public static Icon gmail() { return key("i43"); } public static Icon confirm() { return key("i59"); } public static Icon goOut() { return key("a68"); } public static Icon dog() { return key("a76"); } public static Icon clock() { return key("a82"); } public static Icon smile() { return key("a87"); } public static Icon lightning() { return key("i95"); } public static Icon facebook() { return key("a128"); } public static Icon home() { return key("i96"); } public static Icon girl() { return key("a178"); } public static Icon stop() { return key("i184"); } public static Icon heart() { return key("a230"); } public static Icon fade() { return key("a273"); } public static Icon terminal() { return key("a315"); } public static Icon usa() { return key("a413"); } public static Icon switzerland() { return key("i469"); } public static Icon attention() { return key("i555"); } public static Icon theMatrix() { return key("a653"); } public static Icon pizza() { return key("i1324"); } public static Icon christmasTree() { return key("a1782"); } public static Icon night() { return key("a2285"); } public static Icon fireworks() { return key("a2867"); } public static Icon beer() { return key("i3253"); } public static Icon tetris() { return key("a3793"); } public static Icon halloween() { return key("a4033"); } public static Icon pacman() { return key("a4584"); } private Icons() {} // @formatter:on }
epl-1.0
anish/buildbot
master/buildbot/test/unit/test_mq_base.py
1901
# This file is part of Buildbot. Buildbot 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, version 2. # # 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, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import mock from twisted.internet import defer from twisted.python import failure from twisted.trial import unittest from buildbot.mq import base class QueueRef(unittest.TestCase): def test_success(self): cb = mock.Mock(name='cb') qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') def test_success_deferred(self): cb = mock.Mock(name='cb') cb.return_value = defer.succeed(None) qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') def test_exception(self): cb = mock.Mock(name='cb') cb.side_effect = RuntimeError('oh noes!') qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1) def test_failure(self): cb = mock.Mock(name='cb') cb.return_value = defer.fail(failure.Failure(RuntimeError('oh noes!'))) qref = base.QueueRef(cb) qref.invoke('rk', 'd') cb.assert_called_with('rk', 'd') self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)
gpl-2.0
jo-sf/joomla-cms
tests/unit/suites/libraries/joomla/session/storage/JSessionStorageApcTest.php
2068
<?php /** * @package Joomla.UnitTest * @subpackage Session * * @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Test class for JSessionStorageApc. * * @since 11.1 */ class JSessionStorageApcTest extends \PHPUnit\Framework\TestCase { /** * @var JSessionStorageApc */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { parent::setUp(); // Skip these tests if APC isn't available. if (!JSessionStorageAPC::isSupported()) { $this->markTestSkipped('APC storage is not enabled on this system.'); } $this->object = JSessionStorage::getInstance('APC'); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void */ protected function tearDown() { } /** * Test... * * @todo Implement testRead(). * * @return void */ public function testRead() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testWrite(). * * @return void */ public function testWrite() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testDestroy(). * * @return void */ public function testDestroy() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testIsSupported(). * * @return void */ public function testIsSupported() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } }
gpl-2.0
Distrotech/icedtea7-2.3
test/jtreg/com/sun/javatest/exec/JavaTestContextMenu.java
5948
/* * $Id$ * * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.javatest.exec; import javax.swing.JMenuItem; import com.sun.javatest.TestResult; /** * Class to encapsulate a custom context menu item to be added to the GUI by a * test suite. The method <code>getMenuApplication</code> determines which type * of situations the menu should be presented in. Processing the actual selection * action event for the menu item(s) should be processed as you normally would * with the Swing-provided Action mechanisms. * * All methods in this API will be invoked on the GUI event thread. */ public abstract class JavaTestContextMenu { /** * Create a new instance, based on this instance. The purpose of this is to allow * this menu item to appear in multiple places in the interface. */ public abstract JavaTestContextMenu newInstance(); /** * Get the actual component for this menu. A single menu item is * recommended, but a it may also be a submenu. The reference returned * should not change after this method has been invoked the first time. * This allows for lazy initialization, but then permits caching by the * client of the API. * @return A menu to be displayed to the user. Must never be null. */ public abstract JMenuItem getMenu(); /** * Determine the contexts in which this menu is applicable. Unless the value * is set to <code>CUSTOM</code>, the system managing the menus assumes that * it is allowed to control the enabled/disabled state of the menu item. * @see #TESTS_AND_FOLDERS * @see #TESTS_ONLY * @see #FOLDERS_ONLY * @see #CUSTOM */ public abstract int getMenuApplication(); /** * May multiple nodes be selected at one time for this menu item to be * enabled. If not allowed and multiple items are currently selected, * updateState() methods will not be called. The default state of this * setting is <code>false</code>, override this method to change. * * If you need to enable/disabled based on the composition of the selection, * you should return <code>true</code>, then override <code>updateState(String[], * TestResult[])</code> and disable if needed. * @return True if multiselect is permitted for this menu action. False * otherwise. */ public boolean isMultiSelectAllowed() { return false; } /** * Called upon when a test is selected by the user. This callback allows the * implementation to dynamically adjust it's state. It is recommended that * this method remain unimplemented unless really needed, since it is * processed synchonously on the event thread. It is critical that the * implementation of this method be reasonably fast and non-blocking * because it will may be invoked each time the user requests a popup to be * displayed. * * Implementations which return <code>CUSTOM</code> from * <code>getMenuApplication</code> will generally override this. This method * is called regardless of what application type the object indicates. * * The controlling class will first enable/disable the menu based on the * application type (unless <code>CUSTOM</code>). * * This method will be invoked on the GUI event thread. * @param tr The test result object which the users is acting upon. */ public void updateState(TestResult tr) { } /** * Called upon when a folder is selected by the user. It is in * canonical internal form - forward slash seperated. * * This method will be invoked on the GUI event thread. * @param path */ public void updateState(String path) { } /** * Called upon when multiple items have been selected by the user. The union * of the two parameters represents the leafs selected by the user to act upon. * The intersection of those two parameters is empty. * * This method will be invoked on the GUI event thread. * @param paths The test paths which the user is acting upon, only the folders. * The strings are forward slash seperated locations within the * test suite, a substring of that which would be returned by * <code>TestDescription.getRootRelativeURL()</code>. Null if * none. * @param trs The tests which the user is acting upon. Null if none. * @see TestDescription#getRootRelativeURL */ public void updateState(String[] folders, TestResult[] trs) { } public static final int TESTS_AND_FOLDERS = 0; public static final int TESTS_ONLY = 1; public static final int FOLDERS_ONLY = 2; public static final int CUSTOM = 99; }
gpl-2.0
gtt116/zabbix
frontends/php/include/views/configuration.triggers.edit.php
13109
<?php /* ** Zabbix ** Copyright (C) 2001-2015 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__).'/js/configuration.triggers.edit.js.php'; $triggersWidget = new CWidget(); // append host summary to widget header if (!empty($this->data['hostid'])) { if (!empty($this->data['parent_discoveryid'])) { $triggersWidget->addItem(get_header_host_table('triggers', $this->data['hostid'], $this->data['parent_discoveryid'])); } else { $triggersWidget->addItem(get_header_host_table('triggers', $this->data['hostid'])); } } if (!empty($this->data['parent_discoveryid'])) { $triggersWidget->addPageHeader(_('CONFIGURATION OF TRIGGER PROTOTYPES')); } else { $triggersWidget->addPageHeader(_('CONFIGURATION OF TRIGGERS')); } // create form $triggersForm = new CForm(); $triggersForm->setName('triggersForm'); $triggersForm->addVar('form', $this->data['form']); $triggersForm->addVar('hostid', $this->data['hostid']); $triggersForm->addVar('parent_discoveryid', $this->data['parent_discoveryid']); $triggersForm->addVar('input_method', $this->data['input_method']); $triggersForm->addVar('toggle_input_method', ''); $triggersForm->addVar('remove_expression', ''); if (!empty($this->data['triggerid'])) { $triggersForm->addVar('triggerid', $this->data['triggerid']); } // create form list $triggersFormList = new CFormList('triggersFormList'); if (!empty($this->data['templates'])) { $triggersFormList->addRow(_('Parent triggers'), $this->data['templates']); } $nameTextBox = new CTextBox('description', $this->data['description'], ZBX_TEXTBOX_STANDARD_SIZE, $this->data['limited']); $nameTextBox->attr('autofocus', 'autofocus'); $triggersFormList->addRow(_('Name'), $nameTextBox); // append expression to form list $expressionTextBox = new CTextArea( $this->data['expression_field_name'], $this->data['expression_field_value'], array( 'rows' => ZBX_TEXTAREA_STANDARD_ROWS, 'width' => ZBX_TEXTAREA_STANDARD_WIDTH, 'readonly' => $this->data['expression_field_readonly'] ) ); if ($this->data['expression_field_readonly']) { $triggersForm->addVar('expression', $this->data['expression']); } $addExpressionButton = new CButton( 'insert', ($this->data['input_method'] == IM_TREE) ? _('Edit') : _('Add'), 'return PopUp("popup_trexpr.php?dstfrm='.$triggersForm->getName(). '&dstfld1='.$this->data['expression_field_name'].'&srctbl=expression'.url_param('parent_discoveryid'). '&srcfld1=expression&expression=" + encodeURIComponent(jQuery(\'[name="'.$this->data['expression_field_name'].'"]\').val()), 800, 265);', 'formlist' ); if ($this->data['limited']) { $addExpressionButton->setAttribute('disabled', 'disabled'); } $expressionRow = array($expressionTextBox, $addExpressionButton); if ($this->data['input_method'] == IM_TREE) { // insert macro button $insertMacroButton = new CButton('insert_macro', _('Insert expression'), null, 'formlist'); $insertMacroButton->setMenuPopup(CMenuPopupHelper::getTriggerMacro()); if ($this->data['limited']) { $insertMacroButton->setAttribute('disabled', 'disabled'); } $expressionRow[] = $insertMacroButton; array_push($expressionRow, BR()); if (empty($this->data['outline'])) { // add button $addExpressionButton = new CSubmit('add_expression', _('Add'), null, 'formlist'); if ($this->data['limited']) { $addExpressionButton->setAttribute('disabled', 'disabled'); } array_push($expressionRow, $addExpressionButton); } else { // add button $addExpressionButton = new CSubmit('and_expression', _('And'), null, 'formlist'); if ($this->data['limited']) { $addExpressionButton->setAttribute('disabled', 'disabled'); } array_push($expressionRow, $addExpressionButton); // or button $orExpressionButton = new CSubmit('or_expression', _('Or'), null, 'formlist'); if ($this->data['limited']) { $orExpressionButton->setAttribute('disabled', 'disabled'); } array_push($expressionRow, $orExpressionButton); // replace button $replaceExpressionButton = new CSubmit('replace_expression', _('Replace'), null, 'formlist'); if ($this->data['limited']) { $replaceExpressionButton->setAttribute('disabled', 'disabled'); } array_push($expressionRow, $replaceExpressionButton); } } elseif ($this->data['input_method'] != IM_FORCED) { $inputMethodToggle = new CSpan(_('Expression constructor'), 'link'); $inputMethodToggle->setAttribute('onclick', 'javascript: '. 'document.getElementById("toggle_input_method").value=1;'. 'document.getElementById("input_method").value='.(($this->data['input_method'] == IM_TREE) ? IM_ESTABLISHED : IM_TREE).';'. 'document.forms["'.$triggersForm->getName().'"].submit();' ); $expressionRow[] = array(BR(), $inputMethodToggle); } $triggersFormList->addRow(_('Expression'), $expressionRow); // append expression table to form list if ($this->data['input_method'] == IM_TREE) { $expressionTable = new CTable(null, 'formElementTable'); $expressionTable->setAttribute('style', 'min-width: 500px;'); $expressionTable->setAttribute('id', 'exp_list'); $expressionTable->setOddRowClass('even_row'); $expressionTable->setEvenRowClass('even_row'); $expressionTable->setHeader(array( $this->data['limited'] ? null : _('Target'), _('Expression'), empty($this->data['parent_discoveryid']) ? _('Error') : null, $this->data['limited'] ? null : _('Action') )); $allowedTesting = true; if (!empty($this->data['eHTMLTree'])) { foreach ($this->data['eHTMLTree'] as $i => $e) { if (!$this->data['limited']) { $deleteUrl = new CSpan(_('Delete'), 'link'); $deleteUrl->setAttribute('onclick', 'javascript:'. ' if (confirm('.CJs::encodeJson(_('Delete expression?')).')) {'. ' delete_expression("'.$e['id'] .'");'. ' document.forms["'.$triggersForm->getName().'"].submit();'. ' }' ); $triggerCheckbox = new CCheckBox('expr_target_single', ($i == 0) ? 'yes' : 'no', 'check_target(this);', $e['id']); } else { $triggerCheckbox = null; } if (empty($this->data['parent_discoveryid'])) { if (!isset($e['expression']['levelErrors'])) { $errorImg = new CImg('images/general/ok_icon.png', 'expression_no_errors'); $errorImg->setHint(_('No errors found.')); } else { $allowedTesting = false; $errorImg = new CImg('images/general/error2.png', 'expression_errors'); $errorTexts = array(); if (is_array($e['expression']['levelErrors'])) { foreach ($e['expression']['levelErrors'] as $expVal => $errTxt) { if (count($errorTexts) > 0) { array_push($errorTexts, BR()); } array_push($errorTexts, $expVal, ':', $errTxt); } } $errorImg->setHint($errorTexts, 'left'); } $errorColumn = new CCol($errorImg, 'center'); } else { $errorColumn = null; } // templated trigger if ($this->data['limited']) { // make all links inside inactive $listSize = count($e['list']); for ($i = 0; $i < $listSize; $i++) { if (gettype($e['list'][$i]) == 'object' && get_class($e['list'][$i]) == 'CSpan' && $e['list'][$i]->getAttribute('class') == 'link') { $e['list'][$i]->removeAttribute('class'); $e['list'][$i]->setAttribute('onclick', ''); } } } $row = new CRow(array($triggerCheckbox, $e['list'], $errorColumn, isset($deleteUrl) ? $deleteUrl : null)); $expressionTable->addRow($row); } } else { $allowedTesting = false; $this->data['outline'] = ''; } $testButton = new CButton('test_expression', _('Test'), 'openWinCentered("tr_testexpr.php?expression=" + encodeURIComponent(this.form.elements["expression"].value),'. '"ExpressionTest", 850, 400, "titlebar=no, resizable=yes, scrollbars=yes"); return false;', 'link_menu' ); if (!$allowedTesting) { $testButton->setAttribute('disabled', 'disabled'); } if (empty($this->data['outline'])) { $testButton->setAttribute('disabled', 'disabled'); } $wrapOutline = new CSpan(array($this->data['outline'])); $triggersFormList->addRow(SPACE, array( $wrapOutline, BR(), BR(), new CDiv(array($expressionTable, $testButton), 'objectgroup inlineblock border_dotted ui-corner-all') )); $inputMethodToggle = new CSpan(_('Close expression constructor'), 'link'); $inputMethodToggle->setAttribute('onclick', 'javascript: '. 'document.getElementById("toggle_input_method").value=1;'. 'document.getElementById("input_method").value='.IM_ESTABLISHED.';'. 'document.forms["'.$triggersForm->getName().'"].submit();' ); $triggersFormList->addRow(SPACE, array($inputMethodToggle, BR())); } $triggersFormList->addRow(_('Multiple PROBLEM events generation'), new CCheckBox('type', (($this->data['type'] == TRIGGER_MULT_EVENT_ENABLED) ? 'yes' : 'no'), null, 1)); $triggersFormList->addRow(_('Description'), new CTextArea('comments', $this->data['comments'])); $triggersFormList->addRow(_('URL'), new CTextBox('url', $this->data['url'], ZBX_TEXTBOX_STANDARD_SIZE)); $triggersFormList->addRow(_('Severity'), new CSeverity(array('name' => 'priority', 'value' => $this->data['priority']))); // append status to form list if (empty($this->data['triggerid']) && empty($this->data['form_refresh'])) { $status = 'yes'; } else { $status = ($this->data['status'] == 0) ? 'yes' : 'no'; } $triggersFormList->addRow(_('Enabled'), new CCheckBox('status', $status, null, 1)); // append tabs to form $triggersTab = new CTabView(); if (!$this->data['form_refresh']) { $triggersTab->setSelected(0); } $triggersTab->addTab( 'triggersTab', empty($this->data['parent_discoveryid']) ? _('Trigger') : _('Trigger prototype'), $triggersFormList ); /* * Dependencies tab */ if (empty($this->data['parent_discoveryid'])) { $dependenciesFormList = new CFormList('dependenciesFormList'); $dependenciesTable = new CTable(_('No dependencies defined.'), 'formElementTable'); $dependenciesTable->setAttribute('style', 'min-width: 500px;'); $dependenciesTable->setAttribute('id', 'dependenciesTable'); $dependenciesTable->setHeader(array(_('Name'), _('Action'))); foreach ($this->data['db_dependencies'] as $dependency) { $triggersForm->addVar('dependencies[]', $dependency['triggerid'], 'dependencies_'.$dependency['triggerid']); $hostNames = array(); foreach ($dependency['hosts'] as $host) { $hostNames[] = CHtml::encode($host['name']); $hostNames[] = ', '; } array_pop($hostNames); if ($dependency['flags'] == ZBX_FLAG_DISCOVERY_NORMAL) { $description = new CLink( array($hostNames, NAME_DELIMITER, CHtml::encode($dependency['description'])), 'triggers.php?form=update&hostid='.$dependency['hostid'].'&triggerid='.$dependency['triggerid'] ); $description->setAttribute('target', '_blank'); } else { $description = array($hostNames, NAME_DELIMITER, $dependency['description']); } $row = new CRow(array($description, new CButton('remove', _('Remove'), 'javascript: removeDependency("'.$dependency['triggerid'].'");', 'link_menu' ))); $row->setAttribute('id', 'dependency_'.$dependency['triggerid']); $dependenciesTable->addRow($row); } $dependenciesFormList->addRow( _('Dependencies'), new CDiv( array( $dependenciesTable, new CButton('bnt1', _('Add'), 'return PopUp("popup.php?'. 'srctbl=triggers'. '&srcfld1=triggerid'. '&reference=deptrigger'. '&multiselect=1'. '&with_triggers=1", 1000, 700);', 'link_menu' ) ), 'objectgroup inlineblock border_dotted ui-corner-all' ) ); $triggersTab->addTab('dependenciesTab', _('Dependencies'), $dependenciesFormList); } // append tabs to form $triggersForm->addItem($triggersTab); // append buttons to form if (!empty($this->data['triggerid'])) { $deleteButton = new CButtonDelete( $this->data['parent_discoveryid'] ? _('Delete trigger prototype?') : _('Delete trigger?'), url_params(array('form', 'groupid', 'hostid', 'triggerid', 'parent_discoveryid')) ); if ($this->data['limited']) { $deleteButton->setAttribute('disabled', 'disabled'); } $triggersForm->addItem(makeFormFooter( new CSubmit('update', _('Update')), array( new CSubmit('clone', _('Clone')), $deleteButton, new CButtonCancel(url_params(array('groupid', 'hostid', 'parent_discoveryid'))) ) )); } else { $triggersForm->addItem(makeFormFooter( new CSubmit('add', _('Add')), new CButtonCancel(url_params(array('groupid', 'hostid', 'parent_discoveryid'))) )); } $triggersWidget->addItem($triggersForm); return $triggersWidget;
gpl-2.0
yxl/emscripten-calligra-mobile
plugins/musicshape/core/Staff.cpp
7563
/* This file is part of the KDE project * Copyright (C) 2007 Marijn Kruisselbrink <mkruisselbrink@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "Staff.h" #include "Part.h" #include "Sheet.h" #include "Bar.h" #include "StaffElement.h" #include "Clef.h" #include "KeySignature.h" #include "TimeSignature.h" #include "Chord.h" #include "VoiceBar.h" #include "Note.h" #include <QMap> #include <math.h> #include <limits.h> namespace MusicCore { class Staff::Private { public: qreal spacing; int lineCount; qreal lineSpacing; }; Staff::Staff(Part* part) : QObject(part), d(new Private) { d->spacing = 60; d->lineCount = 5; d->lineSpacing = 5.0; } Staff::~Staff() { delete d; } Part* Staff::part() { return qobject_cast<Part*>(parent()); } qreal Staff::spacing() const { return d->spacing; } void Staff::setSpacing(qreal spacing) { if (d->spacing == spacing) return; d->spacing = spacing; emit spacingChanged(spacing); } qreal Staff::top() { if (!part()) return 0; int n = 0; for (int i = 0; i < part()->sheet()->partCount(); i++) { Part* p = part()->sheet()->part(i); if (p != part()) n += p->staffCount(); else break; } for (int i = 0; i < part()->staffCount(); i++) { if (part()->staff(i) == this) return 30 + 50 * (n+i); } return 30; } qreal Staff::bottom() { return top() + lineSpacing() * (lineCount() - 1); } qreal Staff::center() { return (top() + bottom()) / 2; } int Staff::lineCount() const { return d->lineCount; } void Staff::setLineCount(int lineCount) { if (d->lineCount == lineCount) return; d->lineCount = lineCount; emit lineCountChanged(lineCount); } qreal Staff::lineSpacing() const { return d->lineSpacing; } void Staff::setLineSpacing(qreal lineSpacing) { if (d->lineSpacing == lineSpacing) return; d->lineSpacing = lineSpacing; emit lineSpacingChanged(lineSpacing); } int Staff::line(qreal y) const { y = (lineCount()-1) * lineSpacing() - y; y /= lineSpacing() / 2; return qRound(y); } Clef* Staff::lastClefChange(int bar, int time, Clef* oldClef) { if (!part()) return NULL; if (time < 0) time = INT_MAX; for (int b = bar; b >= 0; b--) { Bar* curBar = part()->sheet()->bar(b); for (int i = curBar->staffElementCount(this)-1; i >= 0; i--) { StaffElement* e = curBar->staffElement(this, i); if (e->startTime() <= time) { Clef* c = dynamic_cast<Clef*>(e); if (c) return c; } } if (oldClef) return oldClef; time = INT_MAX; } return 0; } Clef* Staff::lastClefChange(Bar* bar, int time, Clef* oldClef) { return lastClefChange(part()->sheet()->indexOfBar(bar), time, oldClef); } KeySignature* Staff::lastKeySignatureChange(int bar) { if (!part()) return NULL; for (int b = bar; b >= 0; b--) { Bar* curBar = part()->sheet()->bar(b); for (int i = curBar->staffElementCount(this)-1; i >= 0; i--) { StaffElement* e = curBar->staffElement(this, i); KeySignature* ks = dynamic_cast<KeySignature*>(e); if (ks) return ks; } } return 0; } KeySignature* Staff::lastKeySignatureChange(Bar* bar) { return lastKeySignatureChange(part()->sheet()->indexOfBar(bar)); } TimeSignature* Staff::lastTimeSignatureChange(int bar) { if (!part()) return NULL; for (int b = bar; b >= 0; b--) { Bar* curBar = part()->sheet()->bar(b); for (int i = curBar->staffElementCount(this)-1; i >= 0; i--) { StaffElement* e = curBar->staffElement(this, i); TimeSignature* ts = dynamic_cast<TimeSignature*>(e); if (ts) return ts; } } return 0; } TimeSignature* Staff::lastTimeSignatureChange(Bar* bar) { return lastTimeSignatureChange(part()->sheet()->indexOfBar(bar)); } void Staff::updateAccidentals(int fromBar) { KeySignature* ks = lastKeySignatureChange(fromBar); for (int barIdx = fromBar, barCount = part()->sheet()->barCount(); barIdx < barCount; barIdx++) { Bar* bar = part()->sheet()->bar(barIdx); // process key signature changes in this bar for (int i = 0; i < bar->staffElementCount(this); i++) { StaffElement* e = bar->staffElement(this, i); KeySignature* curks = dynamic_cast<KeySignature*>(e); if (curks) { ks = curks; } } // current accidentals for all notes with pitches from -40..40 // curAccidentals[pitch+40]; value is #accidentals + 100 (so 0 means no notes seen yet, use the keysig) int curAccidentals[81] = {0}; // and a map for all other pitches (there shouldn't be much anyway) QMap<int, int> accidentalsMap; // now loop over all notes in all voices in this bar, and check if they are in this staff // if they are, set accidentals visibility and update current accidentals for (int v = 0; v < part()->voiceCount(); v++) { Voice* voice = part()->voice(v); VoiceBar* vb = bar->voice(voice); for (int e = 0; e < vb->elementCount(); e++) { Chord* c = dynamic_cast<Chord*>(vb->element(e)); if (!c) continue; for (int nid = 0; nid < c->noteCount(); nid++) { Note* note = c->note(nid); if (note->staff() != this) continue; int pitch = note->pitch(); int cur = 0; if (pitch >= -40 && pitch <= 40) { cur = curAccidentals[pitch+40]; if (cur == 0 && ks) { cur = ks->accidentals(pitch); } else { cur -= 100; } curAccidentals[pitch+40] = note->accidentals() + 100; } else { if (accidentalsMap.contains(pitch)) { cur = accidentalsMap[pitch]; } else if (ks) { cur = ks->accidentals(pitch); } else { cur = 0; } accidentalsMap[pitch] = note->accidentals(); } note->setDrawAccidentals(note->accidentals() != cur); } } } } } void Staff::updateAccidentals(Bar* fromBar) { Q_ASSERT( fromBar ); updateAccidentals( part()->sheet()->indexOfBar(fromBar) ); } } // namespace MusicCore #include <Staff.moc>
gpl-2.0
md-5/jdk10
test/langtools/tools/javac/processing/model/util/elements/TestGetModuleOf.java
3698
/* * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8230337 * @summary Test Elements.getModuleOf * @library /tools/javac/lib * @modules java.compiler * jdk.compiler * @build JavacTestingAbstractProcessor TestGetModuleOf * @compile -processor TestGetModuleOf -proc:only TestGetModuleOf.java * @compile -processor TestGetModuleOf -proc:only -source 8 -Xlint:-options TestGetModuleOf.java */ // Also run test under -source 8 to test old behavior pre-modules. import java.util.*; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import static javax.lang.model.SourceVersion.*; import javax.lang.model.element.*; import javax.lang.model.util.*; import static javax.lang.model.util.ElementFilter.*; import static javax.tools.Diagnostic.Kind.*; import static javax.tools.StandardLocation.*; /** * Test basic workings of Elements.getModuleOf */ public class TestGetModuleOf extends JavacTestingAbstractProcessor { /** * Check expected behavior on classes and packages and other elements. */ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!roundEnv.processingOver()) { TypeElement charElt = eltUtils.getTypeElement("java.lang.Character"); PackageElement javaLangPkg = eltUtils.getPackageElement("java.lang"); ModuleElement expectedMod = enclosingToModule(javaLangPkg); checkMod(charElt, expectedMod); checkMod(javaLangPkg, expectedMod); // The module of fields and methods and nested types of // java.lang.Character should match the module of // java.lang. for (Element e : charElt.getEnclosedElements()) { checkMod(e, expectedMod); } // A module of a module is itself if (expectedMod != null) checkMod(expectedMod, expectedMod); } return true; } private ModuleElement enclosingToModule(Element e) { Element enclosing = e.getEnclosingElement(); if (enclosing == null) return null; else return ElementFilter.modulesIn(List.of(enclosing)).get(0); } private void checkMod(Element e, ModuleElement expectedMod) { ModuleElement actualMod = eltUtils.getModuleOf(e); if (!Objects.equals(actualMod, expectedMod)) { throw new RuntimeException(String.format("Unexpected module ``%s''' for %s %s, expected ``%s''%n", actualMod, e.getKind(), e.toString(), expectedMod)); } } }
gpl-2.0
Lisergishnu/CodenameDarwinia
Assets/Plugins/AstarPathfindingProject/Modifiers/RaycastModifier.cs
4878
using UnityEngine; using System.Collections.Generic; using Pathfinding; namespace Pathfinding { /** Simplifies a path using raycasting. * \ingroup modifiers * This modifier will try to remove as many nodes as possible from the path using raycasting (linecasting) to validate the node removal. * Either graph raycasts or Physics.Raycast */ [AddComponentMenu ("Pathfinding/Modifiers/Raycast Simplifier")] [System.Serializable] public class RaycastModifier : MonoModifier { #if UNITY_EDITOR [UnityEditor.MenuItem ("CONTEXT/Seeker/Add Raycast Simplifier Modifier")] public static void AddComp (UnityEditor.MenuCommand command) { (command.context as Component).gameObject.AddComponent (typeof(RaycastModifier)); } #endif public override ModifierData input { get { return ModifierData.VectorPath | ModifierData.StrictVectorPath; } } public override ModifierData output { get { return ModifierData.VectorPath; } } [HideInInspector] public bool useRaycasting = true; [HideInInspector] public LayerMask mask = -1; [HideInInspector] public bool thickRaycast; [HideInInspector] public float thickRaycastRadius; [HideInInspector] public Vector3 raycastOffset = Vector3.zero; /* Use the exact points used to query the path. If false, the start and end points will be snapped to the node positions.*/ //public bool exactStartAndEnd = true; /* Ignore exact start and end points clamped by other modifiers. Other modifiers which modify the start and end points include for example the StartEndModifier. If enabled this modifier will ignore anything that modifier does when calculating the simplification.*/ //public bool overrideClampedExacts = false; [HideInInspector] public bool subdivideEveryIter; public int iterations = 2; /** Use raycasting on the graphs. Only currently works with GridGraph and NavmeshGraph and RecastGraph. \astarpro */ [HideInInspector] public bool useGraphRaycasting; /** To avoid too many memory allocations. An array is kept between the checks and filled in with the positions instead of allocating a new one every time.*/ private static List<Vector3> nodes; public override void Apply (Path p, ModifierData source) { //System.DateTime startTime = System.DateTime.UtcNow; if (iterations <= 0) { return; } if (nodes == null) { nodes = new List<Vector3> (p.vectorPath.Count); } else { nodes.Clear (); } nodes.AddRange (p.vectorPath); // = new List<Vector3> (p.vectorPath); for (int it=0;it<iterations;it++) { if (subdivideEveryIter && it != 0) { if (nodes.Capacity < nodes.Count*3) { nodes.Capacity = nodes.Count*3; } int preLength = nodes.Count; for (int j=0;j<preLength-1;j++) { nodes.Add (Vector3.zero); nodes.Add (Vector3.zero); } for (int j=preLength-1;j > 0;j--) { Vector3 p1 = nodes[j]; Vector3 p2 = nodes[j+1]; nodes[j*3] = nodes[j]; if (j != preLength-1) { nodes[j*3+1] = Vector3.Lerp (p1,p2,0.33F); nodes[j*3+2] = Vector3.Lerp (p1,p2,0.66F); } } } int i = 0; while (i < nodes.Count-2) { Vector3 start = nodes[i]; Vector3 end = nodes[i+2]; var watch = System.Diagnostics.Stopwatch.StartNew(); if (ValidateLine (null,null,start,end)) { nodes.RemoveAt (i+1); } else { i++; } watch.Stop (); } } p.vectorPath.Clear (); p.vectorPath.AddRange (nodes); } /** Check if a straight path between v1 and v2 is valid */ public bool ValidateLine (GraphNode n1, GraphNode n2, Vector3 v1, Vector3 v2) { if (useRaycasting) { // Use raycasting to check if a straight path between v1 and v2 is valid if (thickRaycast && thickRaycastRadius > 0) { RaycastHit hit; if (Physics.SphereCast (v1+raycastOffset, thickRaycastRadius,v2-v1,out hit, (v2-v1).magnitude,mask)) { return false; } } else { RaycastHit hit; if (Physics.Linecast (v1+raycastOffset,v2+raycastOffset,out hit, mask)) { return false; } } } if (useGraphRaycasting && n1 == null) { n1 = AstarPath.active.GetNearest (v1).node; n2 = AstarPath.active.GetNearest (v2).node; } if (useGraphRaycasting && n1 != null && n2 != null) { // Use graph raycasting to check if a straight path between v1 and v2 is valid NavGraph graph = AstarData.GetGraph (n1); NavGraph graph2 = AstarData.GetGraph (n2); if (graph != graph2) { return false; } if (graph != null) { var rayGraph = graph as IRaycastableGraph; if (rayGraph != null) { if (rayGraph.Linecast (v1,v2, n1)) { return false; } } } } return true; } } }
gpl-2.0
popazerty/openblackhole-SH4
lib/python/Plugins/SystemPlugins/SoftwareManager/BackupRestore.py
20796
from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Screens.Console import Console from Screens.Standby import TryQuitMainloop from Components.ActionMap import ActionMap, NumberActionMap from Components.Pixmap import Pixmap from Tools.LoadPixmap import LoadPixmap from Components.Label import Label from Components.Sources.StaticText import StaticText from Components.MenuList import MenuList from Components.Sources.List import List from Components.Button import Button from Components.config import getConfigListEntry, configfile, ConfigSelection, ConfigSubsection, ConfigText, ConfigLocations from Components.config import config from Components.ConfigList import ConfigList,ConfigListScreen from Components.FileList import MultiFileSelectList from Components.Network import iNetwork from Plugins.Plugin import PluginDescriptor from enigma import eTimer, eEnv, eConsoleAppContainer from Tools.Directories import * from os import system, popen, path, makedirs, listdir, access, stat, rename, remove, W_OK, R_OK from time import gmtime, strftime, localtime, sleep from datetime import date from boxbranding import getBoxType, getMachineBrand, getMachineName boxtype = getBoxType() config.plugins.configurationbackup = ConfigSubsection() if boxtype in ('maram9', 'classm', 'axodin', 'axodinc', 'starsatlx', 'genius', 'evo', 'galaxym6') and not path.exists("/media/hdd/backup_%s" %boxtype): config.plugins.configurationbackup.backuplocation = ConfigText(default = '/media/backup/', visible_width = 50, fixed_size = False) else: config.plugins.configurationbackup.backuplocation = ConfigText(default = '/media/hdd/', visible_width = 50, fixed_size = False) config.plugins.configurationbackup.backupdirs = ConfigLocations(default=[eEnv.resolve('${sysconfdir}/enigma2/'), '/etc/CCcam.cfg', '/usr/keys/', '/etc/network/interfaces', '/etc/wpa_supplicant.conf', '/etc/wpa_supplicant.ath0.conf', '/etc/wpa_supplicant.wlan0.conf', '/etc/resolv.conf', '/etc/default_gw', '/etc/hostname', eEnv.resolve("${datadir}/enigma2/keymap.usr")]) def getBackupPath(): backuppath = config.plugins.configurationbackup.backuplocation.value if backuppath.endswith('/'): return backuppath + 'backup_' + boxtype else: return backuppath + '/backup_' + boxtype def getOldBackupPath(): backuppath = config.plugins.configurationbackup.backuplocation.value if backuppath.endswith('/'): return backuppath + 'backup' else: return backuppath + '/backup' def getBackupFilename(): return "enigma2settingsbackup.tar.gz" def SettingsEntry(name, checked): if checked: picture = LoadPixmap(cached = True, path = resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/lock_on.png")); else: picture = LoadPixmap(cached = True, path = resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/lock_off.png")); return (name, picture, checked) class BackupScreen(Screen, ConfigListScreen): skin = """ <screen position="135,144" size="350,310" title="Backup is running" > <widget name="config" position="10,10" size="330,250" transparent="1" scrollbarMode="showOnDemand" /> </screen>""" def __init__(self, session, runBackup = False): Screen.__init__(self, session) self.session = session self.runBackup = runBackup self["actions"] = ActionMap(["WizardActions", "DirectionActions"], { "ok": self.close, "back": self.close, "cancel": self.close, }, -1) self.finished_cb = None self.backuppath = getBackupPath() self.backupfile = getBackupFilename() self.fullbackupfilename = self.backuppath + "/" + self.backupfile self.list = [] ConfigListScreen.__init__(self, self.list) self.onLayoutFinish.append(self.layoutFinished) if self.runBackup: self.onShown.append(self.doBackup) def layoutFinished(self): self.setWindowTitle() def setWindowTitle(self): self.setTitle(_("Backup is running...")) def doBackup(self): configfile.save() try: if path.exists(self.backuppath) == False: makedirs(self.backuppath) self.backupdirs = ' '.join( config.plugins.configurationbackup.backupdirs.value ) if not "/tmp/installed-list.txt" in self.backupdirs: self.backupdirs = self.backupdirs + " /tmp/installed-list.txt" if not "/tmp/changed-configfiles.txt" in self.backupdirs: self.backupdirs = self.backupdirs + " /tmp/changed-configfiles.txt" cmd1 = "ipkg list-installed | egrep 'enigma2-plugin-|task-base|packagegroup-base' > /tmp/installed-list.txt" cmd2 = "ipkg list-changed-conffiles > /tmp/changed-configfiles.txt" cmd3 = "tar -czvf " + self.fullbackupfilename + " " + self.backupdirs cmd = [cmd1, cmd2, cmd3] if path.exists(self.fullbackupfilename): dt = str(date.fromtimestamp(stat(self.fullbackupfilename).st_ctime)) self.newfilename = self.backuppath + "/" + dt + '-' + self.backupfile if path.exists(self.newfilename): remove(self.newfilename) rename(self.fullbackupfilename,self.newfilename) if self.finished_cb: self.session.openWithCallback(self.finished_cb, Console, title = _("Backup is running..."), cmdlist = cmd,finishedCallback = self.backupFinishedCB,closeOnSuccess = True) else: self.session.open(Console, title = _("Backup is running..."), cmdlist = cmd,finishedCallback = self.backupFinishedCB, closeOnSuccess = True) except OSError: if self.finished_cb: self.session.openWithCallback(self.finished_cb, MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10 ) else: self.session.openWithCallback(self.backupErrorCB,MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10 ) def backupFinishedCB(self,retval = None): self.close(True) def backupErrorCB(self,retval = None): self.close(False) def runAsync(self, finished_cb): self.finished_cb = finished_cb self.doBackup() class BackupSelection(Screen): skin = """ <screen name="BackupSelection" position="center,center" size="560,400" title="Select files/folders to backup"> <ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="checkList" position="5,50" size="550,250" transparent="1" scrollbarMode="showOnDemand" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Save")) self["key_yellow"] = StaticText() self.selectedFiles = config.plugins.configurationbackup.backupdirs.value defaultDir = '/' inhibitDirs = ["/bin", "/boot", "/dev", "/autofs", "/lib", "/proc", "/sbin", "/sys", "/hdd", "/tmp", "/mnt", "/media"] self.filelist = MultiFileSelectList(self.selectedFiles, defaultDir, inhibitDirs = inhibitDirs ) self["checkList"] = self.filelist self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ShortcutActions"], { "cancel": self.exit, "red": self.exit, "yellow": self.changeSelectionState, "green": self.saveSelection, "ok": self.okClicked, "left": self.left, "right": self.right, "down": self.down, "up": self.up }, -1) if not self.selectionChanged in self["checkList"].onSelectionChanged: self["checkList"].onSelectionChanged.append(self.selectionChanged) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): idx = 0 self["checkList"].moveToIndex(idx) self.setWindowTitle() self.selectionChanged() def setWindowTitle(self): self.setTitle(_("Select files/folders to backup")) def selectionChanged(self): current = self["checkList"].getCurrent()[0] if current[2] is True: self["key_yellow"].setText(_("Deselect")) else: self["key_yellow"].setText(_("Select")) def up(self): self["checkList"].up() def down(self): self["checkList"].down() def left(self): self["checkList"].pageUp() def right(self): self["checkList"].pageDown() def changeSelectionState(self): self["checkList"].changeSelectionState() self.selectedFiles = self["checkList"].getSelectedList() def saveSelection(self): self.selectedFiles = self["checkList"].getSelectedList() config.plugins.configurationbackup.backupdirs.setValue(self.selectedFiles) config.plugins.configurationbackup.backupdirs.save() config.plugins.configurationbackup.save() config.save() self.close(None) def exit(self): self.close(None) def okClicked(self): if self.filelist.canDescent(): self.filelist.descent() class RestoreMenu(Screen): skin = """ <screen name="RestoreMenu" position="center,center" size="560,400" title="Restore backups" > <ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" /> <ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" /> <widget name="filelist" position="5,50" size="550,230" scrollbarMode="showOnDemand" /> </screen>""" def __init__(self, session, plugin_path): Screen.__init__(self, session) self.skin_path = plugin_path self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Restore")) self["key_yellow"] = StaticText(_("Delete")) self.sel = [] self.val = [] self.entry = False self.exe = False self.path = "" self["actions"] = NumberActionMap(["SetupActions"], { "ok": self.KeyOk, "cancel": self.keyCancel }, -1) self["shortcuts"] = ActionMap(["ShortcutActions"], { "red": self.keyCancel, "green": self.KeyOk, "yellow": self.deleteFile, }) self.flist = [] self["filelist"] = MenuList(self.flist) self.fill_list() self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setWindowTitle() def setWindowTitle(self): self.setTitle(_("Restore backups")) def fill_list(self): self.flist = [] self.path = getBackupPath() if path.exists(self.path) == False: makedirs(self.path) for file in listdir(self.path): if file.endswith(".tar.gz"): self.flist.append(file) self.entry = True self.flist.sort(reverse=True) self["filelist"].l.setList(self.flist) def KeyOk(self): if (self.exe == False) and (self.entry == True): self.sel = self["filelist"].getCurrent() if self.sel: self.val = self.path + "/" + self.sel self.session.openWithCallback(self.startRestore, MessageBox, _("Are you sure you want to restore\nthe following backup:\n%s\nYour receiver will restart after the backup has been restored!") % self.sel) def keyCancel(self): self.close() def startRestore(self, ret = False): if ret == True: self.exe = True self.session.open(Console, title = _("Restoring..."), cmdlist = ["tar -xzvf " + self.path + "/" + self.sel + " -C /", "killall -9 enigma2"]) def deleteFile(self): if (self.exe == False) and (self.entry == True): self.sel = self["filelist"].getCurrent() if self.sel: self.val = self.path + "/" + self.sel self.session.openWithCallback(self.startDelete, MessageBox, _("Are you sure you want to delete\nthe following backup:\n") + self.sel) def startDelete(self, ret = False): if ret == True: self.exe = True print "removing:",self.val if path.exists(self.val) == True: remove(self.val) self.exe = False self.fill_list() class RestoreScreen(Screen, ConfigListScreen): skin = """ <screen position="135,144" size="350,310" title="Restore is running..." > <widget name="config" position="10,10" size="330,250" transparent="1" scrollbarMode="showOnDemand" /> </screen>""" def __init__(self, session, runRestore = False): Screen.__init__(self, session) self.session = session self.runRestore = runRestore self["actions"] = ActionMap(["WizardActions", "DirectionActions"], { "ok": self.close, "back": self.close, "cancel": self.close, }, -1) self.backuppath = getBackupPath() if not path.isdir(self.backuppath): self.backuppath = getOldBackupPath() self.backupfile = getBackupFilename() self.fullbackupfilename = self.backuppath + "/" + self.backupfile self.list = [] ConfigListScreen.__init__(self, self.list) self.onLayoutFinish.append(self.layoutFinished) if self.runRestore: self.onShown.append(self.doRestore) def layoutFinished(self): self.setWindowTitle() def setWindowTitle(self): self.setTitle(_("Restoring...")) def doRestore(self): if path.exists("/proc/stb/vmpeg/0/dst_width"): restorecmdlist = ["tar -xzvf " + self.fullbackupfilename + " -C /", "echo 0 > /proc/stb/vmpeg/0/dst_height", "echo 0 > /proc/stb/vmpeg/0/dst_left", "echo 0 > /proc/stb/vmpeg/0/dst_top", "echo 0 > /proc/stb/vmpeg/0/dst_width"] else: restorecmdlist = ["tar -xzvf " + self.fullbackupfilename + " -C /"] print"[SOFTWARE MANAGER] Restore Settings !!!!" self.session.open(Console, title = _("Restoring..."), cmdlist = restorecmdlist, finishedCallback = self.restoreFinishedCB) def restoreFinishedCB(self,retval = None): self.session.openWithCallback(self.checkPlugins, RestartNetwork) def checkPlugins(self): if path.exists("/tmp/installed-list.txt"): self.session.openWithCallback(self.restartGUI, installedPlugins) else: self.restartGUI() def restartGUI(self, ret = None): self.session.open(Console, title = _("Your %s %s will Reboot...")% (getMachineBrand(), getMachineName()), cmdlist = ["init 4;reboot"]) def runAsync(self, finished_cb): self.doRestore() class RestartNetwork(Screen): def __init__(self, session): Screen.__init__(self, session) skin = """ <screen name="RestartNetwork" position="center,center" size="600,100" title="Restart Network Adapter"> <widget name="label" position="10,30" size="500,50" halign="center" font="Regular;20" transparent="1" foregroundColor="white" /> </screen> """ self.skin = skin self["label"] = Label(_("Please wait while your network is restarting...")) self.onShown.append(self.setWindowTitle) self.onLayoutFinish.append(self.restartLan) def setWindowTitle(self): self.setTitle(_("Restart Network Adapter")) def restartLan(self): print"[SOFTWARE MANAGER] Restart Network" iNetwork.restartNetwork(self.restartLanDataAvail) def restartLanDataAvail(self, data): if data is True: iNetwork.getInterfaces(self.getInterfacesDataAvail) def getInterfacesDataAvail(self, data): self.close() class installedPlugins(Screen): UPDATE = 0 LIST = 1 skin = """ <screen position="center,center" size="600,100" title="Install Plugins" > <widget name="label" position="10,30" size="570,50" halign="center" font="Regular;20" transparent="1" foregroundColor="white" /> <widget name="filelist" position="5,50" size="550,230" scrollbarMode="showOnDemand" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Install Plugins")) self["label"] = Label(_("Please wait while we check your installed plugins...")) self.type = self.UPDATE self.container = eConsoleAppContainer() self.container.appClosed.append(self.runFinished) self.container.dataAvail.append(self.dataAvail) self.remainingdata = "" self.pluginsInstalled = [] self.doUpdate() def doUpdate(self): print"[SOFTWARE MANAGER] update package list" self.container.execute("ipkg update") def doList(self): print"[SOFTWARE MANAGER] read installed package list" self.container.execute("ipkg list-installed | egrep 'enigma2-plugin-|task-base|packagegroup-base'") def dataAvail(self, strData): if self.type == self.LIST: strData = self.remainingdata + strData lines = strData.split('\n') if len(lines[-1]): self.remainingdata = lines[-1] lines = lines[0:-1] else: self.remainingdata = "" for x in lines: self.pluginsInstalled.append(x[:x.find(' - ')]) def runFinished(self, retval): if self.type == self.UPDATE: self.type = self.LIST self.doList() elif self.type == self.LIST: self.readPluginList() def readPluginList(self): self.PluginList = [] f = open("/tmp/installed-list.txt", "r") lines = f.readlines() for x in lines: self.PluginList.append(x[:x.find(' - ')]) f.close() self.createMenuList() def createMenuList(self): self.Menulist = [] for x in self.PluginList: if x not in self.pluginsInstalled: self.Menulist.append(SettingsEntry(x , True)) if len(self.Menulist) == 0: self.close() else: if os.path.exists("/media/hdd/images/config/plugins") and config.misc.firstrun.value: self.startInstall(True) else: self.session.openWithCallback(self.startInstall, MessageBox, _("Backup plugins found\ndo you want to install now?")) def startInstall(self, ret = None): if ret: self.session.openWithCallback(self.restoreCB, RestorePlugins, self.Menulist) else: self.close() def restoreCB(self, ret = None): self.close() class RestorePlugins(Screen): def __init__(self, session, menulist): Screen.__init__(self, session) Screen.setTitle(self, _("Restore Plugins")) self.index = 0 self.list = menulist self.container = eConsoleAppContainer() self["menu"] = List(list()) self["menu"].onSelectionChanged.append(self.selectionChanged) self["key_green"] = Button(_("Install")) self["key_red"] = Button(_("Cancel")) self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], { "red": self.exit, "green": self.green, "cancel": self.exit, "ok": self.ok }, -2) self["menu"].setList(menulist) self["menu"].setIndex(self.index) self.selectionChanged() self.onShown.append(self.setWindowTitle) def setWindowTitle(self): self.setTitle(_("Restore Plugins")) def exit(self): self.close() def green(self): pluginlist = [] self.myipklist = [] for x in self.list: if x[2]: myipk = self.SearchIPK(x[0]) if myipk: self.myipklist.append(myipk) else: pluginlist.append(x[0]) if len(pluginlist) > 0: if len(self.myipklist) > 0: self.session.open(Console, title = _("Installing plugins..."), cmdlist = ['ipkg --force-overwrite install ' + ' '.join(pluginlist)], finishedCallback = self.installLocalIPK, closeOnSuccess = True) else: self.session.open(Console, title = _("Installing plugins..."), cmdlist = ['ipkg --force-overwrite install ' + ' '.join(pluginlist)], finishedCallback = self.exit, closeOnSuccess = True) elif len(self.myipklist) > 0: self.installLocalIPK() def installLocalIPK(self): self.session.open(Console, title = _("Installing plugins..."), cmdlist = ['ipkg --force-overwrite install ' + ' '.join(self.myipklist)], finishedCallback = self.exit, closeOnSuccess = True) def ok(self): index = self["menu"].getIndex() item = self["menu"].getCurrent()[0] state = self["menu"].getCurrent()[2] if state: self.list[index] = SettingsEntry(item , False) else: self.list[index] = SettingsEntry(item, True) self["menu"].setList(self.list) self["menu"].setIndex(index) def selectionChanged(self): index = self["menu"].getIndex() if index == None: index = 0 self.index = index def drawList(self): self["menu"].setList(self.Menulist) self["menu"].setIndex(self.index) def exitNoPlugin(self, ret): self.close() def SearchIPK(self, ipkname): ipkname = ipkname + "*" search_dirs = [ "/media/hdd", "/media/usb" ] sdirs = " ".join(search_dirs) cmd = 'find %s -name "%s" | head -n 1' % (sdirs, ipkname) res = popen(cmd).read() if res == "": return None else: return res.replace("\n", "")
gpl-2.0
Taichi-SHINDO/jdk9-jdk
src/java.desktop/share/classes/java/awt/image/LookupOp.java
22973
/* * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt.image; import java.awt.color.ColorSpace; import java.awt.geom.Rectangle2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.Point2D; import sun.awt.image.ImagingLib; /** * This class implements a lookup operation from the source * to the destination. The LookupTable object may contain a single array * or multiple arrays, subject to the restrictions below. * <p> * For Rasters, the lookup operates on bands. The number of * lookup arrays may be one, in which case the same array is * applied to all bands, or it must equal the number of Source * Raster bands. * <p> * For BufferedImages, the lookup operates on color and alpha components. * The number of lookup arrays may be one, in which case the * same array is applied to all color (but not alpha) components. * Otherwise, the number of lookup arrays may * equal the number of Source color components, in which case no * lookup of the alpha component (if present) is performed. * If neither of these cases apply, the number of lookup arrays * must equal the number of Source color components plus alpha components, * in which case lookup is performed for all color and alpha components. * This allows non-uniform rescaling of multi-band BufferedImages. * <p> * BufferedImage sources with premultiplied alpha data are treated in the same * manner as non-premultiplied images for purposes of the lookup. That is, * the lookup is done per band on the raw data of the BufferedImage source * without regard to whether the data is premultiplied. If a color conversion * is required to the destination ColorModel, the premultiplied state of * both source and destination will be taken into account for this step. * <p> * Images with an IndexColorModel cannot be used. * <p> * If a RenderingHints object is specified in the constructor, the * color rendering hint and the dithering hint may be used when color * conversion is required. * <p> * This class allows the Source to be the same as the Destination. * * @see LookupTable * @see java.awt.RenderingHints#KEY_COLOR_RENDERING * @see java.awt.RenderingHints#KEY_DITHERING */ public class LookupOp implements BufferedImageOp, RasterOp { private LookupTable ltable; private int numComponents; RenderingHints hints; /** * Constructs a <code>LookupOp</code> object given the lookup * table and a <code>RenderingHints</code> object, which might * be <code>null</code>. * @param lookup the specified <code>LookupTable</code> * @param hints the specified <code>RenderingHints</code>, * or <code>null</code> */ public LookupOp(LookupTable lookup, RenderingHints hints) { this.ltable = lookup; this.hints = hints; numComponents = ltable.getNumComponents(); } /** * Returns the <code>LookupTable</code>. * @return the <code>LookupTable</code> of this * <code>LookupOp</code>. */ public final LookupTable getTable() { return ltable; } /** * Performs a lookup operation on a <code>BufferedImage</code>. * If the color model in the source image is not the same as that * in the destination image, the pixels will be converted * in the destination. If the destination image is <code>null</code>, * a <code>BufferedImage</code> will be created with an appropriate * <code>ColorModel</code>. An <code>IllegalArgumentException</code> * might be thrown if the number of arrays in the * <code>LookupTable</code> does not meet the restrictions * stated in the class comment above, or if the source image * has an <code>IndexColorModel</code>. * @param src the <code>BufferedImage</code> to be filtered * @param dst the <code>BufferedImage</code> in which to * store the results of the filter operation * @return the filtered <code>BufferedImage</code>. * @throws IllegalArgumentException if the number of arrays in the * <code>LookupTable</code> does not meet the restrictions * described in the class comments, or if the source image * has an <code>IndexColorModel</code>. */ public final BufferedImage filter(BufferedImage src, BufferedImage dst) { ColorModel srcCM = src.getColorModel(); int numBands = srcCM.getNumColorComponents(); ColorModel dstCM; if (srcCM instanceof IndexColorModel) { throw new IllegalArgumentException("LookupOp cannot be "+ "performed on an indexed image"); } int numComponents = ltable.getNumComponents(); if (numComponents != 1 && numComponents != srcCM.getNumComponents() && numComponents != srcCM.getNumColorComponents()) { throw new IllegalArgumentException("Number of arrays in the "+ " lookup table ("+ numComponents+ " is not compatible with the "+ " src image: "+src); } boolean needToConvert = false; int width = src.getWidth(); int height = src.getHeight(); if (dst == null) { dst = createCompatibleDestImage(src, null); dstCM = srcCM; } else { if (width != dst.getWidth()) { throw new IllegalArgumentException("Src width ("+width+ ") not equal to dst width ("+ dst.getWidth()+")"); } if (height != dst.getHeight()) { throw new IllegalArgumentException("Src height ("+height+ ") not equal to dst height ("+ dst.getHeight()+")"); } dstCM = dst.getColorModel(); if (srcCM.getColorSpace().getType() != dstCM.getColorSpace().getType()) { needToConvert = true; dst = createCompatibleDestImage(src, null); } } BufferedImage origDst = dst; if (ImagingLib.filter(this, src, dst) == null) { // Do it the slow way WritableRaster srcRaster = src.getRaster(); WritableRaster dstRaster = dst.getRaster(); if (srcCM.hasAlpha()) { if (numBands-1 == numComponents || numComponents == 1) { int minx = srcRaster.getMinX(); int miny = srcRaster.getMinY(); int[] bands = new int[numBands-1]; for (int i=0; i < numBands-1; i++) { bands[i] = i; } srcRaster = srcRaster.createWritableChild(minx, miny, srcRaster.getWidth(), srcRaster.getHeight(), minx, miny, bands); } } if (dstCM.hasAlpha()) { int dstNumBands = dstRaster.getNumBands(); if (dstNumBands-1 == numComponents || numComponents == 1) { int minx = dstRaster.getMinX(); int miny = dstRaster.getMinY(); int[] bands = new int[numBands-1]; for (int i=0; i < numBands-1; i++) { bands[i] = i; } dstRaster = dstRaster.createWritableChild(minx, miny, dstRaster.getWidth(), dstRaster.getHeight(), minx, miny, bands); } } filter(srcRaster, dstRaster); } if (needToConvert) { // ColorModels are not the same ColorConvertOp ccop = new ColorConvertOp(hints); ccop.filter(dst, origDst); } return origDst; } /** * Performs a lookup operation on a <code>Raster</code>. * If the destination <code>Raster</code> is <code>null</code>, * a new <code>Raster</code> will be created. * The <code>IllegalArgumentException</code> might be thrown * if the source <code>Raster</code> and the destination * <code>Raster</code> do not have the same * number of bands or if the number of arrays in the * <code>LookupTable</code> does not meet the * restrictions stated in the class comment above. * @param src the source <code>Raster</code> to filter * @param dst the destination <code>WritableRaster</code> for the * filtered <code>src</code> * @return the filtered <code>WritableRaster</code>. * @throws IllegalArgumentException if the source and destinations * rasters do not have the same number of bands, or the * number of arrays in the <code>LookupTable</code> does * not meet the restrictions described in the class comments. * */ public final WritableRaster filter (Raster src, WritableRaster dst) { int numBands = src.getNumBands(); int dstLength = dst.getNumBands(); int height = src.getHeight(); int width = src.getWidth(); int srcPix[] = new int[numBands]; // Create a new destination Raster, if needed if (dst == null) { dst = createCompatibleDestRaster(src); } else if (height != dst.getHeight() || width != dst.getWidth()) { throw new IllegalArgumentException ("Width or height of Rasters do not "+ "match"); } dstLength = dst.getNumBands(); if (numBands != dstLength) { throw new IllegalArgumentException ("Number of channels in the src (" + numBands + ") does not match number of channels" + " in the destination (" + dstLength + ")"); } int numComponents = ltable.getNumComponents(); if (numComponents != 1 && numComponents != src.getNumBands()) { throw new IllegalArgumentException("Number of arrays in the "+ " lookup table ("+ numComponents+ " is not compatible with the "+ " src Raster: "+src); } if (ImagingLib.filter(this, src, dst) != null) { return dst; } // Optimize for cases we know about if (ltable instanceof ByteLookupTable) { byteFilter ((ByteLookupTable) ltable, src, dst, width, height, numBands); } else if (ltable instanceof ShortLookupTable) { shortFilter ((ShortLookupTable) ltable, src, dst, width, height, numBands); } else { // Not one we recognize so do it slowly int sminX = src.getMinX(); int sY = src.getMinY(); int dminX = dst.getMinX(); int dY = dst.getMinY(); for (int y=0; y < height; y++, sY++, dY++) { int sX = sminX; int dX = dminX; for (int x=0; x < width; x++, sX++, dX++) { // Find data for all bands at this x,y position src.getPixel(sX, sY, srcPix); // Lookup the data for all bands at this x,y position ltable.lookupPixel(srcPix, srcPix); // Put it back for all bands dst.setPixel(dX, dY, srcPix); } } } return dst; } /** * Returns the bounding box of the filtered destination image. Since * this is not a geometric operation, the bounding box does not * change. * @param src the <code>BufferedImage</code> to be filtered * @return the bounds of the filtered definition image. */ public final Rectangle2D getBounds2D (BufferedImage src) { return getBounds2D(src.getRaster()); } /** * Returns the bounding box of the filtered destination Raster. Since * this is not a geometric operation, the bounding box does not * change. * @param src the <code>Raster</code> to be filtered * @return the bounds of the filtered definition <code>Raster</code>. */ public final Rectangle2D getBounds2D (Raster src) { return src.getBounds(); } /** * Creates a zeroed destination image with the correct size and number of * bands. If destCM is <code>null</code>, an appropriate * <code>ColorModel</code> will be used. * @param src Source image for the filter operation. * @param destCM the destination's <code>ColorModel</code>, which * can be <code>null</code>. * @return a filtered destination <code>BufferedImage</code>. */ public BufferedImage createCompatibleDestImage (BufferedImage src, ColorModel destCM) { BufferedImage image; int w = src.getWidth(); int h = src.getHeight(); int transferType = DataBuffer.TYPE_BYTE; if (destCM == null) { ColorModel cm = src.getColorModel(); Raster raster = src.getRaster(); if (cm instanceof ComponentColorModel) { DataBuffer db = raster.getDataBuffer(); boolean hasAlpha = cm.hasAlpha(); boolean isPre = cm.isAlphaPremultiplied(); int trans = cm.getTransparency(); int[] nbits = null; if (ltable instanceof ByteLookupTable) { if (db.getDataType() == DataBuffer.TYPE_USHORT) { // Dst raster should be of type byte if (hasAlpha) { nbits = new int[2]; if (trans == java.awt.Transparency.BITMASK) { nbits[1] = 1; } else { nbits[1] = 8; } } else { nbits = new int[1]; } nbits[0] = 8; } // For byte, no need to change the cm } else if (ltable instanceof ShortLookupTable) { transferType = DataBuffer.TYPE_USHORT; if (db.getDataType() == DataBuffer.TYPE_BYTE) { if (hasAlpha) { nbits = new int[2]; if (trans == java.awt.Transparency.BITMASK) { nbits[1] = 1; } else { nbits[1] = 16; } } else { nbits = new int[1]; } nbits[0] = 16; } } if (nbits != null) { cm = new ComponentColorModel(cm.getColorSpace(), nbits, hasAlpha, isPre, trans, transferType); } } image = new BufferedImage(cm, cm.createCompatibleWritableRaster(w, h), cm.isAlphaPremultiplied(), null); } else { image = new BufferedImage(destCM, destCM.createCompatibleWritableRaster(w, h), destCM.isAlphaPremultiplied(), null); } return image; } /** * Creates a zeroed-destination <code>Raster</code> with the * correct size and number of bands, given this source. * @param src the <code>Raster</code> to be transformed * @return the zeroed-destination <code>Raster</code>. */ public WritableRaster createCompatibleDestRaster (Raster src) { return src.createCompatibleWritableRaster(); } /** * Returns the location of the destination point given a * point in the source. If <code>dstPt</code> is not * <code>null</code>, it will be used to hold the return value. * Since this is not a geometric operation, the <code>srcPt</code> * will equal the <code>dstPt</code>. * @param srcPt a <code>Point2D</code> that represents a point * in the source image * @param dstPt a <code>Point2D</code>that represents the location * in the destination * @return the <code>Point2D</code> in the destination that * corresponds to the specified point in the source. */ public final Point2D getPoint2D (Point2D srcPt, Point2D dstPt) { if (dstPt == null) { dstPt = new Point2D.Float(); } dstPt.setLocation(srcPt.getX(), srcPt.getY()); return dstPt; } /** * Returns the rendering hints for this op. * @return the <code>RenderingHints</code> object associated * with this op. */ public final RenderingHints getRenderingHints() { return hints; } private final void byteFilter(ByteLookupTable lookup, Raster src, WritableRaster dst, int width, int height, int numBands) { int[] srcPix = null; // Find the ref to the table and the offset byte[][] table = lookup.getTable(); int offset = lookup.getOffset(); int tidx; int step=1; // Check if it is one lookup applied to all bands if (table.length == 1) { step=0; } int x; int y; int band; int len = table[0].length; // Loop through the data for ( y=0; y < height; y++) { tidx = 0; for ( band=0; band < numBands; band++, tidx+=step) { // Find data for this band, scanline srcPix = src.getSamples(0, y, width, 1, band, srcPix); for ( x=0; x < width; x++) { int index = srcPix[x]-offset; if (index < 0 || index > len) { throw new IllegalArgumentException("index ("+index+ "(out of range: "+ " srcPix["+x+ "]="+ srcPix[x]+ " offset="+ offset); } // Do the lookup srcPix[x] = table[tidx][index]; } // Put it back dst.setSamples(0, y, width, 1, band, srcPix); } } } private final void shortFilter(ShortLookupTable lookup, Raster src, WritableRaster dst, int width, int height, int numBands) { int band; int[] srcPix = null; // Find the ref to the table and the offset short[][] table = lookup.getTable(); int offset = lookup.getOffset(); int tidx; int step=1; // Check if it is one lookup applied to all bands if (table.length == 1) { step=0; } int x = 0; int y = 0; int index; int maxShort = (1<<16)-1; // Loop through the data for (y=0; y < height; y++) { tidx = 0; for ( band=0; band < numBands; band++, tidx+=step) { // Find data for this band, scanline srcPix = src.getSamples(0, y, width, 1, band, srcPix); for ( x=0; x < width; x++) { index = srcPix[x]-offset; if (index < 0 || index > maxShort) { throw new IllegalArgumentException("index out of range "+ index+" x is "+x+ "srcPix[x]="+srcPix[x] +" offset="+ offset); } // Do the lookup srcPix[x] = table[tidx][index]; } // Put it back dst.setSamples(0, y, width, 1, band, srcPix); } } } }
gpl-2.0
md-5/jdk10
src/hotspot/share/utilities/elfFile.hpp
6279
/* * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_UTILITIES_ELFFILE_HPP #define SHARE_UTILITIES_ELFFILE_HPP #if !defined(_WINDOWS) && !defined(__APPLE__) && !defined(_AIX) #if defined(__OpenBSD__) #include <sys/exec_elf.h> #else #include <elf.h> #endif #include <stdio.h> #ifdef _LP64 typedef Elf64_Half Elf_Half; typedef Elf64_Word Elf_Word; typedef Elf64_Off Elf_Off; typedef Elf64_Addr Elf_Addr; typedef Elf64_Ehdr Elf_Ehdr; typedef Elf64_Shdr Elf_Shdr; typedef Elf64_Phdr Elf_Phdr; typedef Elf64_Sym Elf_Sym; #if !defined(_ALLBSD_SOURCE) || defined(__APPLE__) #define ELF_ST_TYPE ELF64_ST_TYPE #endif #else typedef Elf32_Half Elf_Half; typedef Elf32_Word Elf_Word; typedef Elf32_Off Elf_Off; typedef Elf32_Addr Elf_Addr; typedef Elf32_Ehdr Elf_Ehdr; typedef Elf32_Shdr Elf_Shdr; typedef Elf32_Phdr Elf_Phdr; typedef Elf32_Sym Elf_Sym; #if !defined(_ALLBSD_SOURCE) || defined(__APPLE__) #define ELF_ST_TYPE ELF32_ST_TYPE #endif #endif #include "globalDefinitions.hpp" #include "memory/allocation.hpp" #include "utilities/decoder.hpp" class ElfStringTable; class ElfSymbolTable; class ElfFuncDescTable; // ELF section, may or may not have cached data class ElfSection { private: Elf_Shdr _section_hdr; void* _section_data; NullDecoder::decoder_status _stat; public: ElfSection(FILE* fd, const Elf_Shdr& hdr); ~ElfSection(); NullDecoder::decoder_status status() const { return _stat; } const Elf_Shdr* section_header() const { return &_section_hdr; } const void* section_data() const { return (const void*)_section_data; } private: // load this section. // it return no_error, when it fails to cache the section data due to lack of memory NullDecoder::decoder_status load_section(FILE* const file, const Elf_Shdr& hdr); }; class FileReader : public StackObj { protected: FILE* const _fd; public: FileReader(FILE* const fd) : _fd(fd) {}; bool read(void* buf, size_t size); int read_buffer(void* buf, size_t size); bool set_position(long offset); }; // Mark current position, so we can get back to it after // reads. class MarkedFileReader : public FileReader { private: long _marked_pos; public: MarkedFileReader(FILE* const fd); ~MarkedFileReader(); bool has_mark() const { return _marked_pos >= 0; } }; // ElfFile is basically an elf file parser, which can lookup the symbol // that is the nearest to the given address. // Beware, this code is called from vm error reporting code, when vm is already // in "error" state, so there are scenarios, lookup will fail. We want this // part of code to be very defensive, and bait out if anything went wrong. class ElfFile: public CHeapObj<mtInternal> { friend class ElfDecoder; private: // link ElfFiles ElfFile* _next; // Elf file char* _filepath; FILE* _file; // Elf header Elf_Ehdr _elfHdr; // symbol tables ElfSymbolTable* _symbol_tables; // regular string tables ElfStringTable* _string_tables; // section header string table, used for finding section name ElfStringTable* _shdr_string_table; // function descriptors table ElfFuncDescTable* _funcDesc_table; NullDecoder::decoder_status _status; public: ElfFile(const char* filepath); ~ElfFile(); bool decode(address addr, char* buf, int buflen, int* offset); const char* filepath() const { return _filepath; } bool same_elf_file(const char* filepath) const { assert(filepath != NULL, "null file path"); return (_filepath != NULL && !strcmp(filepath, _filepath)); } NullDecoder::decoder_status get_status() const { return _status; } // Returns true if the elf file is marked NOT to require an executable stack, // or if the file could not be opened. // Returns false if the elf file requires an executable stack, the stack flag // is not set at all, or if the file can not be read. // On systems other than linux it always returns false. static bool specifies_noexecstack(const char* filepath) NOT_LINUX({ return false; }); private: // sanity check, if the file is a real elf file static bool is_elf_file(Elf_Ehdr&); // parse this elf file NullDecoder::decoder_status parse_elf(const char* filename); // load string, symbol and function descriptor tables from the elf file NullDecoder::decoder_status load_tables(); ElfFile* next() const { return _next; } void set_next(ElfFile* file) { _next = file; } // find a section by name, return section index // if there is no such section, return -1 int section_by_name(const char* name, Elf_Shdr& hdr); // string tables are stored in a linked list void add_string_table(ElfStringTable* table); // symbol tables are stored in a linked list void add_symbol_table(ElfSymbolTable* table); // return a string table at specified section index ElfStringTable* get_string_table(int index); FILE* const fd() const { return _file; } // Cleanup string, symbol and function descriptor tables void cleanup_tables(); public: // For whitebox test static bool _do_not_cache_elf_section; }; #endif // !_WINDOWS && !__APPLE__ #endif // SHARE_UTILITIES_ELFFILE_HPP
gpl-2.0
Drupal8Todd/drupal8
core/modules/node/lib/Drupal/node/Plugin/views/argument/Type.php
863
<?php /** * @file * Definition of Drupal\node\Plugin\views\argument\Type. */ namespace Drupal\node\Plugin\views\argument; use Drupal\views\Plugin\views\argument\String; /** * Argument handler to accept a node type. * * @PluginID("node_type") */ class Type extends String { /** * Override the behavior of summaryName(). Get the user friendly version * of the node type. */ public function summaryName($data) { return $this->node_type($data->{$this->name_alias}); } /** * Override the behavior of title(). Get the user friendly version of the * node type. */ function title() { return $this->node_type($this->argument); } function node_type($type_name) { $type = entity_load('node_type', $type_name); $output = $type ? $type->label() : t('Unknown content type'); return check_plain($output); } }
gpl-2.0
iniverno/RnR-LLC
jgraph/scale.py
1300
#!/s/std/bin/python import sys, string, os, glob, re, mfgraph def gen_scale(benchmarks): configs = ["1p", "2p", "4p", "8p", "16p"] base_config = "1p" parameter = "Ruby_cycles" stacks = []; print "parsing..." for benchmark in benchmarks: assoc_data = {}; for config in configs: sys.stderr.write(" %s %s\n" % (benchmark, config)) numbers = [] filenames = glob.glob(benchmark + "/*-" + config + "-*.stats") for filename in filenames: lines = mfgraph.grep(filename, parameter); line = lines[0] numbers.append(float(string.split(line)[1])) med = mfgraph.median(numbers) assoc_data[config] = med; mfgraph.normalize(assoc_data, base_config) bars = [] stack_data = [benchmark] for config in configs: bars.append([config, assoc_data[config]]) stacks.append([benchmark] + bars) print "done." return [mfgraph.stacked_bar_graph(stacks, title = "Scalability", ylabel = "normalized runtime", colors = ["0 0 1"], patterns = ["solid"])]
gpl-2.0
gorgozilla/Estivole
templates/purity_iii/tpls/blog.php
1400
<?php /** *------------------------------------------------------------------------------ * @package T3 Framework for Joomla! *------------------------------------------------------------------------------ * @copyright Copyright (C) 2004-2017 JoomlArt.com. All Rights Reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @authors JoomlArt, JoomlaBamboo, (contribute to this project at github * & Google group to become co-author) * @Google group: https://groups.google.com/forum/#!forum/t3fw * @Link: http://t3-framework.org *------------------------------------------------------------------------------ */ $responsive = $this->getParam('responsive', 1); $resClass = ""; if ($responsive==0){ $resClass = "no-responsive"; } defined('_JEXEC') or die; ?> <!DOCTYPE html> <html lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>" class='<jdoc:include type="pageclass" /> <?php echo $resClass ?>'> <head> <jdoc:include type="head" /> <?php $this->loadBlock('head') ?> <?php $this->addCss('layouts/blog') ?> </head> <body> <div class="t3-wrapper blog"> <!-- Need this wrapper for off-canvas menu. Remove if you don't use of-canvas --> <?php $this->loadBlock('header') ?> <?php $this->loadBlock('mainbody') ?> <?php $this->loadBlock('footer') ?> </div> </body> </html>
gpl-2.0
BunnyWei/truffle-llvmir
graal/com.oracle.graal.jtt/src/com/oracle/graal/jtt/micro/Fibonacci.java
2186
/* * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.jtt.micro; import org.junit.*; import com.oracle.graal.jtt.*; /* */ public class Fibonacci extends JTTTest { public static int test(int num) { if (num <= 0) { return 0; } int n1 = 0; int n2 = 1; for (int i = 1; i < num; i++) { final int next = n2 + n1; n1 = n2; n2 = next; } return n2; } @Test public void run0() throws Throwable { runTest("test", 0); } @Test public void run1() throws Throwable { runTest("test", 1); } @Test public void run2() throws Throwable { runTest("test", 2); } @Test public void run3() throws Throwable { runTest("test", 3); } @Test public void run4() throws Throwable { runTest("test", 4); } @Test public void run5() throws Throwable { runTest("test", 5); } @Test public void run6() throws Throwable { runTest("test", 6); } @Test public void run7() throws Throwable { runTest("test", 7); } }
gpl-2.0
yodanielo/madara
wp-includes/rewrite.php
62741
<?php /** * WordPress Rewrite API * * @package WordPress * @subpackage Rewrite */ /** * Add a straight rewrite rule. * * @see WP_Rewrite::add_rule() for long description. * @since 2.1.0 * * @param string $regex Regular Expression to match request against. * @param string $redirect Page to redirect to. * @param string $after Optional, default is 'bottom'. Where to add rule, can also be 'top'. */ function add_rewrite_rule($regex, $redirect, $after = 'bottom') { global $wp_rewrite; $wp_rewrite->add_rule($regex, $redirect, $after); } /** * Add a new tag (like %postname%). * * Warning: you must call this on init or earlier, otherwise the query var * addition stuff won't work. * * @since 2.1.0 * * @param string $tagname * @param string $regex */ function add_rewrite_tag($tagname, $regex) { //validation if ( strlen($tagname) < 3 || $tagname{0} != '%' || $tagname{strlen($tagname)-1} != '%' ) return; $qv = trim($tagname, '%'); global $wp_rewrite, $wp; $wp->add_query_var($qv); $wp_rewrite->add_rewrite_tag($tagname, $regex, $qv . '='); } /** * Add permalink structure. * * @see WP_Rewrite::add_permastruct() * @since 3.0.0 * * @param string $name Name for permalink structure. * @param string $struct Permalink structure. * @param bool $with_front Prepend front base to permalink structure. */ function add_permastruct( $name, $struct, $with_front = true, $ep_mask = EP_NONE ) { global $wp_rewrite; return $wp_rewrite->add_permastruct( $name, $struct, $with_front, $ep_mask ); } /** * Add a new feed type like /atom1/. * * @since 2.1.0 * * @param string $feedname * @param callback $function Callback to run on feed display. * @return string Feed action name. */ function add_feed($feedname, $function) { global $wp_rewrite; if ( ! in_array($feedname, $wp_rewrite->feeds) ) //override the file if it is $wp_rewrite->feeds[] = $feedname; $hook = 'do_feed_' . $feedname; // Remove default function hook remove_action($hook, $hook, 10, 1); add_action($hook, $function, 10, 1); return $hook; } /** * Remove rewrite rules and then recreate rewrite rules. * * @see WP_Rewrite::flush_rules() * @since 3.0.0 * * @param bool $hard Whether to update .htaccess (hard flush) or just update * rewrite_rules transient (soft flush). Default is true (hard). */ function flush_rewrite_rules( $hard = true ) { global $wp_rewrite; $wp_rewrite->flush_rules( $hard ); } //pseudo-places /** * Endpoint Mask for default, which is nothing. * * @since 2.1.0 */ define('EP_NONE', 0); /** * Endpoint Mask for Permalink. * * @since 2.1.0 */ define('EP_PERMALINK', 1); /** * Endpoint Mask for Attachment. * * @since 2.1.0 */ define('EP_ATTACHMENT', 2); /** * Endpoint Mask for date. * * @since 2.1.0 */ define('EP_DATE', 4); /** * Endpoint Mask for year * * @since 2.1.0 */ define('EP_YEAR', 8); /** * Endpoint Mask for month. * * @since 2.1.0 */ define('EP_MONTH', 16); /** * Endpoint Mask for day. * * @since 2.1.0 */ define('EP_DAY', 32); /** * Endpoint Mask for root. * * @since 2.1.0 */ define('EP_ROOT', 64); /** * Endpoint Mask for comments. * * @since 2.1.0 */ define('EP_COMMENTS', 128); /** * Endpoint Mask for searches. * * @since 2.1.0 */ define('EP_SEARCH', 256); /** * Endpoint Mask for categories. * * @since 2.1.0 */ define('EP_CATEGORIES', 512); /** * Endpoint Mask for tags. * * @since 2.3.0 */ define('EP_TAGS', 1024); /** * Endpoint Mask for authors. * * @since 2.1.0 */ define('EP_AUTHORS', 2048); /** * Endpoint Mask for pages. * * @since 2.1.0 */ define('EP_PAGES', 4096); /** * Endpoint Mask for everything. * * @since 2.1.0 */ define('EP_ALL', 8191); /** * Add an endpoint, like /trackback/. * * The endpoints are added to the end of the request. So a request matching * "/2008/10/14/my_post/myep/", the endpoint will be "/myep/". * * Be sure to flush the rewrite rules (wp_rewrite->flush()) when your plugin gets * activated (register_activation_hook()) and deactivated (register_deactivation_hook()) * * @since 2.1.0 * @see WP_Rewrite::add_endpoint() Parameters and more description. * @uses $wp_rewrite * * @param unknown_type $name * @param unknown_type $places */ function add_rewrite_endpoint($name, $places) { global $wp_rewrite; $wp_rewrite->add_endpoint($name, $places); } /** * Filter the URL base for taxonomies. * * To remove any manually prepended /index.php/. * * @access private * @since 2.6.0 * * @param string $base The taxonomy base that we're going to filter * @return string */ function _wp_filter_taxonomy_base( $base ) { if ( !empty( $base ) ) { $base = preg_replace( '|^/index\.php/|', '', $base ); $base = trim( $base, '/' ); } return $base; } /** * Examine a url and try to determine the post ID it represents. * * Checks are supposedly from the hosted site blog. * * @since 1.0.0 * * @param string $url Permalink to check. * @return int Post ID, or 0 on failure. */ function url_to_postid($url) { global $wp_rewrite; $url = apply_filters('url_to_postid', $url); // First, check to see if there is a 'p=N' or 'page_id=N' to match against if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) ) { $id = absint($values[2]); if ( $id ) return $id; } // Check to see if we are using rewrite rules $rewrite = $wp_rewrite->wp_rewrite_rules(); // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options if ( empty($rewrite) ) return 0; // $url cleanup by Mark Jaquith // This fixes things like #anchors, ?query=strings, missing 'www.', // added 'www.', or added 'index.php/' that will mess up our WP_Query // and return a false negative // Get rid of the #anchor $url_split = explode('#', $url); $url = $url_split[0]; // Get rid of URL ?query=string $url_split = explode('?', $url); $url = $url_split[0]; // Add 'www.' if it is absent and should be there if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') ) $url = str_replace('://', '://www.', $url); // Strip 'www.' if it is present and shouldn't be if ( false === strpos(home_url(), '://www.') ) $url = str_replace('://www.', '://', $url); // Strip 'index.php/' if we're not using path info permalinks if ( !$wp_rewrite->using_index_permalinks() ) $url = str_replace('index.php/', '', $url); if ( false !== strpos($url, home_url()) ) { // Chop off http://domain.com $url = str_replace(home_url(), '', $url); } else { // Chop off /path/to/blog $home_path = parse_url(home_url()); $home_path = $home_path['path']; $url = str_replace($home_path, '', $url); } // Trim leading and lagging slashes $url = trim($url, '/'); $request = $url; // Done with cleanup // Look for matches. $request_match = $request; foreach ( (array)$rewrite as $match => $query) { // If the requesting file is the anchor of the match, prepend it // to the path info. if ( !empty($url) && ($url != $request) && (strpos($match, $url) === 0) ) $request_match = $url . '/' . $request; if ( preg_match("!^$match!", $request_match, $matches) ) { // Got a match. // Trim the query of everything up to the '?'. $query = preg_replace("!^.+\?!", '', $query); // Substitute the substring matches into the query. $query = addslashes(WP_MatchesMapRegex::apply($query, $matches)); // Filter out non-public query vars global $wp; parse_str($query, $query_vars); $query = array(); foreach ( (array) $query_vars as $key => $value ) { if ( in_array($key, $wp->public_query_vars) ) $query[$key] = $value; } // Do the query $query = new WP_Query($query); if ( $query->is_single || $query->is_page ) return $query->post->ID; else return 0; } } return 0; } /** * WordPress Rewrite Component. * * The WordPress Rewrite class writes the rewrite module rules to the .htaccess * file. It also handles parsing the request to get the correct setup for the * WordPress Query class. * * The Rewrite along with WP class function as a front controller for WordPress. * You can add rules to trigger your page view and processing using this * component. The full functionality of a front controller does not exist, * meaning you can't define how the template files load based on the rewrite * rules. * * @since 1.5.0 */ class WP_Rewrite { /** * Default permalink structure for WordPress. * * @since 1.5.0 * @access private * @var string */ var $permalink_structure; /** * Whether to add trailing slashes. * * @since 2.2.0 * @access private * @var bool */ var $use_trailing_slashes; /** * Customized or default category permalink base ( example.com/xx/tagname ). * * @since 1.5.0 * @access private * @var string */ var $category_base; /** * Customized or default tag permalink base ( example.com/xx/tagname ). * * @since 2.3.0 * @access private * @var string */ var $tag_base; /** * Permalink request structure for categories. * * @since 1.5.0 * @access private * @var string */ var $category_structure; /** * Permalink request structure for tags. * * @since 2.3.0 * @access private * @var string */ var $tag_structure; /** * Permalink author request base ( example.com/author/authorname ). * * @since 1.5.0 * @access private * @var string */ var $author_base = 'author'; /** * Permalink request structure for author pages. * * @since 1.5.0 * @access private * @var string */ var $author_structure; /** * Permalink request structure for dates. * * @since 1.5.0 * @access private * @var string */ var $date_structure; /** * Permalink request structure for pages. * * @since 1.5.0 * @access private * @var string */ var $page_structure; /** * Search permalink base ( example.com/search/query ). * * @since 1.5.0 * @access private * @var string */ var $search_base = 'search'; /** * Permalink request structure for searches. * * @since 1.5.0 * @access private * @var string */ var $search_structure; /** * Comments permalink base. * * @since 1.5.0 * @access private * @var string */ var $comments_base = 'comments'; /** * Feed permalink base. * * @since 1.5.0 * @access private * @var string */ var $feed_base = 'feed'; /** * Comments feed request structure permalink. * * @since 1.5.0 * @access private * @var string */ var $comments_feed_structure; /** * Feed request structure permalink. * * @since 1.5.0 * @access private * @var string */ var $feed_structure; /** * Front URL path. * * The difference between the root property is that WordPress might be * located at example/WordPress/index.php, if permalinks are turned off. The * WordPress/index.php will be the front portion. If permalinks are turned * on, this will most likely be empty or not set. * * @since 1.5.0 * @access private * @var string */ var $front; /** * Root URL path to WordPress (without domain). * * The difference between front property is that WordPress might be located * at example.com/WordPress/. The root is the 'WordPress/' portion. * * @since 1.5.0 * @access private * @var string */ var $root = ''; /** * Permalink to the home page. * * @since 1.5.0 * @access public * @var string */ var $index = 'index.php'; /** * Request match string. * * @since 1.5.0 * @access private * @var string */ var $matches = ''; /** * Rewrite rules to match against the request to find the redirect or query. * * @since 1.5.0 * @access private * @var array */ var $rules; /** * Additional rules added external to the rewrite class. * * Those not generated by the class, see add_rewrite_rule(). * * @since 2.1.0 * @access private * @var array */ var $extra_rules = array(); // /** * Additional rules that belong at the beginning to match first. * * Those not generated by the class, see add_rewrite_rule(). * * @since 2.3.0 * @access private * @var array */ var $extra_rules_top = array(); // /** * Rules that don't redirect to WP's index.php. * * These rules are written to the mod_rewrite portion of the .htaccess. * * @since 2.1.0 * @access private * @var array */ var $non_wp_rules = array(); // /** * Extra permalink structures. * * @since 2.1.0 * @access private * @var array */ var $extra_permastructs = array(); /** * Endpoints permalinks * * @since unknown * @access private * @var array */ var $endpoints; /** * Whether to write every mod_rewrite rule for WordPress. * * This is off by default, turning it on might print a lot of rewrite rules * to the .htaccess file. * * @since 2.0.0 * @access public * @var bool */ var $use_verbose_rules = false; /** * Whether to write every mod_rewrite rule for WordPress pages. * * @since 2.5.0 * @access public * @var bool */ var $use_verbose_page_rules = true; /** * Permalink structure search for preg_replace. * * @since 1.5.0 * @access private * @var array */ var $rewritecode = array( '%year%', '%monthnum%', '%day%', '%hour%', '%minute%', '%second%', '%postname%', '%post_id%', '%category%', '%tag%', '%author%', '%pagename%', '%search%' ); /** * Preg_replace values for the search, see {@link WP_Rewrite::$rewritecode}. * * @since 1.5.0 * @access private * @var array */ var $rewritereplace = array( '([0-9]{4})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([^/]+)', '([0-9]+)', '(.+?)', '(.+?)', '([^/]+)', '([^/]+?)', '(.+)' ); /** * Search for the query to look for replacing. * * @since 1.5.0 * @access private * @var array */ var $queryreplace = array ( 'year=', 'monthnum=', 'day=', 'hour=', 'minute=', 'second=', 'name=', 'p=', 'category_name=', 'tag=', 'author_name=', 'pagename=', 's=' ); /** * Supported default feeds. * * @since 1.5.0 * @access private * @var array */ var $feeds = array ( 'feed', 'rdf', 'rss', 'rss2', 'atom' ); /** * Whether permalinks are being used. * * This can be either rewrite module or permalink in the HTTP query string. * * @since 1.5.0 * @access public * * @return bool True, if permalinks are enabled. */ function using_permalinks() { return ! empty($this->permalink_structure); } /** * Whether permalinks are being used and rewrite module is not enabled. * * Means that permalink links are enabled and index.php is in the URL. * * @since 1.5.0 * @access public * * @return bool */ function using_index_permalinks() { if ( empty($this->permalink_structure) ) return false; // If the index is not in the permalink, we're using mod_rewrite. if ( preg_match('#^/*' . $this->index . '#', $this->permalink_structure) ) return true; return false; } /** * Whether permalinks are being used and rewrite module is enabled. * * Using permalinks and index.php is not in the URL. * * @since 1.5.0 * @access public * * @return bool */ function using_mod_rewrite_permalinks() { if ( $this->using_permalinks() && ! $this->using_index_permalinks() ) return true; else return false; } /** * Index for matches for usage in preg_*() functions. * * The format of the string is, with empty matches property value, '$NUM'. * The 'NUM' will be replaced with the value in the $number parameter. With * the matches property not empty, the value of the returned string will * contain that value of the matches property. The format then will be * '$MATCHES[NUM]', with MATCHES as the value in the property and NUM the * value of the $number parameter. * * @since 1.5.0 * @access public * * @param int $number Index number. * @return string */ function preg_index($number) { $match_prefix = '$'; $match_suffix = ''; if ( ! empty($this->matches) ) { $match_prefix = '$' . $this->matches . '['; $match_suffix = ']'; } return "$match_prefix$number$match_suffix"; } /** * Retrieve all page and attachments for pages URIs. * * The attachments are for those that have pages as parents and will be * retrieved. * * @since 2.5.0 * @access public * * @return array Array of page URIs as first element and attachment URIs as second element. */ function page_uri_index() { global $wpdb; //get pages in order of hierarchy, i.e. children after parents $posts = get_page_hierarchy($wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page'")); // If we have no pages get out quick if ( !$posts ) return array( array(), array() ); //now reverse it, because we need parents after children for rewrite rules to work properly $posts = array_reverse($posts, true); $page_uris = array(); $page_attachment_uris = array(); foreach ( $posts as $id => $post ) { // URL => page name $uri = get_page_uri($id); $attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id )); if ( !empty($attachments) ) { foreach ( $attachments as $attachment ) { $attach_uri = get_page_uri($attachment->ID); $page_attachment_uris[$attach_uri] = $attachment->ID; } } $page_uris[$uri] = $id; } return array( $page_uris, $page_attachment_uris ); } /** * Retrieve all of the rewrite rules for pages. * * If the 'use_verbose_page_rules' property is false, then there will only * be a single rewrite rule for pages for those matching '%pagename%'. With * the property set to true, the attachments and the pages will be added for * each individual attachment URI and page URI, respectively. * * @since 1.5.0 * @access public * * @return array */ function page_rewrite_rules() { $rewrite_rules = array(); $page_structure = $this->get_page_permastruct(); if ( ! $this->use_verbose_page_rules ) { $this->add_rewrite_tag('%pagename%', "(.+?)", 'pagename='); $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES)); return $rewrite_rules; } $page_uris = $this->page_uri_index(); $uris = $page_uris[0]; $attachment_uris = $page_uris[1]; if ( is_array( $attachment_uris ) ) { foreach ( $attachment_uris as $uri => $pagename ) { $this->add_rewrite_tag('%pagename%', "($uri)", 'attachment='); $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES)); } } if ( is_array( $uris ) ) { foreach ( $uris as $uri => $pagename ) { $this->add_rewrite_tag('%pagename%', "($uri)", 'pagename='); $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES)); } } return $rewrite_rules; } /** * Retrieve date permalink structure, with year, month, and day. * * The permalink structure for the date, if not set already depends on the * permalink structure. It can be one of three formats. The first is year, * month, day; the second is day, month, year; and the last format is month, * day, year. These are matched against the permalink structure for which * one is used. If none matches, then the default will be used, which is * year, month, day. * * Prevents post ID and date permalinks from overlapping. In the case of * post_id, the date permalink will be prepended with front permalink with * 'date/' before the actual permalink to form the complete date permalink * structure. * * @since 1.5.0 * @access public * * @return bool|string False on no permalink structure. Date permalink structure. */ function get_date_permastruct() { if ( isset($this->date_structure) ) return $this->date_structure; if ( empty($this->permalink_structure) ) { $this->date_structure = ''; return false; } // The date permalink must have year, month, and day separated by slashes. $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%'); $this->date_structure = ''; $date_endian = ''; foreach ( $endians as $endian ) { if ( false !== strpos($this->permalink_structure, $endian) ) { $date_endian= $endian; break; } } if ( empty($date_endian) ) $date_endian = '%year%/%monthnum%/%day%'; // Do not allow the date tags and %post_id% to overlap in the permalink // structure. If they do, move the date tags to $front/date/. $front = $this->front; preg_match_all('/%.+?%/', $this->permalink_structure, $tokens); $tok_index = 1; foreach ( (array) $tokens[0] as $token) { if ( '%post_id%' == $token && ($tok_index <= 3) ) { $front = $front . 'date/'; break; } $tok_index++; } $this->date_structure = $front . $date_endian; return $this->date_structure; } /** * Retrieve the year permalink structure without month and day. * * Gets the date permalink structure and strips out the month and day * permalink structures. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Year structure on success. */ function get_year_permastruct() { $structure = $this->get_date_permastruct($this->permalink_structure); if ( empty($structure) ) return false; $structure = str_replace('%monthnum%', '', $structure); $structure = str_replace('%day%', '', $structure); $structure = preg_replace('#/+#', '/', $structure); return $structure; } /** * Retrieve the month permalink structure without day and with year. * * Gets the date permalink structure and strips out the day permalink * structures. Keeps the year permalink structure. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Year/Month structure on success. */ function get_month_permastruct() { $structure = $this->get_date_permastruct($this->permalink_structure); if ( empty($structure) ) return false; $structure = str_replace('%day%', '', $structure); $structure = preg_replace('#/+#', '/', $structure); return $structure; } /** * Retrieve the day permalink structure with month and year. * * Keeps date permalink structure with all year, month, and day. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Year/Month/Day structure on success. */ function get_day_permastruct() { return $this->get_date_permastruct($this->permalink_structure); } /** * Retrieve the permalink structure for categories. * * If the category_base property has no value, then the category structure * will have the front property value, followed by 'category', and finally * '%category%'. If it does, then the root property will be used, along with * the category_base property value. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Category permalink structure. */ function get_category_permastruct() { if ( isset($this->category_structure) ) return $this->category_structure; if ( empty($this->permalink_structure) ) { $this->category_structure = ''; return false; } if ( empty($this->category_base) ) $this->category_structure = trailingslashit( $this->front . 'category' ); else $this->category_structure = trailingslashit( '/' . $this->root . $this->category_base ); $this->category_structure .= '%category%'; return $this->category_structure; } /** * Retrieve the permalink structure for tags. * * If the tag_base property has no value, then the tag structure will have * the front property value, followed by 'tag', and finally '%tag%'. If it * does, then the root property will be used, along with the tag_base * property value. * * @since 2.3.0 * @access public * * @return bool|string False on failure. Tag permalink structure. */ function get_tag_permastruct() { if ( isset($this->tag_structure) ) return $this->tag_structure; if ( empty($this->permalink_structure) ) { $this->tag_structure = ''; return false; } if ( empty($this->tag_base) ) $this->tag_structure = trailingslashit( $this->front . 'tag' ); else $this->tag_structure = trailingslashit( '/' . $this->root . $this->tag_base ); $this->tag_structure .= '%tag%'; return $this->tag_structure; } /** * Retrieve extra permalink structure by name. * * @since unknown * @access public * * @param string $name Permalink structure name. * @return string|bool False if not found. Permalink structure string. */ function get_extra_permastruct($name) { if ( empty($this->permalink_structure) ) return false; if ( isset($this->extra_permastructs[$name]) ) return $this->extra_permastructs[$name][0]; return false; } /** * Retrieve the author permalink structure. * * The permalink structure is front property, author base, and finally * '/%author%'. Will set the author_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_author_permastruct() { if ( isset($this->author_structure) ) return $this->author_structure; if ( empty($this->permalink_structure) ) { $this->author_structure = ''; return false; } $this->author_structure = $this->front . $this->author_base . '/%author%'; return $this->author_structure; } /** * Retrieve the search permalink structure. * * The permalink structure is root property, search base, and finally * '/%search%'. Will set the search_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_search_permastruct() { if ( isset($this->search_structure) ) return $this->search_structure; if ( empty($this->permalink_structure) ) { $this->search_structure = ''; return false; } $this->search_structure = $this->root . $this->search_base . '/%search%'; return $this->search_structure; } /** * Retrieve the page permalink structure. * * The permalink structure is root property, and '%pagename%'. Will set the * page_structure property and then return it without attempting to set the * value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_page_permastruct() { if ( isset($this->page_structure) ) return $this->page_structure; if (empty($this->permalink_structure)) { $this->page_structure = ''; return false; } $this->page_structure = $this->root . '%pagename%'; return $this->page_structure; } /** * Retrieve the feed permalink structure. * * The permalink structure is root property, feed base, and finally * '/%feed%'. Will set the feed_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_feed_permastruct() { if ( isset($this->feed_structure) ) return $this->feed_structure; if ( empty($this->permalink_structure) ) { $this->feed_structure = ''; return false; } $this->feed_structure = $this->root . $this->feed_base . '/%feed%'; return $this->feed_structure; } /** * Retrieve the comment feed permalink structure. * * The permalink structure is root property, comment base property, feed * base and finally '/%feed%'. Will set the comment_feed_structure property * and then return it without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_comment_feed_permastruct() { if ( isset($this->comment_feed_structure) ) return $this->comment_feed_structure; if (empty($this->permalink_structure)) { $this->comment_feed_structure = ''; return false; } $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%'; return $this->comment_feed_structure; } /** * Append or update tag, pattern, and query for replacement. * * If the tag already exists, replace the existing pattern and query for * that tag, otherwise add the new tag, pattern, and query to the end of the * arrays. * * @internal What is the purpose of this function again? Need to finish long * description. * * @since 1.5.0 * @access public * * @param string $tag Append tag to rewritecode property array. * @param string $pattern Append pattern to rewritereplace property array. * @param string $query Append query to queryreplace property array. */ function add_rewrite_tag($tag, $pattern, $query) { $position = array_search($tag, $this->rewritecode); if ( false !== $position && null !== $position ) { $this->rewritereplace[$position] = $pattern; $this->queryreplace[$position] = $query; } else { $this->rewritecode[] = $tag; $this->rewritereplace[] = $pattern; $this->queryreplace[] = $query; } } /** * Generate the rules from permalink structure. * * The main WP_Rewrite function for building the rewrite rule list. The * contents of the function is a mix of black magic and regular expressions, * so best just ignore the contents and move to the parameters. * * @since 1.5.0 * @access public * * @param string $permalink_structure The permalink structure. * @param int $ep_mask Optional, default is EP_NONE. Endpoint constant, see EP_* constants. * @param bool $paged Optional, default is true. Whether permalink request is paged. * @param bool $feed Optional, default is true. Whether for feed. * @param bool $forcomments Optional, default is false. Whether for comments. * @param bool $walk_dirs Optional, default is true. Whether to create list of directories to walk over. * @param bool $endpoints Optional, default is true. Whether endpoints are enabled. * @return array Rewrite rule list. */ function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) { //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/? $feedregex2 = ''; foreach ( (array) $this->feeds as $feed_name) $feedregex2 .= $feed_name . '|'; $feedregex2 = '(' . trim($feedregex2, '|') . ')/?$'; //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom //and <permalink>/atom are both possible $feedregex = $this->feed_base . '/' . $feedregex2; //build a regex to match the trackback and page/xx parts of URLs $trackbackregex = 'trackback/?$'; $pageregex = 'page/?([0-9]{1,})/?$'; $commentregex = 'comment-page-([0-9]{1,})/?$'; //build up an array of endpoint regexes to append => queries to append if ( $endpoints ) { $ep_query_append = array (); foreach ( (array) $this->endpoints as $endpoint) { //match everything after the endpoint name, but allow for nothing to appear there $epmatch = $endpoint[1] . '(/(.*))?/?$'; //this will be appended on to the rest of the query for each dir $epquery = '&' . $endpoint[1] . '='; $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery ); } } //get everything up to the first rewrite tag $front = substr($permalink_structure, 0, strpos($permalink_structure, '%')); //build an array of the tags (note that said array ends up being in $tokens[0]) preg_match_all('/%.+?%/', $permalink_structure, $tokens); $num_tokens = count($tokens[0]); $index = $this->index; //probably 'index.php' $feedindex = $index; $trackbackindex = $index; //build a list from the rewritecode and queryreplace arrays, that will look something like //tagname=$matches[i] where i is the current $i for ( $i = 0; $i < $num_tokens; ++$i ) { if ( 0 < $i ) $queries[$i] = $queries[$i - 1] . '&'; else $queries[$i] = ''; $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1); $queries[$i] .= $query_token; } //get the structure, minus any cruft (stuff that isn't tags) at the front $structure = $permalink_structure; if ( $front != '/' ) $structure = str_replace($front, '', $structure); //create a list of dirs to walk over, making rewrite rules for each level //so for example, a $structure of /%year%/%month%/%postname% would create //rewrite rules for /%year%/, /%year%/%month%/ and /%year%/%month%/%postname% $structure = trim($structure, '/'); $dirs = $walk_dirs ? explode('/', $structure) : array( $structure ); $num_dirs = count($dirs); //strip slashes from the front of $front $front = preg_replace('|^/+|', '', $front); //the main workhorse loop $post_rewrite = array(); $struct = $front; for ( $j = 0; $j < $num_dirs; ++$j ) { //get the struct for this dir, and trim slashes off the front $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above $struct = ltrim($struct, '/'); //replace tags with regexes $match = str_replace($this->rewritecode, $this->rewritereplace, $struct); //make a list of tags, and store how many there are in $num_toks $num_toks = preg_match_all('/%.+?%/', $struct, $toks); //get the 'tagname=$matches[i]' $query = ( isset($queries) && is_array($queries) ) ? $queries[$num_toks - 1] : ''; //set up $ep_mask_specific which is used to match more specific URL types switch ( $dirs[$j] ) { case '%year%': $ep_mask_specific = EP_YEAR; break; case '%monthnum%': $ep_mask_specific = EP_MONTH; break; case '%day%': $ep_mask_specific = EP_DAY; break; default: $ep_mask_specific = EP_NONE; } //create query for /page/xx $pagematch = $match . $pageregex; $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1); //create query for /comment-page-xx $commentmatch = $match . $commentregex; $commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index($num_toks + 1); if ( get_option('page_on_front') ) { //create query for Root /comment-page-xx $rootcommentmatch = $match . $commentregex; $rootcommentquery = $index . '?' . $query . '&page_id=' . get_option('page_on_front') . '&cpage=' . $this->preg_index($num_toks + 1); } //create query for /feed/(feed|atom|rss|rss2|rdf) $feedmatch = $match . $feedregex; $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1); //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex) $feedmatch2 = $match . $feedregex2; $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1); //if asked to, turn the feed queries into comment feed ones if ( $forcomments ) { $feedquery .= '&withcomments=1'; $feedquery2 .= '&withcomments=1'; } //start creating the array of rewrites for this dir $rewrite = array(); if ( $feed ) //...adding on /feed/ regexes => queries $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2); if ( $paged ) //...and /page/xx ones $rewrite = array_merge($rewrite, array($pagematch => $pagequery)); //only on pages with comments add ../comment-page-xx/ if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask ) $rewrite = array_merge($rewrite, array($commentmatch => $commentquery)); else if ( EP_ROOT & $ep_mask && get_option('page_on_front') ) $rewrite = array_merge($rewrite, array($rootcommentmatch => $rootcommentquery)); //do endpoints if ( $endpoints ) { foreach ( (array) $ep_query_append as $regex => $ep) { //add the endpoints on if the mask fits if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific ) $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2); } } //if we've got some tags in this dir if ( $num_toks ) { $post = false; $page = false; //check to see if this dir is permalink-level: i.e. the structure specifies an //individual post. Do this by checking it contains at least one of 1) post name, //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and //minute all present). Set these flags now as we need them for the endpoints. if ( strpos($struct, '%postname%') !== false || strpos($struct, '%post_id%') !== false || strpos($struct, '%pagename%') !== false || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false) ) { $post = true; if ( strpos($struct, '%pagename%') !== false ) $page = true; } if ( ! $post ) { // For custom post types, we need to add on endpoints as well. foreach ( get_post_types( array('_builtin' => false ) ) as $ptype ) { if ( strpos($struct, "%$ptype%") !== false ) { $post = true; $page = is_post_type_hierarchical( $ptype ); // This is for page style attachment url's break; } } } //if we're creating rules for a permalink, do all the endpoints like attachments etc if ( $post ) { //create query and regex for trackback $trackbackmatch = $match . $trackbackregex; $trackbackquery = $trackbackindex . '?' . $query . '&tb=1'; //trim slashes from the end of the regex for this dir $match = rtrim($match, '/'); //get rid of brackets $submatchbase = str_replace( array('(', ')'), '', $match); //add a rule for at attachments, which take the form of <permalink>/some-text $sub1 = $submatchbase . '/([^/]+)/'; $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/... $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...) $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...) $sub1comment = $sub1 . $commentregex; //and <permalink>/comment-page-xx //add an ? as we don't have to match that last slash, and finally a $ so we //match to the end of the URL //add another rule to match attachments in the explicit form: //<permalink>/attachment/some-text $sub2 = $submatchbase . '/attachment/([^/]+)/'; $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback $sub2feed = $sub2 . $feedregex; //feeds, <permalink>/attachment/feed/(atom|...) $sub2feed2 = $sub2 . $feedregex2; //and feeds again on to this <permalink>/attachment/(feed|atom...) $sub2comment = $sub2 . $commentregex; //and <permalink>/comment-page-xx //create queries for these extra tag-ons we've just dealt with $subquery = $index . '?attachment=' . $this->preg_index(1); $subtbquery = $subquery . '&tb=1'; $subfeedquery = $subquery . '&feed=' . $this->preg_index(2); $subcommentquery = $subquery . '&cpage=' . $this->preg_index(2); //do endpoints for attachments if ( !empty($endpoints) ) { foreach ( (array) $ep_query_append as $regex => $ep ) { if ( $ep[0] & EP_ATTACHMENT ) { $rewrite[$sub1 . $regex] = $subquery . $ep[1] . $this->preg_index(2); $rewrite[$sub2 . $regex] = $subquery . $ep[1] . $this->preg_index(2); } } } //now we've finished with endpoints, finish off the $sub1 and $sub2 matches $sub1 .= '?$'; $sub2 .= '?$'; //allow URLs like <permalink>/2 for <permalink>/page/2 $match = $match . '(/[0-9]+)?/?$'; $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1); } else { //not matching a permalink so this is a lot simpler //close the match and finalise the query $match .= '?$'; $query = $index . '?' . $query; } //create the final array for this dir by joining the $rewrite array (which currently //only contains rules/queries for trackback, pages etc) to the main regex/query for //this dir $rewrite = array_merge($rewrite, array($match => $query)); //if we're matching a permalink, add those extras (attachments etc) on if ( $post ) { //add trackback $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite); //add regexes/queries for attachments, attachment trackbacks and so on if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery, $sub1comment => $subcommentquery)); $rewrite = array_merge(array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery, $sub2comment => $subcommentquery), $rewrite); } } //if($num_toks) //add the rules for this dir to the accumulating $post_rewrite $post_rewrite = array_merge($rewrite, $post_rewrite); } //foreach ($dir) return $post_rewrite; //the finished rules. phew! } /** * Generate Rewrite rules with permalink structure and walking directory only. * * Shorten version of {@link WP_Rewrite::generate_rewrite_rules()} that * allows for shorter list of parameters. See the method for longer * description of what generating rewrite rules does. * * @uses WP_Rewrite::generate_rewrite_rules() See for long description and rest of parameters. * @since 1.5.0 * @access public * * @param string $permalink_structure The permalink structure to generate rules. * @param bool $walk_dirs Optional, default is false. Whether to create list of directories to walk over. * @return array */ function generate_rewrite_rule($permalink_structure, $walk_dirs = false) { return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs); } /** * Construct rewrite matches and queries from permalink structure. * * Runs the action 'generate_rewrite_rules' with the parameter that is an * reference to the current WP_Rewrite instance to further manipulate the * permalink structures and rewrite rules. Runs the 'rewrite_rules_array' * filter on the full rewrite rule array. * * There are two ways to manipulate the rewrite rules, one by hooking into * the 'generate_rewrite_rules' action and gaining full control of the * object or just manipulating the rewrite rule array before it is passed * from the function. * * @since 1.5.0 * @access public * * @return array An associate array of matches and queries. */ function rewrite_rules() { $rewrite = array(); if ( empty($this->permalink_structure) ) return $rewrite; // robots.txt -only if installed at the root $home_path = parse_url( home_url() ); $robots_rewrite = ( empty( $home_path['path'] ) || '/' == $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array(); // Default Feed rules - These are require to allow for the direct access files to work with permalink structure starting with %category% $default_feeds = array( '.*wp-atom.php$' => $this->index . '?feed=atom', '.*wp-rdf.php$' => $this->index . '?feed=rdf', '.*wp-rss.php$' => $this->index . '?feed=rss', '.*wp-rss2.php$' => $this->index . '?feed=rss2', '.*wp-feed.php$' => $this->index . '?feed=feed', '.*wp-commentsrss2.php$' => $this->index . '?feed=rss2&withcomments=1'); // Registration rules $registration_pages = array(); if ( is_multisite() && is_main_site() ) { $registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true'; $registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true'; } // Post $post_rewrite = $this->generate_rewrite_rules($this->permalink_structure, EP_PERMALINK); $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite); // Date $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE); $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite); // Root $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT); $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite); // Comments $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, true, true, true, false); $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite); // Search $search_structure = $this->get_search_permastruct(); $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH); $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite); // Categories $category_rewrite = $this->generate_rewrite_rules($this->get_category_permastruct(), EP_CATEGORIES); $category_rewrite = apply_filters('category_rewrite_rules', $category_rewrite); // Tags $tag_rewrite = $this->generate_rewrite_rules($this->get_tag_permastruct(), EP_TAGS); $tag_rewrite = apply_filters('tag_rewrite_rules', $tag_rewrite); // Authors $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS); $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite); // Pages $page_rewrite = $this->page_rewrite_rules(); $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite); // Extra permastructs foreach ( $this->extra_permastructs as $permastruct ) { if ( is_array($permastruct) ) $this->extra_rules_top = array_merge($this->extra_rules_top, $this->generate_rewrite_rules($permastruct[0], $permastruct[1])); else $this->extra_rules_top = array_merge($this->extra_rules_top, $this->generate_rewrite_rules($permastruct, EP_NONE)); } // Put them together. if ( $this->use_verbose_page_rules ) $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $default_feeds, $registration_pages, $page_rewrite, $root_rewrite, $comments_rewrite, $search_rewrite, $category_rewrite, $tag_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $this->extra_rules); else $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $default_feeds, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $category_rewrite, $tag_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules); do_action_ref_array('generate_rewrite_rules', array(&$this)); $this->rules = apply_filters('rewrite_rules_array', $this->rules); return $this->rules; } /** * Retrieve the rewrite rules. * * The difference between this method and {@link * WP_Rewrite::rewrite_rules()} is that this method stores the rewrite rules * in the 'rewrite_rules' option and retrieves it. This prevents having to * process all of the permalinks to get the rewrite rules in the form of * caching. * * @since 1.5.0 * @access public * * @return array Rewrite rules. */ function wp_rewrite_rules() { $this->rules = get_option('rewrite_rules'); if ( empty($this->rules) ) { $this->matches = 'matches'; $this->rewrite_rules(); update_option('rewrite_rules', $this->rules); } return $this->rules; } /** * Retrieve mod_rewrite formatted rewrite rules to write to .htaccess. * * Does not actually write to the .htaccess file, but creates the rules for * the process that will. * * Will add the non_wp_rules property rules to the .htaccess file before * the WordPress rewrite rules one. * * @since 1.5.0 * @access public * * @return string */ function mod_rewrite_rules() { if ( ! $this->using_permalinks() ) return ''; $site_root = parse_url(get_option('siteurl')); if ( isset( $site_root['path'] ) ) $site_root = trailingslashit($site_root['path']); $home_root = parse_url(home_url()); if ( isset( $home_root['path'] ) ) $home_root = trailingslashit($home_root['path']); else $home_root = '/'; $rules = "<IfModule mod_rewrite.c>\n"; $rules .= "RewriteEngine On\n"; $rules .= "RewriteBase $home_root\n"; $rules .= "RewriteRule ^index\.php$ - [L]\n"; // Prevent -f checks on index.php. //add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all) foreach ( (array) $this->non_wp_rules as $match => $query) { // Apache 1.3 does not support the reluctant (non-greedy) modifier. $match = str_replace('.+?', '.+', $match); // If the match is unanchored and greedy, prepend rewrite conditions // to avoid infinite redirects and eclipsing of real files. //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) { //nada. //} $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n"; } if ( $this->use_verbose_rules ) { $this->matches = ''; $rewrite = $this->rewrite_rules(); $num_rules = count($rewrite); $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" . "RewriteCond %{REQUEST_FILENAME} -d\n" . "RewriteRule ^.*$ - [S=$num_rules]\n"; foreach ( (array) $rewrite as $match => $query) { // Apache 1.3 does not support the reluctant (non-greedy) modifier. $match = str_replace('.+?', '.+', $match); // If the match is unanchored and greedy, prepend rewrite conditions // to avoid infinite redirects and eclipsing of real files. //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) { //nada. //} if ( strpos($query, $this->index) !== false ) $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n"; else $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n"; } } else { $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" . "RewriteCond %{REQUEST_FILENAME} !-d\n" . "RewriteRule . {$home_root}{$this->index} [L]\n"; } $rules .= "</IfModule>\n"; $rules = apply_filters('mod_rewrite_rules', $rules); $rules = apply_filters('rewrite_rules', $rules); // Deprecated return $rules; } /** * Retrieve IIS7 URL Rewrite formatted rewrite rules to write to web.config file. * * Does not actually write to the web.config file, but creates the rules for * the process that will. * * @since 2.8.0 * @access public * * @return string */ function iis7_url_rewrite_rules( $add_parent_tags = false ) { if ( ! $this->using_permalinks() ) return ''; $rules = ''; if ( $add_parent_tags ) { $rules .= '<configuration> <system.webServer> <rewrite> <rules>'; } if ( !is_multisite() ) { $rules .= ' <rule name="wordpress" patternSyntax="Wildcard"> <match url="*" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="index.php" /> </rule>'; } else { if (is_subdomain_install()) { $rules .= ' <rule name="wordpress - Rule 1" stopProcessing="true"> <match url="^index\.php$" ignoreCase="false" /> <action type="None" /> </rule> <rule name="wordpress - Rule 2" stopProcessing="true"> <match url="^files/(.+)" ignoreCase="false" /> <action type="Rewrite" url="wp-includes/ms-files.php?file={R:1}" appendQueryString="false" /> </rule> <rule name="wordpress - Rule 3" stopProcessing="true"> <match url="^" ignoreCase="false" /> <conditions logicalGrouping="MatchAny"> <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" /> </conditions> <action type="None" /> </rule> <rule name="wordpress - Rule 4" stopProcessing="true"> <match url="." ignoreCase="false" /> <action type="Rewrite" url="index.php" /> </rule>'; } else { $rules .= ' <rule name="wordpress - Rule 1" stopProcessing="true"> <match url="^index\.php$" ignoreCase="false" /> <action type="None" /> </rule> <rule name="wordpress - Rule 2" stopProcessing="true"> <match url="^([_0-9a-zA-Z-]+/)?files/(.+)" ignoreCase="false" /> <action type="Rewrite" url="wp-includes/ms-files.php?file={R:2}" appendQueryString="false" /> </rule> <rule name="wordpress - Rule 3" stopProcessing="true"> <match url="^([_0-9a-zA-Z-]+/)?wp-admin$" ignoreCase="false" /> <action type="Redirect" url="{R:1}wp-admin/" redirectType="Permanent" /> </rule> <rule name="wordpress - Rule 4" stopProcessing="true"> <match url="^" ignoreCase="false" /> <conditions logicalGrouping="MatchAny"> <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" /> </conditions> <action type="None" /> </rule> <rule name="wordpress - Rule 5" stopProcessing="true"> <match url="^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*)" ignoreCase="false" /> <action type="Rewrite" url="{R:2}" /> </rule> <rule name="wordpress - Rule 6" stopProcessing="true"> <match url="^([_0-9a-zA-Z-]+/)?(.*\.php)$" ignoreCase="false" /> <action type="Rewrite" url="{R:2}" /> </rule> <rule name="wordpress - Rule 7" stopProcessing="true"> <match url="." ignoreCase="false" /> <action type="Rewrite" url="index.php" /> </rule>'; } } if ( $add_parent_tags ) { $rules .= ' </rules> </rewrite> </system.webServer> </configuration>'; } $rules = apply_filters('iis7_url_rewrite_rules', $rules); return $rules; } /** * Add a straight rewrite rule. * * Any value in the $after parameter that isn't 'bottom' will be placed at * the top of the rules. * * @since 2.1.0 * @access public * * @param string $regex Regular expression to match against request. * @param string $redirect URL regex redirects to when regex matches request. * @param string $after Optional, default is bottom. Location to place rule. */ function add_rule($regex, $redirect, $after = 'bottom') { //get everything up to the first ? $index = (strpos($redirect, '?') == false ? strlen($redirect) : strpos($redirect, '?')); $front = substr($redirect, 0, $index); if ( $front != $this->index ) { //it doesn't redirect to WP's index.php $this->add_external_rule($regex, $redirect); } else { if ( 'bottom' == $after) $this->extra_rules = array_merge($this->extra_rules, array($regex => $redirect)); else $this->extra_rules_top = array_merge($this->extra_rules_top, array($regex => $redirect)); //$this->extra_rules[$regex] = $redirect; } } /** * Add a rule that doesn't redirect to index.php. * * Can redirect to any place. * * @since 2.1.0 * @access public * * @param string $regex Regular expression to match against request. * @param string $redirect URL regex redirects to when regex matches request. */ function add_external_rule($regex, $redirect) { $this->non_wp_rules[$regex] = $redirect; } /** * Add an endpoint, like /trackback/. * * To be inserted after certain URL types (specified in $places). * * @since 2.1.0 * @access public * * @param string $name Name of endpoint. * @param array $places URL types that endpoint can be used. */ function add_endpoint($name, $places) { global $wp; $this->endpoints[] = array ( $places, $name ); $wp->add_query_var($name); } /** * Add permalink structure. * * These are added along with the extra rewrite rules that are merged to the * top. * * @since unknown * @access public * * @param string $name Name for permalink structure. * @param string $struct Permalink structure. * @param bool $with_front Prepend front base to permalink structure. */ function add_permastruct($name, $struct, $with_front = true, $ep_mask = EP_NONE) { if ( $with_front ) $struct = $this->front . $struct; $this->extra_permastructs[$name] = array($struct, $ep_mask); } /** * Remove rewrite rules and then recreate rewrite rules. * * Calls {@link WP_Rewrite::wp_rewrite_rules()} after removing the * 'rewrite_rules' option. If the function named 'save_mod_rewrite_rules' * exists, it will be called. * * @since 2.0.1 * @access public * @param $hard bool Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush). Default is true (hard). */ function flush_rules($hard = true) { delete_option('rewrite_rules'); $this->wp_rewrite_rules(); if ( $hard && function_exists('save_mod_rewrite_rules') ) save_mod_rewrite_rules(); if ( $hard && function_exists('iis7_save_url_rewrite_rules') ) iis7_save_url_rewrite_rules(); } /** * Sets up the object's properties. * * The 'use_verbose_page_rules' object property will be set to true if the * permalink structure begins with one of the following: '%postname%', '%category%', * '%tag%', or '%author%'. * * @since 1.5.0 * @access public */ function init() { $this->extra_rules = $this->non_wp_rules = $this->endpoints = array(); $this->permalink_structure = get_option('permalink_structure'); $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%')); $this->root = ''; if ( $this->using_index_permalinks() ) $this->root = $this->index . '/'; $this->category_base = get_option( 'category_base' ); $this->tag_base = get_option( 'tag_base' ); unset($this->category_structure); unset($this->author_structure); unset($this->date_structure); unset($this->page_structure); unset($this->search_structure); unset($this->feed_structure); unset($this->comment_feed_structure); $this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) ); // Enable generic rules for pages if permalink structure doesn't begin with a wildcard. if ( preg_match("/^[^%]*%(?:postname|category|tag|author)%/", $this->permalink_structure) ) $this->use_verbose_page_rules = true; else $this->use_verbose_page_rules = false; } /** * Set the main permalink structure for the blog. * * Will update the 'permalink_structure' option, if there is a difference * between the current permalink structure and the parameter value. Calls * {@link WP_Rewrite::init()} after the option is updated. * * Fires the 'permalink_structure_changed' action once the init call has * processed passing the old and new values * * @since 1.5.0 * @access public * * @param string $permalink_structure Permalink structure. */ function set_permalink_structure($permalink_structure) { if ( $permalink_structure != $this->permalink_structure ) { update_option('permalink_structure', $permalink_structure); $this->init(); do_action('permalink_structure_changed', $this->permalink_structure, $permalink_structure); } } /** * Set the category base for the category permalink. * * Will update the 'category_base' option, if there is a difference between * the current category base and the parameter value. Calls * {@link WP_Rewrite::init()} after the option is updated. * * @since 1.5.0 * @access public * * @param string $category_base Category permalink structure base. */ function set_category_base($category_base) { if ( $category_base != $this->category_base ) { update_option('category_base', $category_base); $this->init(); } } /** * Set the tag base for the tag permalink. * * Will update the 'tag_base' option, if there is a difference between the * current tag base and the parameter value. Calls * {@link WP_Rewrite::init()} after the option is updated. * * @since 2.3.0 * @access public * * @param string $tag_base Tag permalink structure base. */ function set_tag_base( $tag_base ) { if ( $tag_base != $this->tag_base ) { update_option( 'tag_base', $tag_base ); $this->init(); } } /** * PHP4 Constructor - Calls init(), which runs setup. * * @since 1.5.0 * @access public * * @return WP_Rewrite */ function WP_Rewrite() { $this->init(); } } ?>
gpl-2.0
maddy2101/TYPO3.CMS
typo3/sysext/core/Tests/Unit/Configuration/FlexForm/Fixtures/DataStructureIdentifierPreProcessHookReturnArray.php
1098
<?php declare(strict_types=1); /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ namespace TYPO3\CMS\Core\Tests\Unit\Configuration\FlexForm\Fixtures; /** * Fixture to test hooks from FlexFormTools */ class DataStructureIdentifierPreProcessHookReturnArray { /** * Returns an array * * @param array $fieldTca * @param string $tableName * @param string $fieldName * @param array $row * @return array */ public function getDataStructureIdentifierPreProcess( array $fieldTca, string $tableName, string $fieldName, array $row ): array { return [ 'type' => 'myExtension', 'further' => 'data', ]; } }
gpl-2.0
anhtuan8591/shop
modules/mod_acymailing/tmpl/popup.php
905
<?php /** * @copyright Copyright (C) 2009-2012 ACYBA SARL - All rights reserved. * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL */ defined('_JEXEC') or die('Restricted access'); ?> <div class="acymailing_module<?php echo $params->get('moduleclass_sfx')?>" id="acymailing_module_<?php echo $formName; ?>"> <?php if(!empty($mootoolsIntro)) echo '<p class="acymailing_mootoolsintro">'.$mootoolsIntro.'</p>'; ?> <div class="acymailing_mootoolsbutton"> <?php $link = "rel=\"{handler: 'iframe', size: {x: ".$params->get('boxwidth',250).", y: ".$params->get('boxheight',200)."}}\" class=\"modal acymailing_togglemodule\""; $href=acymailing_completeLink('sub&task=display&formid='.$module->id,true); ?> <p><a <?php echo $link; ?> id="acymailing_togglemodule_<?php echo $formName; ?>" href="<?php echo $href;?>"><?php echo $mootoolsButton ?></a></p> </div> </div>
gpl-2.0
networksoft/declarafacil.com.co
plugins/editors-xtd/uniform/uniform.php
2114
<?php /** * @version $Id: uniform.php 19014 2012-11-28 04:48:56Z thailv $ * @package JSNUniform * @subpackage Plugin * @author JoomlaShine Team <support@joomlashine.com> * @copyright Copyright (C) 2015 JoomlaShine.com. All Rights Reserved. * @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html * * Websites: http://www.joomlashine.com * Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html */ defined('_JEXEC') or die('Restricted access'); /** * Plugin button select form in articles view * * @package Joomla.Plugin * * @subpackage Content.joomla * * @since 1.6 */ class plgButtonUniform extends JPlugin { /** * Constructor * * For php4 compatability we must not use the __constructor as a constructor for plugins * because func_get_args ( void ) returns a copy of all passed arguments NOT references. * This causes problems with cross-referencing necessary for the observer design pattern. * * @param object &$subject The object to observe * * @param array $config An array that holds the plugin configuration * * @since 1.5 */ function plgButtonUniform(&$subject, $config) { parent::__construct($subject, $config); $this->loadLanguage(); } /** * Display the button * * @param String $name Name button * * @return array A two element array of (imageName, textToInsert) */ function onDisplay($name) { $js = " function jsnSelectForm(id) { jInsertEditorText('{uniform form='+id+'/}', '" . $name . "'); SqueezeBox.close(); }"; $doc = JFactory::getDocument(); $doc->addScriptDeclaration($js); $link = 'index.php?option=com_uniform&amp;view=forms&amp;task=forms.viewSelectForm&amp;tmpl=component'; JHtml::_('behavior.modal'); $button = new JObject; $button->set('modal', true); $button->set('class', 'btn'); $button->set('link', $link); $button->set('text', JText::_('JSN_UNIFORM')); $button->set('name', 'list'); $button->set('options', "{handler: 'iframe', size: {x: 600, y: 200}}"); return $button; } }
gpl-2.0
grublits/Drupal-8
core/modules/views/src/Plugin/views/display/PathPluginBase.php
15196
<?php /** * @file * Contains \Drupal\views\Plugin\views\display\PathPluginBase. */ namespace Drupal\views\Plugin\views\display; use Drupal\Core\Form\FormErrorInterface; use Drupal\Core\State\StateInterface; use Drupal\Core\Routing\RouteCompiler; use Drupal\Core\Routing\RouteProviderInterface; use Drupal\views\Views; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; /** * The base display plugin for path/callbacks. This is used for pages and feeds. * * @see \Drupal\views\EventSubscriber\RouteSubscriber */ abstract class PathPluginBase extends DisplayPluginBase implements DisplayRouterInterface { /** * The route provider. * * @var \Drupal\Core\Routing\RouteProviderInterface */ protected $routeProvider; /** * The state key value store. * * @var \Drupal\Core\State\StateInterface */ protected $state; /** * The form error helper. * * @var \Drupal\Core\Form\FormErrorInterface */ protected $formError; /** * Constructs a PathPluginBase object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Routing\RouteProviderInterface $route_provider * The route provider. * @param \Drupal\Core\State\StateInterface $state * The state key value store. * @param \Drupal\Core\Form\FormErrorInterface $form_error * The form error helper. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, StateInterface $state, FormErrorInterface $form_error) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->routeProvider = $route_provider; $this->state = $state; $this->formError = $form_error; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('router.route_provider'), $container->get('state'), $container->get('form_validator') ); } /** * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::hasPath(). */ public function hasPath() { return TRUE; } /** * {@inheritdoc} */ public function getPath() { $bits = explode('/', $this->getOption('path')); if ($this->isDefaultTabPath()) { array_pop($bits); } return implode('/', $bits); } /** * Determines if this display's path is a default tab. * * @return bool * TRUE if the display path is for a default tab, FALSE otherwise. */ protected function isDefaultTabPath() { $menu = $this->getOption('menu'); $tab_options = $this->getOption('tab_options'); return $menu['type'] == 'default tab' && !empty($tab_options['type']) && $tab_options['type'] != 'none'; } /** * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase:defineOptions(). */ protected function defineOptions() { $options = parent::defineOptions(); $options['path'] = array('default' => ''); $options['route_name'] = array('default' => ''); return $options; } /** * Generates a route entry for a given view and display. * * @param string $view_id * The ID of the view. * @param string $display_id * The current display ID. * * @return \Symfony\Component\Routing\Route * The route for the view. */ protected function getRoute($view_id, $display_id) { $defaults = array( '_controller' => 'Drupal\views\Routing\ViewPageController::handle', 'view_id' => $view_id, 'display_id' => $display_id, ); // @todo How do we apply argument validation? $bits = explode('/', $this->getOption('path')); // @todo Figure out validation/argument loading. // Replace % with %views_arg for menu autoloading and add to the // page arguments so the argument actually comes through. $arg_counter = 0; $argument_ids = array_keys((array) $this->getOption('arguments')); $total_arguments = count($argument_ids); $argument_map = array(); // Replace arguments in the views UI (defined via %) with parameters in // routes (defined via {}). As a name for the parameter use arg_$key, so // it can be pulled in the views controller from the request. foreach ($bits as $pos => $bit) { if ($bit == '%') { // Generate the name of the parameter using the key of the argument // handler. $arg_id = 'arg_' . $arg_counter++; $bits[$pos] = '{' . $arg_id . '}'; } elseif (strpos($bit, '%') === 0) { // Use the name defined in the path. $parameter_name = substr($bit, 1); $arg_id = 'arg_' . $arg_counter++; $argument_map[$arg_id] = $parameter_name; $bits[$pos] = '{' . $parameter_name . '}'; } } // Add missing arguments not defined in the path, but added as handler. while (($total_arguments - $arg_counter) > 0) { $arg_id = 'arg_' . $arg_counter++; $bit = '{' . $arg_id . '}'; // In contrast to the previous loop add the defaults here, as % was not // specified, which means the argument is optional. $defaults[$arg_id] = NULL; $bits[] = $bit; } // If this is to be a default tab, create the route for the parent path. if ($this->isDefaultTabPath()) { $bit = array_pop($bits); if (empty($bits)) { $bits[] = $bit; } } $route_path = '/' . implode('/', $bits); $route = new Route($route_path, $defaults); // Add access check parameters to the route. $access_plugin = $this->getPlugin('access'); if (!isset($access_plugin)) { // @todo Do we want to support a default plugin in getPlugin itself? $access_plugin = Views::pluginManager('access')->createInstance('none'); } $access_plugin->alterRouteDefinition($route); // @todo Figure out whether _access_mode ANY is the proper one. This is // particular important for altering routes. $route->setOption('_access_mode', 'ANY'); // Set the argument map, in order to support named parameters. $route->setOption('_view_argument_map', $argument_map); return $route; } /** * {@inheritdoc} */ public function collectRoutes(RouteCollection $collection) { $view_id = $this->view->storage->id(); $display_id = $this->display['id']; $route = $this->getRoute($view_id, $display_id); if (!($route_name = $this->getOption('route_name'))) { $route_name = "view.$view_id.$display_id"; } $collection->add($route_name, $route); return array("$view_id.$display_id" => $route_name); } /** * {@inheritdoc} */ public function alterRoutes(RouteCollection $collection) { $view_route_names = array(); $view_path = $this->getPath(); foreach ($collection->all() as $name => $route) { // Find all paths which match the path of the current display.. $route_path = RouteCompiler::getPathWithoutDefaults($route); $route_path = RouteCompiler::getPatternOutline($route_path); // Ensure that we don't override a route which is already controlled by // views. if (!$route->hasDefault('view_id') && ('/' . $view_path == $route_path)) { $parameters = $route->compile()->getPathVariables(); // @todo Figure out whether we need to merge some settings (like // requirements). // Replace the existing route with a new one based on views. $collection->remove($name); $view_id = $this->view->storage->id(); $display_id = $this->display['id']; $route = $this->getRoute($view_id, $display_id); $path = $route->getPath(); // Replace the path with the original parameter names and add a mapping. $argument_map = array(); // We assume that the numeric ids of the parameters match the one from // the view argument handlers. foreach ($parameters as $position => $parameter_name) { $path = str_replace('arg_' . $position, $parameter_name, $path); $argument_map['arg_' . $position] = $parameter_name; } // Set the corrected path and the mapping to the route object. $route->setOption('_view_argument_map', $argument_map); $route->setPath($path); $collection->add($name, $route); $view_route_names[$view_id . '.' . $display_id] = $name; } } return $view_route_names; } /** * {@inheritdoc} */ public function executeHookMenuLinkDefaults(array &$existing_links) { $links = array(); // Replace % with the link to our standard views argument loader // views_arg_load -- which lives in views.module. $bits = explode('/', $this->getOption('path')); // Replace % with %views_arg for menu autoloading and add to the // page arguments so the argument actually comes through. foreach ($bits as $pos => $bit) { if ($bit == '%') { // If a view requires any arguments we cannot create a static menu link. return array(); } } $view_route_names = $this->state->get('views.view_route_names') ?: array(); $path = implode('/', $bits); $menu_link_id = 'views.' . str_replace('/', '.', $path); if ($path) { $menu = $this->getOption('menu'); if (!empty($menu['type']) && $menu['type'] == 'normal') { $links[$menu_link_id] = array(); // Some views might override existing paths, so we have to set the route // name based upon the altering. $view_id_display = "{$this->view->storage->id()}.{$this->display['id']}"; $links[$menu_link_id] = array( 'route_name' => isset($view_route_names[$view_id_display]) ? $view_route_names[$view_id_display] : "view.$view_id_display", // Identify URL embedded arguments and correlate them to a handler. 'load arguments' => array($this->view->storage->id(), $this->display['id'], '%index'), 'machine_name' => $menu_link_id, ); $links[$menu_link_id]['title'] = $menu['title']; $links[$menu_link_id]['description'] = $menu['description']; if (isset($menu['weight'])) { $links[$menu_link_id]['weight'] = intval($menu['weight']); } // Insert item into the proper menu. $links[$menu_link_id]['menu_name'] = $menu['name']; } } return $links; } /** * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::execute(). */ public function execute() { // Prior to this being called, the $view should already be set to this // display, and arguments should be set on the view. $this->view->build(); if (!empty($this->view->build_info['fail'])) { throw new NotFoundHttpException(); } if (!empty($this->view->build_info['denied'])) { throw new AccessDeniedHttpException(); } } /** * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::optionsSummary(). */ public function optionsSummary(&$categories, &$options) { parent::optionsSummary($categories, $options); $categories['page'] = array( 'title' => t('Page settings'), 'column' => 'second', 'build' => array( '#weight' => -10, ), ); $path = strip_tags($this->getOption('path')); if (empty($path)) { $path = t('No path is set'); } else { $path = '/' . $path; } $options['path'] = array( 'category' => 'page', 'title' => t('Path'), 'value' => views_ui_truncate($path, 24), ); } /** * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::buildOptionsForm(). */ public function buildOptionsForm(&$form, &$form_state) { parent::buildOptionsForm($form, $form_state); switch ($form_state['section']) { case 'path': $form['#title'] .= t('The menu path or URL of this view'); $form['path'] = array( '#type' => 'textfield', '#title' => t('Path'), '#description' => t('This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term'), '#default_value' => $this->getOption('path'), '#field_prefix' => '<span dir="ltr">' . url(NULL, array('absolute' => TRUE)), '#field_suffix' => '</span>&lrm;', '#attributes' => array('dir' => 'ltr'), // Account for the leading backslash. '#maxlength' => 254, ); break; } } /** * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::validateOptionsForm(). */ public function validateOptionsForm(&$form, &$form_state) { parent::validateOptionsForm($form, $form_state); if ($form_state['section'] == 'path') { $errors = $this->validatePath($form_state['values']['path']); foreach ($errors as $error) { $this->formError->setError($form['path'], $form_state, $error); } // Automatically remove '/' and trailing whitespace from path. $form_state['values']['path'] = trim($form_state['values']['path'], '/ '); } } /** * Overrides \Drupal\views\Plugin\views\display\DisplayPluginBase::submitOptionsForm(). */ public function submitOptionsForm(&$form, &$form_state) { parent::submitOptionsForm($form, $form_state); if ($form_state['section'] == 'path') { $this->setOption('path', $form_state['values']['path']); } } /** * Validates the path of the display. * * @param string $path * The path to validate. * * @return array * A list of error strings. */ protected function validatePath($path) { $errors = array(); if (strpos($path, '%') === 0) { $errors[] = $this->t('"%" may not be used for the first segment of a path.'); } $path_sections = explode('/', $path); // Symfony routing does not allow to use numeric placeholders. // @see \Symfony\Component\Routing\RouteCompiler $numeric_placeholders = array_filter($path_sections, function ($section) { return (preg_match('/^%(.*)/', $section, $matches) && is_numeric($matches[1])); }); if (!empty($numeric_placeholders)) { $errors[] = $this->t("Numeric placeholders may not be used. Please use plain placeholders (%)."); } return $errors; } /** * {@inheritdoc} */ public function validate() { $errors = parent::validate(); $errors += $this->validatePath($this->getOption('path')); return $errors; } }
gpl-2.0
vanfanel/scummvm
engines/saga/sfuncs_ihnm.cpp
12702
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifdef ENABLE_IHNM // Scripting module script function component #include "saga/saga.h" #include "saga/gfx.h" #include "saga/actor.h" #include "saga/animation.h" #include "saga/console.h" #include "saga/events.h" #include "saga/font.h" #include "saga/interface.h" #include "saga/music.h" #include "saga/itedata.h" #include "saga/puzzle.h" #include "saga/render.h" #include "saga/sound.h" #include "saga/sndres.h" #include "saga/resource.h" #include "saga/script.h" #include "saga/objectmap.h" #include "saga/scene.h" #include "saga/isomap.h" #include "common/config-manager.h" namespace Saga { void Script::setupIHNMScriptFuncList() { static const ScriptFunctionDescription IHNMScriptFunctionsList[IHNM_SCRIPT_FUNCTION_MAX] = { OPCODE(sfNull), OPCODE(sfWait), OPCODE(sfTakeObject), OPCODE(sfIsCarried), OPCODE(sfStatusBar), OPCODE(sfMainMode), OPCODE(sfScriptWalkTo), OPCODE(sfScriptDoAction), OPCODE(sfSetActorFacing), OPCODE(sfStartBgdAnim), OPCODE(sfStopBgdAnim), OPCODE(sfLockUser), OPCODE(sfPreDialog), OPCODE(sfKillActorThreads), OPCODE(sfFaceTowards), OPCODE(sfSetFollower), OPCODE(sfScriptGotoScene), OPCODE(sfSetObjImage), OPCODE(sfSetObjName), OPCODE(sfGetObjImage), OPCODE(sfGetNumber), OPCODE(sfScriptOpenDoor), OPCODE(sfScriptCloseDoor), OPCODE(sfSetBgdAnimSpeed), OPCODE(sfCycleColors), OPCODE(sfDoCenterActor), OPCODE(sfStartBgdAnimSpeed), OPCODE(sfScriptWalkToAsync), OPCODE(sfEnableZone), OPCODE(sfSetActorState), OPCODE(sfScriptMoveTo), OPCODE(sfSceneEq), OPCODE(sfDropObject), OPCODE(sfFinishBgdAnim), OPCODE(sfSwapActors), OPCODE(sfSimulSpeech), OPCODE(sfScriptWalk), OPCODE(sfCycleFrames), OPCODE(sfSetFrame), OPCODE(sfSetPortrait), OPCODE(sfSetProtagPortrait), OPCODE(sfChainBgdAnim), OPCODE(sfScriptSpecialWalk), OPCODE(sfPlaceActor), OPCODE(sfCheckUserInterrupt), OPCODE(sfScriptWalkRelative), OPCODE(sfScriptMoveRelative), OPCODE(sfSimulSpeech2), OPCODE(sfPsychicProfile), OPCODE(sfPsychicProfileOff), OPCODE(sfSetProtagState), OPCODE(sfResumeBgdAnim), OPCODE(sfThrowActor), OPCODE(sfWaitWalk), OPCODE(sfScriptSceneID), OPCODE(sfChangeActorScene), OPCODE(sfScriptClimb), OPCODE(sfSetDoorState), OPCODE(sfSetActorZ), OPCODE(sfScriptText), OPCODE(sfGetActorX), OPCODE(sfGetActorY), OPCODE(sfEraseDelta), OPCODE(sfPlayMusic), OPCODE(sfNull), OPCODE(sfEnableEscape), OPCODE(sfPlaySound), OPCODE(sfPlayLoopedSound), OPCODE(sfGetDeltaFrame), OPCODE(sfNull), OPCODE(sfNull), OPCODE(sfRand), OPCODE(sfFadeMusic), OPCODE(sfNull), OPCODE(sfSetChapterPoints), OPCODE(sfSetPortraitBgColor), OPCODE(sfScriptStartCutAway), OPCODE(sfReturnFromCutAway), OPCODE(sfEndCutAway), OPCODE(sfGetMouseClicks), OPCODE(sfResetMouseClicks), OPCODE(sfWaitFrames), OPCODE(sfScriptFade), OPCODE(sfScriptStartVideo), OPCODE(sfScriptReturnFromVideo), OPCODE(sfScriptEndVideo), OPCODE(sfSetActorZ), OPCODE(sfShowIHNMDemoHelpBg), OPCODE(sfAddIHNMDemoHelpTextLine), OPCODE(sfShowIHNMDemoHelpPage), OPCODE(sfVstopFX), OPCODE(sfVstopLoopedFX), OPCODE(sfDemoSetInteractive), // only used in the demo version of IHNM OPCODE(sfDemoIsInteractive), OPCODE(sfVsetTrack), OPCODE(sfGetPoints), OPCODE(sfSetGlobalFlag), OPCODE(sfClearGlobalFlag), OPCODE(sfTestGlobalFlag), OPCODE(sfSetPoints), OPCODE(sfSetSpeechBox), OPCODE(sfDebugShowData), OPCODE(sfWaitFramesEsc), OPCODE(sfQueueMusic), OPCODE(sfDisableAbortSpeeches) }; _scriptFunctionsList = IHNMScriptFunctionsList; } void Script::sfSetChapterPoints(SCRIPTFUNC_PARAMS) { int chapter = _vm->_scene->currentChapterNumber(); _vm->_ethicsPoints[chapter] = thread->pop(); int16 barometer = thread->pop(); static PalEntry cur_pal[PAL_ENTRIES]; PalEntry portraitBgColor = _vm->_interface->_portraitBgColor; byte portraitColor = (_vm->getLanguage() == Common::ES_ESP) ? 253 : 254; _vm->_spiritualBarometer = _vm->_ethicsPoints[chapter] * 256 / barometer; _vm->_scene->setChapterPointsChanged(true); // don't save this music when saving in IHNM // Set the portrait bg color, in case a saved state is restored from the // launcher. In this case, sfSetPortraitBgColor is not called, thus the // portrait color will always be 0 (black). if (portraitBgColor.red == 0 && portraitBgColor.green == 0 && portraitBgColor.blue == 0) portraitBgColor.green = 255; if (_vm->_spiritualBarometer > 255) _vm->_gfx->setPaletteColor(portraitColor, 0xff, 0xff, 0xff); else _vm->_gfx->setPaletteColor(portraitColor, _vm->_spiritualBarometer * portraitBgColor.red / 256, _vm->_spiritualBarometer * portraitBgColor.green / 256, _vm->_spiritualBarometer * portraitBgColor.blue / 256); _vm->_gfx->getCurrentPal(cur_pal); _vm->_gfx->setPalette(cur_pal); } void Script::sfSetPortraitBgColor(SCRIPTFUNC_PARAMS) { int16 red = thread->pop(); int16 green = thread->pop(); int16 blue = thread->pop(); _vm->_interface->setPortraitBgColor(red, green, blue); } void Script::sfScriptStartCutAway(SCRIPTFUNC_PARAMS) { int16 cut = thread->pop(); thread->pop(); // Not used int16 fade = thread->pop(); _vm->_anim->setCutAwayMode(kPanelCutaway); _vm->_anim->playCutaway(cut, fade != 0); } void Script::sfReturnFromCutAway(SCRIPTFUNC_PARAMS) { _vm->_anim->returnFromCutaway(); thread->wait(kWaitTypeWakeUp); } void Script::sfEndCutAway(SCRIPTFUNC_PARAMS) { _vm->_anim->endCutaway(); } void Script::sfGetMouseClicks(SCRIPTFUNC_PARAMS) { thread->_returnValue = _vm->getMouseClickCount(); } void Script::sfResetMouseClicks(SCRIPTFUNC_PARAMS) { _vm->resetMouseClickCount(); } void Script::sfWaitFrames(SCRIPTFUNC_PARAMS) { int16 frames = thread->pop(); if (!_skipSpeeches) thread->waitFrames(_vm->_frameCount + frames); } void Script::sfScriptFade(SCRIPTFUNC_PARAMS) { int16 firstPalEntry = thread->pop(); int16 lastPalEntry = thread->pop(); int16 startingBrightness = thread->pop(); int16 endingBrightness = thread->pop(); Event event; static PalEntry cur_pal[PAL_ENTRIES]; _vm->_gfx->getCurrentPal(cur_pal); event.type = kEvTImmediate; event.code = kPalEvent; event.op = kEventPalFade; event.time = 0; event.duration = kNormalFadeDuration; event.data = cur_pal; event.param = startingBrightness; event.param2 = endingBrightness; event.param3 = firstPalEntry; event.param4 = lastPalEntry - firstPalEntry + 1; _vm->_events->queue(event); } void Script::sfScriptStartVideo(SCRIPTFUNC_PARAMS) { int16 vid = thread->pop(); int16 fade = thread->pop(); _vm->_anim->setCutAwayMode(kPanelVideo); _vm->_anim->startVideo(vid, fade != 0); } void Script::sfScriptReturnFromVideo(SCRIPTFUNC_PARAMS) { _vm->_anim->returnFromVideo(); } void Script::sfScriptEndVideo(SCRIPTFUNC_PARAMS) { _vm->_anim->endVideo(); } void Script::sfShowIHNMDemoHelpBg(SCRIPTFUNC_PARAMS) { _ihnmDemoCurrentY = 0; _vm->_scene->_textList.clear(); _vm->_interface->setMode(kPanelConverse); _vm->_scene->showPsychicProfile(NULL); } void Script::sfAddIHNMDemoHelpTextLine(SCRIPTFUNC_PARAMS) { int stringId = thread->pop(); TextListEntry textEntry; Event event; textEntry.knownColor = kKnownColorBlack; textEntry.useRect = true; textEntry.rect.left = 245; textEntry.rect.setHeight(210 + 76); textEntry.rect.setWidth(226); textEntry.rect.top = 76 + _ihnmDemoCurrentY; textEntry.font = kKnownFontVerb; textEntry.flags = (FontEffectFlags)(kFontCentered); textEntry.text = thread->_strings->getString(stringId); TextListEntry *_psychicProfileTextEntry = _vm->_scene->_textList.addEntry(textEntry); event.type = kEvTOneshot; event.code = kTextEvent; event.op = kEventDisplay; event.data = _psychicProfileTextEntry; _vm->_events->queue(event); _ihnmDemoCurrentY += _vm->_font->getHeight(kKnownFontVerb, thread->_strings->getString(stringId), 226, kFontCentered); } void Script::sfShowIHNMDemoHelpPage(SCRIPTFUNC_PARAMS) { // Note: The IHNM demo changes panel mode to 8 (kPanelProtect in ITE) // when changing pages _vm->_interface->setMode(kPanelPlacard); _ihnmDemoCurrentY = 0; } void Script::sfVstopFX(SCRIPTFUNC_PARAMS) { _vm->_sound->stopSound(); } void Script::sfVstopLoopedFX(SCRIPTFUNC_PARAMS) { _vm->_sound->stopSound(); } void Script::sfDemoSetInteractive(SCRIPTFUNC_PARAMS) { if (thread->pop() == 0) { _vm->_interface->deactivate(); _vm->_interface->setMode(kPanelNull); } // Note: the original also sets an appropriate flag here, but we don't, // as we don't use it } void Script::sfDemoIsInteractive(SCRIPTFUNC_PARAMS) { thread->_returnValue = 0; } void Script::sfVsetTrack(SCRIPTFUNC_PARAMS) { int16 chapter = thread->pop(); int16 sceneNumber = thread->pop(); int16 actorsEntrance = thread->pop(); debug(2, "sfVsetTrrack(%d, %d, %d)", chapter, sceneNumber, actorsEntrance); _vm->_scene->changeScene(sceneNumber, actorsEntrance, kTransitionFade, chapter); } void Script::sfGetPoints(SCRIPTFUNC_PARAMS) { int16 index = thread->pop(); if (index >= 0 && index < ARRAYSIZE(_vm->_ethicsPoints)) thread->_returnValue = _vm->_ethicsPoints[index]; else thread->_returnValue = 0; } void Script::sfSetGlobalFlag(SCRIPTFUNC_PARAMS) { int16 flag = thread->pop(); if (flag >= 0 && flag < 32) _vm->_globalFlags |= (1 << flag); } void Script::sfClearGlobalFlag(SCRIPTFUNC_PARAMS) { int16 flag = thread->pop(); if (flag >= 0 && flag < 32) _vm->_globalFlags &= ~(1 << flag); } void Script::sfTestGlobalFlag(SCRIPTFUNC_PARAMS) { int16 flag = thread->pop(); if (flag >= 0 && flag < 32 && _vm->_globalFlags & (1 << flag)) thread->_returnValue = 1; else thread->_returnValue = 0; } void Script::sfSetPoints(SCRIPTFUNC_PARAMS) { int16 index = thread->pop(); int16 points = thread->pop(); if (index >= 0 && index < ARRAYSIZE(_vm->_ethicsPoints)) _vm->_ethicsPoints[index] = points; } void Script::sfSetSpeechBox(SCRIPTFUNC_PARAMS) { int16 param1 = thread->pop(); int16 param2 = thread->pop(); int16 param3 = thread->pop(); int16 param4 = thread->pop(); _vm->_actor->_speechBoxScript.left = param1; _vm->_actor->_speechBoxScript.top = param2; _vm->_actor->_speechBoxScript.setWidth(param3 - param1); _vm->_actor->_speechBoxScript.setHeight(param4 - param2); } void Script::sfDebugShowData(SCRIPTFUNC_PARAMS) { int16 param = thread->pop(); Common::String buf = Common::String::format("Reached breakpoint %d", param); _vm->_interface->setStatusText(buf.c_str()); } void Script::sfWaitFramesEsc(SCRIPTFUNC_PARAMS) { thread->_returnValue = _vm->_framesEsc; } void Script::sfQueueMusic(SCRIPTFUNC_PARAMS) { int16 param1 = thread->pop(); int16 param2 = thread->pop(); Event event; if (param1 < 0) { _vm->_music->stop(); return; } if (uint(param1) >= _vm->_music->_songTable.size()) { warning("sfQueueMusic: Wrong song number (%d > %d)", param1, _vm->_music->_songTable.size() - 1); } else { _vm->_music->resetVolume(); _vm->_events->queueMusic(_vm->_music->_songTable[param1], param2, _vm->ticksToMSec(1000)); if (!_vm->_scene->haveChapterPointsChanged()) { _vm->_scene->setCurrentMusicTrack(param1); _vm->_scene->setCurrentMusicRepeat(param2); } else { // Don't save this music track when saving in IHNM _vm->_scene->setChapterPointsChanged(false); } } } void Script::sfDisableAbortSpeeches(SCRIPTFUNC_PARAMS) { _vm->_interface->disableAbortSpeeches(thread->pop() != 0); } void Script::sfPsychicProfile(SCRIPTFUNC_PARAMS) { thread->wait(kWaitTypePlacard); _vm->_scene->showPsychicProfile(thread->_strings->getString(thread->pop())); } void Script::sfPsychicProfileOff(SCRIPTFUNC_PARAMS) { // This is called a while after the psychic profile is // opened, to close it automatically _vm->_scene->clearPsychicProfile(); } } // End of namespace Saga #endif
gpl-2.0
blisskid/xuanqi
wp-content/themes/dt-the7/inc/shortcodes/includes/quote/quote.php
2296
<?php /** * Quote shortcode. * */ // File Security Check if ( ! defined( 'ABSPATH' ) ) { exit; } if ( ! class_exists( 'DT_Shortcode_Quote', false ) ) { class DT_Shortcode_Quote extends DT_Shortcode { static protected $instance; public static function get_instance() { if ( !self::$instance ) { self::$instance = new DT_Shortcode_Quote(); } return self::$instance; } protected function __construct() { add_shortcode( 'dt_quote', array( $this, 'shortcode' ) ); } public function shortcode( $atts, $content = null ) { $default_atts = array( 'type' => 'pullquote', 'layout' => 'left', 'font_size' => 'big', 'size' => '1', 'animation' => 'none', 'background' => 'plain' ); extract( shortcode_atts( $default_atts, $atts ) ); $font_size = sanitize_key( $font_size ); $type = sanitize_key( $type ); $layout = sanitize_key( $layout ); $size = sanitize_key( $size ); $background = sanitize_key( $background ); $classes = array(); $classes[] = presscore_get_font_size_class( $font_size ); if ( presscore_shortcode_animation_on( $animation ) ) { $classes[] = presscore_get_shortcode_animation_html_class( $animation ); } if ( 'blockquote' != $type ) { $tag = 'q'; $autop = false; $classes[] = 'shortcode-pullquote'; $classes[] = 'wf-cell'; if ( 'right' == $layout ) { $classes[] = 'align-right'; } else { $classes[] = 'align-left'; } switch ( $size ) { case '2': $classes[] = 'wf-1-2'; break; case '3': $classes[] = 'wf-1-3'; break; case '4': $classes[] = 'wf-1-4'; break; default: $classes[] = 'wf-1'; } } else { $tag = 'blockquote'; $autop = true; $classes[] = 'shortcode-blockquote'; if ( 'fancy' == $background ) { $classes[] = 'block-style-widget'; } } $classes = implode( ' ', $classes ); $output = sprintf( '<%1$s class="%2$s">%3$s</%1$s>', $tag, esc_attr( $classes ), /** * @see sanitize-functions.php */ presscore_remove_wpautop( $content, $autop ) ); return $output; } } // create shortcode DT_Shortcode_Quote::get_instance(); }
gpl-2.0
mygithome002/server
src/game/AuctionHouse/AuctionHouseMgr.cpp
30154
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero> * Copyright (C) 2011-2016 Nostalrius <https://nostalrius.org> * Copyright (C) 2016-2017 Elysium Project <https://github.com/elysium-project> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "AuctionHouseMgr.h" #include "Database/DatabaseEnv.h" #include "SQLStorages.h" #include "DBCStores.h" #include "ProgressBar.h" #include "AccountMgr.h" #include "Item.h" #include "Language.h" #include "Log.h" #include "ObjectMgr.h" #include "ObjectGuid.h" #include "Player.h" #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Mail.h" #include "Policies/SingletonImp.h" INSTANTIATE_SINGLETON_1(AuctionHouseMgr); bool AuctionHouseObject::RemoveAuction(uint32 id) { if (AuctionsMap.erase(id)) { sObjectMgr.FreeAuctionID(id); return true; } return false; } AuctionHouseMgr::AuctionHouseMgr() { } AuctionHouseMgr::~AuctionHouseMgr() { for (ItemMap::const_iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr) delete itr->second; } AuctionHouseObject * AuctionHouseMgr::GetAuctionsMap(AuctionHouseEntry const* house) { if (sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_AUCTION)) return &mNeutralAuctions; // team have linked auction houses switch (GetAuctionHouseTeam(house)) { case ALLIANCE: return &mAllianceAuctions; case HORDE: return &mHordeAuctions; default: return &mNeutralAuctions; } } uint32 AuctionHouseMgr::GetAuctionDeposit(AuctionHouseEntry const* entry, uint32 time, Item *pItem) { float deposit = float(pItem->GetProto()->SellPrice * pItem->GetCount() * (time / MIN_AUCTION_TIME)); deposit = deposit * entry->depositPercent / 100.0f; float min_deposit = float(sWorld.getConfig(CONFIG_UINT32_AUCTION_DEPOSIT_MIN)); if (deposit < min_deposit) deposit = min_deposit; return uint32(deposit * sWorld.getConfig(CONFIG_FLOAT_RATE_AUCTION_DEPOSIT)); } // does not clear ram void AuctionHouseMgr::SendAuctionWonMail(AuctionEntry *auction) { Item *pItem = GetAItem(auction->itemGuidLow); if (!pItem) return; ObjectGuid bidder_guid = ObjectGuid(HIGHGUID_PLAYER, auction->bidder); Player *bidder = sObjectMgr.GetPlayer(bidder_guid); uint32 bidder_accId = 0; // data for gm.log if (sWorld.getConfig(CONFIG_BOOL_GM_LOG_TRADE)) { uint32 bidder_security = 0; std::string bidder_name; if (bidder) { bidder_accId = bidder->GetSession()->GetAccountId(); bidder_security = bidder->GetSession()->GetSecurity(); bidder_name = bidder->GetName(); } else { bidder_accId = sObjectMgr.GetPlayerAccountIdByGUID(bidder_guid); bidder_security = sAccountMgr.GetSecurity(bidder_accId); if (bidder_security > SEC_PLAYER) // not do redundant DB requests { if (!sObjectMgr.GetPlayerNameByGUID(bidder_guid, bidder_name)) bidder_name = sObjectMgr.GetMangosStringForDBCLocale(LANG_UNKNOWN); } } if (bidder_security > SEC_PLAYER) { ObjectGuid owner_guid = ObjectGuid(HIGHGUID_PLAYER, auction->owner); std::string owner_name; if (!sObjectMgr.GetPlayerNameByGUID(owner_guid, owner_name)) owner_name = sObjectMgr.GetMangosStringForDBCLocale(LANG_UNKNOWN); uint32 owner_accid = sObjectMgr.GetPlayerAccountIdByGUID(owner_guid); sLog.outCommand(bidder_accId, "GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)", bidder_name.c_str(), bidder_accId, pItem->GetProto()->Name1, pItem->GetEntry(), pItem->GetCount(), auction->bid, owner_name.c_str(), owner_accid); } } else if (!bidder) bidder_accId = sObjectMgr.GetPlayerAccountIdByGUID(bidder_guid); // receiver exist if (bidder || bidder_accId) { std::ostringstream msgAuctionWonSubject; msgAuctionWonSubject << auction->itemTemplate << ":0:" << AUCTION_WON; std::ostringstream msgAuctionWonBody; msgAuctionWonBody.width(16); msgAuctionWonBody << std::right << std::hex << auction->owner; msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout; DEBUG_LOG("AuctionWon body string : %s", msgAuctionWonBody.str().c_str()); // set owner to bidder (to prevent delete item with sender char deleting) // owner in `data` will set at mail receive and item extracting CharacterDatabase.PExecute("UPDATE item_instance SET owner_guid = '%u' WHERE guid='%u'", auction->bidder, pItem->GetGUIDLow()); CharacterDatabase.CommitTransaction(); if (bidder) bidder->GetSession()->SendAuctionBidderNotification(auction, true); else RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !! // will delete item or place to receiver mail list MailDraft(msgAuctionWonSubject.str(), msgAuctionWonBody.str()) .AddItem(pItem) .SendMailTo(MailReceiver(bidder, bidder_guid), auction, MAIL_CHECK_MASK_COPIED); } // receiver not exist else { CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow()); RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !! delete pItem; } } // call this method to send mail to auction owner, when auction is successful, it does not clear ram void AuctionHouseMgr::SendAuctionSuccessfulMail(AuctionEntry * auction) { ObjectGuid owner_guid = ObjectGuid(HIGHGUID_PLAYER, auction->owner); Player *owner = sObjectMgr.GetPlayer(owner_guid); uint32 owner_accId = 0; if (!owner) owner_accId = sObjectMgr.GetPlayerAccountIdByGUID(owner_guid); // owner exist if (owner || owner_accId) { std::ostringstream msgAuctionSuccessfulSubject; msgAuctionSuccessfulSubject << auction->itemTemplate << ":0:" << AUCTION_SUCCESSFUL; std::ostringstream auctionSuccessfulBody; uint32 auctionCut = auction->GetAuctionCut(); auctionSuccessfulBody.width(16); auctionSuccessfulBody << std::right << std::hex << auction->bidder; auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout; auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut; DEBUG_LOG("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str()); uint32 profit = auction->bid + auction->deposit - auctionCut; if (owner) { //send auction owner notification, bidder must be current! owner->GetSession()->SendAuctionOwnerNotification(auction, true); } MailDraft(msgAuctionSuccessfulSubject.str(), auctionSuccessfulBody.str()) .SetMoney(profit) .SendMailTo(MailReceiver(owner, owner_guid), auction, MAIL_CHECK_MASK_COPIED); } } // does not clear ram void AuctionHouseMgr::SendAuctionExpiredMail(AuctionEntry * auction) { // return an item in auction to its owner by mail Item *pItem = GetAItem(auction->itemGuidLow); if (!pItem) { sLog.outError("Auction item (GUID: %u) not found, and lost.", auction->itemGuidLow); return; } ObjectGuid owner_guid = ObjectGuid(HIGHGUID_PLAYER, auction->owner); Player *owner = sObjectMgr.GetPlayer(owner_guid); uint32 owner_accId = 0; if (!owner) owner_accId = sObjectMgr.GetPlayerAccountIdByGUID(owner_guid); // owner exist if (owner || owner_accId) { std::ostringstream subject; subject << auction->itemTemplate << ":0:" << AUCTION_EXPIRED; if (owner) owner->GetSession()->SendAuctionOwnerNotification(auction, false); else RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !! // will delete item or place to receiver mail list MailDraft(subject.str()) .AddItem(pItem) .SendMailTo(MailReceiver(owner, owner_guid), auction, MAIL_CHECK_MASK_COPIED); } // owner not found else { CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid='%u'", pItem->GetGUIDLow()); RemoveAItem(pItem->GetGUIDLow()); // we have to remove the item, before we delete it !! delete pItem; } } void AuctionHouseMgr::LoadAuctionItems() { // 0 1 2 3 4 5 6 7 8 9 10 11 QueryResult *result = CharacterDatabase.Query("SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, text, itemguid, itemEntry FROM auction JOIN item_instance ON itemguid = guid"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded 0 auction items"); return; } BarGoLink bar(result->GetRowCount()); uint32 count = 0; Field *fields; do { bar.step(); fields = result->Fetch(); uint32 item_guid = fields[10].GetUInt32(); uint32 item_template = fields[11].GetUInt32(); ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template); if (!proto) { sLog.outError("AuctionHouseMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid, item_template); continue; } Item *item = NewItemOrBag(proto); if (!item->LoadFromDB(item_guid, ObjectGuid(), fields, item_template)) { delete item; continue; } AddAItem(item); ++count; } while (result->NextRow()); delete result; sLog.outString(); sLog.outString(">> Loaded %u auction items", count); } void AuctionHouseMgr::LoadAuctions() { QueryResult *result = CharacterDatabase.Query("SELECT COUNT(*) FROM auction"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded 0 auctions. DB table `auction` is empty."); return; } Field *fields = result->Fetch(); uint32 AuctionCount = fields[0].GetUInt32(); delete result; if (!AuctionCount) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded 0 auctions. DB table `auction` is empty."); return; } result = CharacterDatabase.Query("SELECT id,houseid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit FROM auction"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(); sLog.outString(">> Loaded 0 auctions. DB table `auction` is empty."); return; } BarGoLink bar(AuctionCount); do { fields = result->Fetch(); bar.step(); AuctionEntry *auction = new AuctionEntry; auction->Id = fields[0].GetUInt32(); uint32 houseid = fields[1].GetUInt32(); auction->itemGuidLow = fields[2].GetUInt32(); auction->itemTemplate = fields[3].GetUInt32(); auction->owner = fields[4].GetUInt32(); auction->buyout = fields[5].GetUInt32(); auction->depositTime = 0; auction->expireTime = fields[6].GetUInt32(); auction->bidder = fields[7].GetUInt32(); auction->bid = fields[8].GetUInt32(); auction->startbid = fields[9].GetUInt32(); auction->deposit = fields[10].GetUInt32(); auction->auctionHouseEntry = NULL; // init later // check if sold item exists for guid // and item_template in fact (GetAItem will fail if problematic in result check in AuctionHouseMgr::LoadAuctionItems) Item* pItem = GetAItem(auction->itemGuidLow); if (!pItem) { auction->DeleteFromDB(); sLog.outError("Auction %u has not a existing item : %u, deleted", auction->Id, auction->itemGuidLow); delete auction; continue; } auction->auctionHouseEntry = sAuctionHouseStore.LookupEntry(houseid); if (!houseid) { // need for send mail, use goblin auctionhouse auction->auctionHouseEntry = sAuctionHouseStore.LookupEntry(7); // Attempt send item back to owner std::ostringstream msgAuctionCanceledOwner; msgAuctionCanceledOwner << auction->itemTemplate << ":0:" << AUCTION_CANCELED; // item will deleted or added to received mail list MailDraft(msgAuctionCanceledOwner.str(), "") // TODO: fix body .AddItem(pItem) .SendMailTo(MailReceiver(ObjectGuid(HIGHGUID_PLAYER, auction->owner)), auction, MAIL_CHECK_MASK_COPIED); RemoveAItem(auction->itemGuidLow); auction->DeleteFromDB(); delete auction; continue; } GetAuctionsMap(auction->auctionHouseEntry)->AddAuction(auction); } while (result->NextRow()); delete result; sLog.outString(); sLog.outString(">> Loaded %u auctions", AuctionCount); } void AuctionHouseMgr::AddAItem(Item* it) { MANGOS_ASSERT(it); MANGOS_ASSERT(mAitems.find(it->GetGUIDLow()) == mAitems.end()); mAitems[it->GetGUIDLow()] = it; } bool AuctionHouseMgr::RemoveAItem(uint32 id) { ItemMap::iterator i = mAitems.find(id); if (i == mAitems.end()) return false; mAitems.erase(i); return true; } void AuctionHouseMgr::Update() { mHordeAuctions.Update(); mAllianceAuctions.Update(); mNeutralAuctions.Update(); } uint32 AuctionHouseMgr::GetAuctionHouseTeam(AuctionHouseEntry const* house) { // auction houses have faction field pointing to PLAYER,* factions, // but player factions not have filled team field, and hard go from faction value to faction_template value, // so more easy just sort by auction house ids switch (house->houseId) { case 1: case 2: case 3: return ALLIANCE; case 4: case 5: case 6: return HORDE; case 7: default: return 0; // neutral } } AuctionHouseEntry const* AuctionHouseMgr::GetAuctionHouseEntry(Unit* unit) { uint32 houseid = 1; // dwarf auction house (used for normal cut/etc percents) if (!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_AUCTION)) { if (unit->GetTypeId() == TYPEID_UNIT) { // FIXME: found way for proper auctionhouse selection by another way // AuctionHouse.dbc have faction field with _player_ factions associated with auction house races. // but no easy way convert creature faction to player race faction for specific city uint32 factionTemplateId = unit->getFaction(); switch (factionTemplateId) { case 12: houseid = 1; break; // human case 29: houseid = 6; break; // orc, and generic for horde case 55: houseid = 2; break; // dwarf/gnome, and generic for alliance case 68: houseid = 4; break; // undead case 80: houseid = 3; break; // n-elf case 104: houseid = 5; break; // trolls case 120: houseid = 7; break; // booty bay, neutral case 474: houseid = 7; break; // gadgetzan, neutral case 534: houseid = 2; break; // Alliance Generic case 855: houseid = 7; break; // everlook, neutral default: // for unknown case { FactionTemplateEntry const* u_entry = sFactionTemplateStore.LookupEntry(factionTemplateId); if (!u_entry) houseid = 7; // goblin auction house else if (u_entry->ourMask & FACTION_MASK_ALLIANCE) houseid = 1; // human auction house else if (u_entry->ourMask & FACTION_MASK_HORDE) houseid = 6; // orc auction house else houseid = 7; // goblin auction house break; } } } else { Player* player = (Player*)unit; if (player->GetAuctionAccessMode() > 0) houseid = 7; else { switch (((Player*)unit)->GetTeam()) { case ALLIANCE: houseid = player->GetAuctionAccessMode() == 0 ? 1 : 6; break; case HORDE: houseid = player->GetAuctionAccessMode() == 0 ? 6 : 1; break; } } } } return sAuctionHouseStore.LookupEntry(houseid); } AuctionHouseEntry const* AuctionHouseMgr::GetAuctionHouseEntry(uint32 factionTemplateId) { uint32 houseid = 1; // dwarf auction house (used for normal cut/etc percents) switch (factionTemplateId) { case 12: houseid = 1; break; // human case 29: houseid = 6; break; // orc, and generic for horde case 55: houseid = 2; break; // dwarf/gnome, and generic for alliance case 68: houseid = 4; break; // undead case 80: houseid = 3; break; // n-elf case 104: houseid = 5; break; // trolls case 120: houseid = 7; break; // booty bay, neutral case 474: houseid = 7; break; // gadgetzan, neutral case 534: houseid = 2; break; // Alliance Generic case 855: houseid = 7; break; // everlook, neutral default: // for unknown case { FactionTemplateEntry const* u_entry = sFactionTemplateStore.LookupEntry(factionTemplateId); if (!u_entry) houseid = 7; // goblin auction house else if (u_entry->ourMask & FACTION_MASK_ALLIANCE) houseid = 1; // human auction house else if (u_entry->ourMask & FACTION_MASK_HORDE) houseid = 6; // orc auction house else houseid = 7; // goblin auction house break; } } return sAuctionHouseStore.LookupEntry(houseid); } void AuctionHouseObject::Update() { time_t curTime = sWorld.GetGameTime(); ///- Handle expired auctions AuctionEntryMap::iterator next; for (AuctionEntryMap::iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); itr = next) { if (itr->second->depositTime + 5*60 < curTime) // Locked for 5 minutes on IP to prevent AH snipping itr->second->lockedIpAddress.clear(); next = itr; ++next; if (curTime > (itr->second->expireTime)) { ///- Either cancel the auction if there was no bidder if (itr->second->bidder == 0) sAuctionMgr.SendAuctionExpiredMail(itr->second); ///- Or perform the transaction else { PlayerTransactionData data; data.type = "Bid"; data.parts[0].lowGuid = itr->second->owner; data.parts[0].itemsEntries[0] = itr->second->itemTemplate; Item* item = sAuctionMgr.GetAItem(itr->second->itemGuidLow); data.parts[0].itemsCount[0] = item ? item->GetCount() : 0; data.parts[0].itemsGuid[0] = itr->second->itemGuidLow; data.parts[1].lowGuid = itr->second->bidder; data.parts[1].money = itr->second->bid; sWorld.LogTransaction(data); //we should send an "item sold" message if the seller is online //we send the item to the winner //we send the money to the seller sAuctionMgr.SendAuctionSuccessfulMail(itr->second); sAuctionMgr.SendAuctionWonMail(itr->second); } ///- In any case clear the auction itr->second->DeleteFromDB(); sAuctionMgr.RemoveAItem(itr->second->itemGuidLow); delete itr->second; RemoveAuction(itr->first); } } } void AuctionHouseObject::BuildListBidderItems(WorldPacket& data, Player* player, uint32 listfrom, uint32& count, uint32& totalcount) { for (AuctionEntryMap::const_iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); ++itr) { AuctionEntry *Aentry = itr->second; if (Aentry && Aentry->bidder == player->GetGUIDLow()) { ++totalcount; if (count < 50 && totalcount > listfrom) if (itr->second->BuildAuctionInfo(data)) ++count; } } } void AuctionHouseObject::BuildListOwnerItems(WorldPacket& data, Player* player, uint32 listfrom, uint32& count, uint32& totalcount) { for (AuctionEntryMap::const_iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); ++itr) { AuctionEntry *Aentry = itr->second; if (Aentry && Aentry->owner == player->GetGUIDLow()) { ++totalcount; if (count < 50 && totalcount > listfrom) if (Aentry->BuildAuctionInfo(data)) ++count; } } } void AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player, AuctionHouseClientQuery const& query, uint32& count, uint32& totalcount) { // Happening often, and easy to deal with if (query.auctionMainCategory == 0xffffffff && query.auctionSubCategory == 0xffffffff && query.auctionSlotID == 0xffffffff && query.quality == 0xffffffff && query.levelmin == 0x00 && query.levelmax == 0x00 && query.usable == 0x00 && query.wsearchedname.empty()) { totalcount = AuctionsMap.size(); if (query.listfrom < totalcount) { AuctionEntryMap::iterator itr = AuctionsMap.begin(); std::advance(itr, query.listfrom); for (; itr != AuctionsMap.end(); ++itr) { itr->second->BuildAuctionInfo(data); if ((++count) >= 50) break; } } return; } time_t currTime = sWorld.GetGameTime(); std::string const& clientIp = player->GetSession()->GetRemoteAddress(); int loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); for (AuctionEntryMap::const_iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); ++itr) { AuctionEntry *Aentry = itr->second; Item *item = sAuctionMgr.GetAItem(Aentry->itemGuidLow); if (!item) continue; { ItemPrototype const *proto = item->GetProto(); if (query.auctionMainCategory != 0xffffffff && proto->Class != query.auctionMainCategory) continue; if (query.auctionSubCategory != 0xffffffff && proto->SubClass != query.auctionSubCategory) continue; if (query.auctionSlotID != 0xffffffff && proto->InventoryType != query.auctionSlotID && (query.auctionSlotID != INVTYPE_CHEST || query.auctionSlotID == INVTYPE_CHEST && proto->InventoryType != INVTYPE_ROBE)) continue; if (query.quality != 0xffffffff && proto->Quality < query.quality) continue; if (query.levelmin != 0x00 && (proto->RequiredLevel < query.levelmin || (query.levelmax != 0x00 && proto->RequiredLevel > query.levelmax))) continue; if (query.usable != 0x00 && player->CanUseItem(item) != EQUIP_ERR_OK) continue; if (query.usable != 0x00 && proto->Class == ITEM_CLASS_RECIPE) if (SpellEntry const* spell = sSpellMgr.GetSpellEntry(proto->Spells[0].SpellId)) if (player->HasSpell(spell->EffectTriggerSpell[EFFECT_INDEX_0])) continue; // IP locked auction if (!Aentry->lockedIpAddress.empty() && Aentry->lockedIpAddress != clientIp) continue; if (!query.wsearchedname.empty()) { std::string name = proto->Name1; if (name.empty()) continue; // local name if (loc_idx >= 0) { ItemLocale const *il = sObjectMgr.GetItemLocale(proto->ItemId); if (il) { if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty()) name = il->Name[loc_idx]; } } if (!Utf8FitTo(name, query.wsearchedname)) continue; } if (count < 50 && totalcount >= query.listfrom) { ++count; Aentry->BuildAuctionInfo(data); } } ++totalcount; } } // this function inserts to WorldPacket auction's data bool AuctionEntry::BuildAuctionInfo(WorldPacket & data) const { Item *pItem = sAuctionMgr.GetAItem(itemGuidLow); if (!pItem) { sLog.outError("auction to item, that doesn't exist !!!!"); return false; } data << uint32(Id); data << uint32(pItem->GetEntry()); // [-ZERO] no other infos about enchantment in 1.12 [?] //for (uint8 i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i) //{ data << uint32(pItem->GetEnchantmentId(EnchantmentSlot(PERM_ENCHANTMENT_SLOT))); // data << uint32(pItem->GetEnchantmentDuration(EnchantmentSlot(i))); // data << uint32(pItem->GetEnchantmentCharges(EnchantmentSlot(i))); //} data << uint32(pItem->GetItemRandomPropertyId()); // random item property id data << uint32(pItem->GetItemSuffixFactor()); // SuffixFactor data << uint32(pItem->GetCount()); // item->count data << uint32(pItem->GetSpellCharges()); // item->charge FFFFFFF data << ObjectGuid(HIGHGUID_PLAYER, owner); // Auction->owner data << uint32(startbid); // Auction->startbid (not sure if useful) data << uint32(bid ? GetAuctionOutBid() : 0); // minimal outbid data << uint32(buyout); // auction->buyout data << uint32((expireTime - time(NULL))*IN_MILLISECONDS); // time left data << ObjectGuid(HIGHGUID_PLAYER, bidder); // auction->bidder current data << uint32(bid); // current bid return true; } uint32 AuctionEntry::GetAuctionCut() const { return uint32(auctionHouseEntry->cutPercent * bid * sWorld.getConfig(CONFIG_FLOAT_RATE_AUCTION_CUT) / 100.0f); } /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c uint32 AuctionEntry::GetAuctionOutBid() const { uint32 outbid = (bid / 100) * 5; if (!outbid) outbid = 1; return outbid; } void AuctionEntry::DeleteFromDB() const { //No SQL injection (Id is integer) CharacterDatabase.PExecute("DELETE FROM auction WHERE id = '%u'", Id); } void AuctionEntry::SaveToDB() const { //No SQL injection (no strings) CharacterDatabase.PExecute("INSERT INTO auction (id,houseid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit) " "VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u')", Id, auctionHouseEntry->houseId, itemGuidLow, itemTemplate, owner, buyout, (uint64)expireTime, bidder, bid, startbid, deposit); }
gpl-2.0
11hks11/sy
src/main/webapp/js/plugs/echarts/echarts-master/src/chart/gauge/GaugeView.js
15306
define(function (require) { var PointerPath = require('./PointerPath'); var graphic = require('../../util/graphic'); var numberUtil = require('../../util/number'); var parsePercent = numberUtil.parsePercent; function parsePosition(seriesModel, api) { var center = seriesModel.get('center'); var width = api.getWidth(); var height = api.getHeight(); var size = Math.min(width, height); var cx = parsePercent(center[0], api.getWidth()); var cy = parsePercent(center[1], api.getHeight()); var r = parsePercent(seriesModel.get('radius'), size / 2); return { cx: cx, cy: cy, r: r }; } function formatLabel(label, labelFormatter) { if (labelFormatter) { if (typeof labelFormatter === 'string') { label = labelFormatter.replace('{value}', label); } else if (typeof labelFormatter === 'function') { label = labelFormatter(label); } } return label; } var PI2 = Math.PI * 2; var GaugeView = require('../../view/Chart').extend({ type: 'gauge', render: function (seriesModel, ecModel, api) { this.group.removeAll(); var colorList = seriesModel.get('axisLine.lineStyle.color'); var posInfo = parsePosition(seriesModel, api); this._renderMain( seriesModel, ecModel, api, colorList, posInfo ); }, _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) { var group = this.group; var axisLineModel = seriesModel.getModel('axisLine'); var lineStyleModel = axisLineModel.getModel('lineStyle'); var clockwise = seriesModel.get('clockwise'); var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI; var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI; var angleRangeSpan = (endAngle - startAngle) % PI2; var prevEndAngle = startAngle; var axisLineWidth = lineStyleModel.get('width'); for (var i = 0; i < colorList.length; i++) { // Clamp var percent = Math.min(Math.max(colorList[i][0], 0), 1); var endAngle = startAngle + angleRangeSpan * percent; var sector = new graphic.Sector({ shape: { startAngle: prevEndAngle, endAngle: endAngle, cx: posInfo.cx, cy: posInfo.cy, clockwise: clockwise, r0: posInfo.r - axisLineWidth, r: posInfo.r }, silent: true }); sector.setStyle({ fill: colorList[i][1] }); sector.setStyle(lineStyleModel.getLineStyle( // Because we use sector to simulate arc // so the properties for stroking are useless ['color', 'borderWidth', 'borderColor'] )); group.add(sector); prevEndAngle = endAngle; } var getColor = function (percent) { // Less than 0 if (percent <= 0) { return colorList[0][1]; } for (var i = 0; i < colorList.length; i++) { if (colorList[i][0] >= percent && (i === 0 ? 0 : colorList[i - 1][0]) < percent ) { return colorList[i][1]; } } // More than 1 return colorList[i - 1][1]; }; if (!clockwise) { var tmp = startAngle; startAngle = endAngle; endAngle = tmp; } this._renderTicks( seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise ); this._renderPointer( seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise ); this._renderTitle( seriesModel, ecModel, api, getColor, posInfo ); this._renderDetail( seriesModel, ecModel, api, getColor, posInfo ); }, _renderTicks: function ( seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise ) { var group = this.group; var cx = posInfo.cx; var cy = posInfo.cy; var r = posInfo.r; var minVal = seriesModel.get('min'); var maxVal = seriesModel.get('max'); var splitLineModel = seriesModel.getModel('splitLine'); var tickModel = seriesModel.getModel('axisTick'); var labelModel = seriesModel.getModel('axisLabel'); var splitNumber = seriesModel.get('splitNumber'); var subSplitNumber = tickModel.get('splitNumber'); var splitLineLen = parsePercent( splitLineModel.get('length'), r ); var tickLen = parsePercent( tickModel.get('length'), r ); var angle = startAngle; var step = (endAngle - startAngle) / splitNumber; var subStep = step / subSplitNumber; var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle(); var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle(); var textStyleModel = labelModel.getModel('textStyle'); for (var i = 0; i <= splitNumber; i++) { var unitX = Math.cos(angle); var unitY = Math.sin(angle); // Split line if (splitLineModel.get('show')) { var splitLine = new graphic.Line({ shape: { x1: unitX * r + cx, y1: unitY * r + cy, x2: unitX * (r - splitLineLen) + cx, y2: unitY * (r - splitLineLen) + cy }, style: splitLineStyle, silent: true }); if (splitLineStyle.stroke === 'auto') { splitLine.setStyle({ stroke: getColor(i / splitNumber) }); } group.add(splitLine); } // Label if (labelModel.get('show')) { var label = formatLabel( numberUtil.round(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter') ); var distance = labelModel.get('distance'); var text = new graphic.Text({ style: { text: label, x: unitX * (r - splitLineLen - distance) + cx, y: unitY * (r - splitLineLen - distance) + cy, fill: textStyleModel.getTextColor(), textFont: textStyleModel.getFont(), textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'), textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center') }, silent: true }); if (text.style.fill === 'auto') { text.setStyle({ fill: getColor(i / splitNumber) }); } group.add(text); } // Axis tick if (tickModel.get('show') && i !== splitNumber) { for (var j = 0; j <= subSplitNumber; j++) { var unitX = Math.cos(angle); var unitY = Math.sin(angle); var tickLine = new graphic.Line({ shape: { x1: unitX * r + cx, y1: unitY * r + cy, x2: unitX * (r - tickLen) + cx, y2: unitY * (r - tickLen) + cy }, silent: true, style: tickLineStyle }); if (tickLineStyle.stroke === 'auto') { tickLine.setStyle({ stroke: getColor((i + j / subSplitNumber) / splitNumber) }); } group.add(tickLine); angle += subStep; } angle -= subStep; } else { angle += step; } } }, _renderPointer: function ( seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise ) { var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')]; var angleExtent = [startAngle, endAngle]; if (!clockwise) { angleExtent = angleExtent.reverse(); } var data = seriesModel.getData(); var oldData = this._data; var group = this.group; data.diff(oldData) .add(function (idx) { var pointer = new PointerPath({ shape: { angle: startAngle } }); graphic.updateProps(pointer, { shape: { angle: numberUtil.linearMap(data.get('value', idx), valueExtent, angleExtent, true) } }, seriesModel); group.add(pointer); data.setItemGraphicEl(idx, pointer); }) .update(function (newIdx, oldIdx) { var pointer = oldData.getItemGraphicEl(oldIdx); graphic.updateProps(pointer, { shape: { angle: numberUtil.linearMap(data.get('value', newIdx), valueExtent, angleExtent, true) } }, seriesModel); group.add(pointer); data.setItemGraphicEl(newIdx, pointer); }) .remove(function (idx) { var pointer = oldData.getItemGraphicEl(idx); group.remove(pointer); }) .execute(); data.eachItemGraphicEl(function (pointer, idx) { var itemModel = data.getItemModel(idx); var pointerModel = itemModel.getModel('pointer'); pointer.setShape({ x: posInfo.cx, y: posInfo.cy, width: parsePercent( pointerModel.get('width'), posInfo.r ), r: parsePercent(pointerModel.get('length'), posInfo.r) }); pointer.useStyle(itemModel.getModel('itemStyle.normal').getItemStyle()); if (pointer.style.fill === 'auto') { pointer.setStyle('fill', getColor( (data.get('value', idx) - valueExtent[0]) / (valueExtent[1] - valueExtent[0]) )); } graphic.setHoverStyle( pointer, itemModel.getModel('itemStyle.emphasis').getItemStyle() ); }); this._data = data; }, _renderTitle: function ( seriesModel, ecModel, api, getColor, posInfo ) { var titleModel = seriesModel.getModel('title'); if (titleModel.get('show')) { var textStyleModel = titleModel.getModel('textStyle'); var offsetCenter = titleModel.get('offsetCenter'); var x = posInfo.cx + parsePercent(offsetCenter[0], posInfo.r); var y = posInfo.cy + parsePercent(offsetCenter[1], posInfo.r); var text = new graphic.Text({ style: { x: x, y: y, // FIXME First data name ? text: seriesModel.getData().getName(0), fill: textStyleModel.getTextColor(), textFont: textStyleModel.getFont(), textAlign: 'center', textVerticalAlign: 'middle' } }); this.group.add(text); } }, _renderDetail: function ( seriesModel, ecModel, api, getColor, posInfo ) { var detailModel = seriesModel.getModel('detail'); var minVal = seriesModel.get('min'); var maxVal = seriesModel.get('max'); if (detailModel.get('show')) { var textStyleModel = detailModel.getModel('textStyle'); var offsetCenter = detailModel.get('offsetCenter'); var x = posInfo.cx + parsePercent(offsetCenter[0], posInfo.r); var y = posInfo.cy + parsePercent(offsetCenter[1], posInfo.r); var width = parsePercent(detailModel.get('width'), posInfo.r); var height = parsePercent(detailModel.get('height'), posInfo.r); var value = seriesModel.getData().get('value', 0); var rect = new graphic.Rect({ shape: { x: x - width / 2, y: y - height / 2, width: width, height: height }, style: { text: formatLabel( // FIXME First data name ? value, detailModel.get('formatter') ), fill: detailModel.get('backgroundColor'), textFill: textStyleModel.getTextColor(), textFont: textStyleModel.getFont() } }); if (rect.style.textFill === 'auto') { rect.setStyle('textFill', getColor( numberUtil.linearMap(value, [minVal, maxVal], [0, 1], true) )); } rect.setStyle(detailModel.getItemStyle(['color'])); this.group.add(rect); } } }); return GaugeView; });
gpl-2.0
gwenaelCF/eveGCF
test/functional/tck/orderActionsTest.php
393
<?php include(dirname(__FILE__).'/../../bootstrap/functional.php'); $browser = new sfTestFunctional(new sfBrowser()); $browser-> get('/order/index')-> with('request')->begin()-> isParameter('module', 'order')-> isParameter('action', 'index')-> end()-> with('response')->begin()-> isStatusCode(200)-> checkElement('body', '!/This is a temporary page/')-> end() ;
gpl-2.0
yannliang/blog-cielyann
wp-content/plugins/tinymce-advanced/mce/advlink/langs/pt_dlg.js
1957
tinyMCE.addI18n('pt.advlink_dlg',{ title:"Inserir/editar hyperlink", url:"URL do hyperlink", target:"Alvo", titlefield:"T\u00EDtulo", is_email:"A URL digitada parece ser um endere\u00E7o de e-mail. Deseja acrescentar o (necess\u00E1rio) prefixo mailto:?", is_external:"A URL digitada parece conduzir a um link externo. Deseja acrescentar o (necess\u00E1rio) prefixo http://?", list:"Lista de hyperlinks", general_tab:"Geral", popup_tab:"Popup", events_tab:"Eventos", advanced_tab:"Avan\u00E7ado", general_props:"Propriedades gerais", popup_props:"Propriedades de popup", event_props:"Eventos", advanced_props:"Propriedades avan\u00E7adas", popup_opts:"Op\u00E7\u00F5es", anchor_names:"\u00C2ncoras", target_same:"Abrir nessa janela/quadro", target_parent:"Abrir na janela/quadro pai", target_top:"Abrir na p\u00E1gina inteira (substitui todos os quadros)", target_blank:"Abrir em nova janela", popup:"Popup javascript", popup_url:"URL do popup", popup_name:"Nome da janela", popup_return:"Inserir 'return false'", popup_scrollbars:"Mostrar barras de rolagem", popup_statusbar:"Mostrar barra de status", popup_toolbar:"Mostrar barras de ferramentas", popup_menubar:"Mostrar barra de menu", popup_location:"Mostrar barra de endere\u00E7os", popup_resizable:"Permitir altera\u00E7\u00E3o do tamanho da janela", popup_dependent:"Dependente (Mozilla/Firefox apenas)", popup_size:"Tamanho", popup_position:"Posi\u00E7\u00E3o (X/Y)", id:"Id", style:"Estilo", classes:"Classes", target_name:"Nome do alvo", langdir:"Dire\u00E7\u00E3o do texto", target_langcode:"linguagem alvo", langcode:"C\u00F3digo da linguagem", encoding:"Codifica\u00E7\u00E3o de caracteres", mime:"Tipo MIME alvo", rel:"Rela\u00E7\u00E3o p\u00E1gina/alvo", rev:"Rela\u00E7\u00E3o alvo/p\u00E1gina", tabindex:"Tabindex", accesskey:"Chave de acesso", ltr:"Esquerda para direita", rtl:"Direita para esquerda", link_list:"Lista de hyperlinks" });
gpl-2.0
FelixNong1990/flatsome
wp-content/themes/sistina/core/templates/shortcodes/size.php
256
<?php if ( ! is_null( $px ) ) $size = "{$px}px"; elseif ( ! is_null( $perc ) ) $size = "{$perc}%"; elseif ( ! is_null( $em ) ) $size = "{$em}em"; ?> <span style="font-size: <?php echo $size;?>;"><?php echo do_shortcode( $content ); ?></span>
gpl-2.0
R3dRidle/MaineLearning
wp-content/plugins/wangguard/js/wangguard-admin.js
2589
jQuery(document).ready(function () { jQuery('a.wangguard-open-web').mouseover(function () { var thisParentWidth = jQuery(this).parent().width() - 640; thisParentWidth = thisParentWidth + 'px'; if (jQuery(this).find('.mShot').length == 0) { var thisId = jQuery(this).attr('id') + '_preview'; jQuery('.widefat td').css('overflow', 'visible'); jQuery(this).css('position', 'relative'); var thisHref = jQuery.WGtks2AK_URLEncode(jQuery(this).attr('href')); jQuery(this).append('<div class="mShot mshot-container" style="left: '+thisParentWidth+'"><img src="http://s.wordpress.com/mshots/v1/'+thisHref+'?w=450" width="450" class="mshot-image_'+thisId+'" style="margin: 0;" /><div class="mshot-arrow-right"></div></div>'); setTimeout(function () { jQuery('.mshot-image_'+thisId).attr('src', 'http://s.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=2'); }, 6000); setTimeout(function () { jQuery('.mshot-image_'+thisId).attr('src', 'http://s.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=3'); }, 12000); } else { jQuery(this).find('.mShot').css('left', thisParentWidth).show(); } }).mouseout(function () { jQuery(this).find('.mShot').hide(); }); jQuery('div.wangguard-user-ip').mouseover(function () { var thisParentWidth = jQuery(this).parent().width() - 530; thisParentWidth = thisParentWidth + 'px'; if (jQuery(this).find('.wangguard-ipinfo').length == 0) { jQuery('.widefat td').css('overflow', 'visible'); jQuery(this).css('position', 'relative'); var thisIP = jQuery(this).attr('data'); jQuery(this).append('<div class="wangguard-ipinfo wangguard-ipinfo-container" style="left: '+thisParentWidth+'"><div class="wangguard-ipdata-container"><img class="wangguard-ipdata-wait" src="'+wangguard_JSadminurl+'images/wpspin_light.gif" alt="..." /></div><div class="mshot-arrow-right"></div></div>'); data = { action : 'wangguard_ajax_ip_info', ip : thisIP }; jQuery(".wangguard-ipdata-container" , this).load( ajaxurl , data); } else { jQuery(this).find('.wangguard-ipinfo').css('left', thisParentWidth).show(); } }).mouseout(function () { jQuery(this).find('.wangguard-ipinfo').hide(); }); }); jQuery.extend({WGtks2AK_URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/; while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;} });
gpl-2.0
macnlos/runuo_rpi
Scripts/Mobiles/Special/Silvani.cs
3291
using System; using Server; using Server.Items; namespace Server.Mobiles { public class Silvani : BaseCreature { [Constructable] public Silvani() : base( AIType.AI_Mage, FightMode.Evil, 18, 1, 0.1, 0.2 ) { Name = "Silvani"; Body = 176; BaseSoundID = 0x467; SetStr( 253, 400 ); SetDex( 157, 850 ); SetInt( 503, 800 ); SetHits( 600 ); SetDamage( 27, 38 ); SetDamageType( ResistanceType.Physical, 75 ); SetDamageType( ResistanceType.Cold, 25 ); SetResistance( ResistanceType.Physical, 45, 55 ); SetResistance( ResistanceType.Fire, 30, 40 ); SetResistance( ResistanceType.Cold, 30, 40 ); SetResistance( ResistanceType.Poison, 40, 50 ); SetResistance( ResistanceType.Energy, 40, 50 ); SetSkill( SkillName.EvalInt, 100.0 ); SetSkill( SkillName.Magery, 97.6, 107.5 ); SetSkill( SkillName.Meditation, 100.0 ); SetSkill( SkillName.MagicResist, 100.5, 150.0 ); SetSkill( SkillName.Tactics, 97.6, 100.0 ); SetSkill( SkillName.Wrestling, 97.6, 100.0 ); Fame = 20000; Karma = 20000; VirtualArmor = 50; } public override void GenerateLoot() { AddLoot( LootPack.UltraRich, 2 ); } public override OppositionGroup OppositionGroup { get{ return OppositionGroup.FeyAndUndead; } } public override bool CanFly { get { return true; } } public override bool Unprovokable{ get{ return true; } } public override Poison PoisonImmune{ get{ return Poison.Regular; } } public override int TreasureMapLevel{ get{ return 5; } } public void SpawnPixies( Mobile target ) { Map map = this.Map; if ( map == null ) return; int newPixies = Utility.RandomMinMax( 3, 6 ); for ( int i = 0; i < newPixies; ++i ) { Pixie pixie = new Pixie(); pixie.Team = this.Team; pixie.FightMode = FightMode.Closest; bool validLocation = false; Point3D loc = this.Location; for ( int j = 0; !validLocation && j < 10; ++j ) { int x = X + Utility.Random( 3 ) - 1; int y = Y + Utility.Random( 3 ) - 1; int z = map.GetAverageZ( x, y ); if ( validLocation = map.CanFit( x, y, this.Z, 16, false, false ) ) loc = new Point3D( x, y, Z ); else if ( validLocation = map.CanFit( x, y, z, 16, false, false ) ) loc = new Point3D( x, y, z ); } pixie.MoveToWorld( loc, map ); pixie.Combatant = target; } } public override void AlterDamageScalarFrom( Mobile caster, ref double scalar ) { if ( 0.1 >= Utility.RandomDouble() ) SpawnPixies( caster ); } public override void OnGaveMeleeAttack( Mobile defender ) { base.OnGaveMeleeAttack( defender ); defender.Damage( Utility.Random( 20, 10 ), this ); defender.Stam -= Utility.Random( 20, 10 ); defender.Mana -= Utility.Random( 20, 10 ); } public override void OnGotMeleeAttack( Mobile attacker ) { base.OnGotMeleeAttack( attacker ); if ( 0.1 >= Utility.RandomDouble() ) SpawnPixies( attacker ); } public Silvani( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
gpl-2.0
khalibartan/Antidote-DM
Antidotes DM/youtube_dl/extractor/nhl.py
9196
from __future__ import unicode_literals import re import json import os from .common import InfoExtractor from ..compat import ( compat_urlparse, compat_urllib_parse, compat_urllib_parse_urlparse ) from ..utils import ( unified_strdate, ) class NHLBaseInfoExtractor(InfoExtractor): @staticmethod def _fix_json(json_string): return json_string.replace('\\\'', '\'') def _real_extract_video(self, video_id): vid_parts = video_id.split(',') if len(vid_parts) == 3: video_id = '%s0%s%s-X-h' % (vid_parts[0][:4], vid_parts[1], vid_parts[2].rjust(4, '0')) json_url = 'http://video.nhl.com/videocenter/servlets/playlist?ids=%s&format=json' % video_id data = self._download_json( json_url, video_id, transform_source=self._fix_json) return self._extract_video(data[0]) def _extract_video(self, info): video_id = info['id'] self.report_extraction(video_id) initial_video_url = info['publishPoint'] if info['formats'] == '1': parsed_url = compat_urllib_parse_urlparse(initial_video_url) filename, ext = os.path.splitext(parsed_url.path) path = '%s_sd%s' % (filename, ext) data = compat_urllib_parse.urlencode({ 'type': 'fvod', 'path': compat_urlparse.urlunparse(parsed_url[:2] + (path,) + parsed_url[3:]) }) path_url = 'http://video.nhl.com/videocenter/servlets/encryptvideopath?' + data path_doc = self._download_xml( path_url, video_id, 'Downloading final video url') video_url = path_doc.find('path').text else: video_url = initial_video_url join = compat_urlparse.urljoin ret = { 'id': video_id, 'title': info['name'], 'url': video_url, 'description': info['description'], 'duration': int(info['duration']), 'thumbnail': join(join(video_url, '/u/'), info['bigImage']), 'upload_date': unified_strdate(info['releaseDate'].split('.')[0]), } if video_url.startswith('rtmp:'): mobj = re.match(r'(?P<tc_url>rtmp://[^/]+/(?P<app>[a-z0-9/]+))/(?P<play_path>mp4:.*)', video_url) ret.update({ 'tc_url': mobj.group('tc_url'), 'play_path': mobj.group('play_path'), 'app': mobj.group('app'), 'no_resume': True, }) return ret class NHLIE(NHLBaseInfoExtractor): IE_NAME = 'nhl.com' _VALID_URL = r'https?://video(?P<team>\.[^.]*)?\.nhl\.com/videocenter/(?:console|embed)?(?:\?(?:.*?[?&])?)(?:id|hlg|playlist)=(?P<id>[-0-9a-zA-Z,]+)' _TESTS = [{ 'url': 'http://video.canucks.nhl.com/videocenter/console?catid=6?id=453614', 'md5': 'db704a4ea09e8d3988c85e36cc892d09', 'info_dict': { 'id': '453614', 'ext': 'mp4', 'title': 'Quick clip: Weise 4-3 goal vs Flames', 'description': 'Dale Weise scores his first of the season to put the Canucks up 4-3.', 'duration': 18, 'upload_date': '20131006', }, }, { 'url': 'http://video.nhl.com/videocenter/console?id=2014020024-628-h', 'md5': 'd22e82bc592f52d37d24b03531ee9696', 'info_dict': { 'id': '2014020024-628-h', 'ext': 'mp4', 'title': 'Alex Galchenyuk Goal on Ray Emery (14:40/3rd)', 'description': 'Home broadcast - Montreal Canadiens at Philadelphia Flyers - October 11, 2014', 'duration': 0, 'upload_date': '20141011', }, }, { 'url': 'http://video.mapleleafs.nhl.com/videocenter/console?id=58665&catid=802', 'md5': 'c78fc64ea01777e426cfc202b746c825', 'info_dict': { 'id': '58665', 'ext': 'flv', 'title': 'Classic Game In Six - April 22, 1979', 'description': 'It was the last playoff game for the Leafs in the decade, and the last time the Leafs and Habs played in the playoffs. Great game, not a great ending.', 'duration': 400, 'upload_date': '20100129' }, }, { 'url': 'http://video.flames.nhl.com/videocenter/console?id=630616', 'only_matching': True, }, { 'url': 'http://video.nhl.com/videocenter/?id=736722', 'only_matching': True, }, { 'url': 'http://video.nhl.com/videocenter/console?hlg=20142015,2,299&lang=en', 'md5': '076fcb88c255154aacbf0a7accc3f340', 'info_dict': { 'id': '2014020299-X-h', 'ext': 'mp4', 'title': 'Penguins at Islanders / Game Highlights', 'description': 'Home broadcast - Pittsburgh Penguins at New York Islanders - November 22, 2014', 'duration': 268, 'upload_date': '20141122', } }, { 'url': 'http://video.oilers.nhl.com/videocenter/console?id=691469&catid=4', 'info_dict': { 'id': '691469', 'ext': 'mp4', 'title': 'RAW | Craig MacTavish Full Press Conference', 'description': 'Oilers GM Craig MacTavish addresses the media at Rexall Place on Friday.', 'upload_date': '20141205', }, 'params': { 'skip_download': True, # Requires rtmpdump } }, { 'url': 'http://video.nhl.com/videocenter/embed?playlist=836127', 'only_matching': True, }] def _real_extract(self, url): video_id = self._match_id(url) return self._real_extract_video(video_id) class NHLNewsIE(NHLBaseInfoExtractor): IE_NAME = 'nhl.com:news' IE_DESC = 'NHL news' _VALID_URL = r'https?://(?:.+?\.)?nhl\.com/(?:ice|club)/news\.html?(?:\?(?:.*?[?&])?)id=(?P<id>[-0-9a-zA-Z]+)' _TESTS = [{ 'url': 'http://www.nhl.com/ice/news.htm?id=750727', 'md5': '4b3d1262e177687a3009937bd9ec0be8', 'info_dict': { 'id': '736722', 'ext': 'mp4', 'title': 'Cal Clutterbuck has been fined $2,000', 'description': 'md5:45fe547d30edab88b23e0dd0ab1ed9e6', 'duration': 37, 'upload_date': '20150128', }, }, { # iframe embed 'url': 'http://sabres.nhl.com/club/news.htm?id=780189', 'md5': '9f663d1c006c90ac9fb82777d4294e12', 'info_dict': { 'id': '836127', 'ext': 'mp4', 'title': 'Morning Skate: OTT vs. BUF (9/23/15)', 'description': "Brian Duff chats with Tyler Ennis prior to Buffalo's first preseason home game.", 'duration': 93, 'upload_date': '20150923', }, }] def _real_extract(self, url): news_id = self._match_id(url) webpage = self._download_webpage(url, news_id) video_id = self._search_regex( [r'pVid(\d+)', r"nlid\s*:\s*'(\d+)'", r'<iframe[^>]+src=["\']https?://video.*?\.nhl\.com/videocenter/embed\?.*\bplaylist=(\d+)'], webpage, 'video id') return self._real_extract_video(video_id) class NHLVideocenterIE(NHLBaseInfoExtractor): IE_NAME = 'nhl.com:videocenter' IE_DESC = 'NHL videocenter category' _VALID_URL = r'https?://video\.(?P<team>[^.]*)\.nhl\.com/videocenter/(console\?[^(id=)]*catid=(?P<catid>[0-9]+)(?![&?]id=).*?)?$' _TEST = { 'url': 'http://video.canucks.nhl.com/videocenter/console?catid=999', 'info_dict': { 'id': '999', 'title': 'Highlights', }, 'playlist_count': 12, } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) team = mobj.group('team') webpage = self._download_webpage(url, team) cat_id = self._search_regex( [r'var defaultCatId = "(.+?)";', r'{statusIndex:0,index:0,.*?id:(.*?),'], webpage, 'category id') playlist_title = self._html_search_regex( r'tab0"[^>]*?>(.*?)</td>', webpage, 'playlist title', flags=re.DOTALL).lower().capitalize() data = compat_urllib_parse.urlencode({ 'cid': cat_id, # This is the default value 'count': 12, 'ptrs': 3, 'format': 'json', }) path = '/videocenter/servlets/browse?' + data request_url = compat_urlparse.urljoin(url, path) response = self._download_webpage(request_url, playlist_title) response = self._fix_json(response) if not response.strip(): self._downloader.report_warning('Got an empty response, trying ' 'adding the "newvideos" parameter') response = self._download_webpage(request_url + '&newvideos=true', playlist_title) response = self._fix_json(response) videos = json.loads(response) return { '_type': 'playlist', 'title': playlist_title, 'id': cat_id, 'entries': [self._extract_video(v) for v in videos], }
gpl-2.0
etown/sysdig
userspace/libsinsp/table.cpp
28108
/* Copyright (C) 2013-2014 Draios inc. This file is part of sysdig. sysdig is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. sysdig 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 sysdig. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #ifndef _WIN32 #include <curses.h> #endif #include "sinsp.h" #include "sinsp_int.h" #include "../../driver/ppm_ringbuffer.h" #include "filter.h" #include "filterchecks.h" #include "table.h" extern sinsp_filter_check_list g_filterlist; extern sinsp_evttables g_infotables; // // // Table sorter functor typedef struct table_row_cmp { bool operator()(const sinsp_sample_row& src, const sinsp_sample_row& dst) { ppm_cmp_operator op; if(m_ascending) { op = CO_LT; } else { op = CO_GT; } if(src.m_values[m_colid].m_cnt > 1 || dst.m_values[m_colid].m_cnt > 1) { return flt_compare_avg(op, m_type, src.m_values[m_colid].m_val, dst.m_values[m_colid].m_val, src.m_values[m_colid].m_len, dst.m_values[m_colid].m_len, src.m_values[m_colid].m_cnt, dst.m_values[m_colid].m_cnt); } else { return flt_compare(op, m_type, src.m_values[m_colid].m_val, dst.m_values[m_colid].m_val, src.m_values[m_colid].m_len, dst.m_values[m_colid].m_len); } } uint32_t m_colid; ppm_param_type m_type; bool m_ascending; }table_row_cmp; sinsp_table::sinsp_table(sinsp* inspector, tabletype type, uint64_t refresh_interval_ns, bool print_to_stdout) { m_inspector = inspector; m_type = type; m_is_key_present = false; m_is_groupby_key_present = false; m_fld_pointers = NULL; m_premerge_fld_pointers = NULL; m_postmerge_fld_pointers = NULL; m_n_fields = 0; m_n_premerge_fields = 0; m_n_postmerge_fields = 0; m_refresh_interval_ns = refresh_interval_ns; m_print_to_stdout = print_to_stdout; m_next_flush_time_ns = 0; m_printer = new sinsp_filter_check_reference(); m_buffer = &m_buffer1; m_is_sorting_ascending = false; m_sorting_col = -1; m_just_sorted = true; m_do_merging = true; m_types = &m_premerge_types; m_table = &m_premerge_table; m_extractors = &m_premerge_extractors; m_filter = NULL; m_use_defaults = false; m_zero_u64 = 0; m_zero_double = 0; m_paused = false; m_sample_data = NULL; } sinsp_table::~sinsp_table() { uint32_t j; for(j = 0; j < m_chks_to_free.size(); j++) { delete m_chks_to_free[j]; } if(m_premerge_fld_pointers != NULL) { delete[] m_premerge_fld_pointers; } if(m_postmerge_fld_pointers != NULL) { delete[] m_postmerge_fld_pointers; } if(m_filter != NULL) { delete m_filter; } delete m_printer; } void sinsp_table::configure(vector<sinsp_view_column_info>* entries, const string& filter, bool use_defaults) { m_use_defaults = use_defaults; // // If this is a list table, increase the refresh time to improve realtimyiness // if(m_type == sinsp_table::TT_LIST) { set_refresh_interval(200000000); } ////////////////////////////////////////////////////////////////////////////////////// // If a filter has been spefied, compile it ////////////////////////////////////////////////////////////////////////////////////// if(filter != "") { m_filter = new sinsp_filter(m_inspector, filter); } ////////////////////////////////////////////////////////////////////////////////////// // Extract the tokens ////////////////////////////////////////////////////////////////////////////////////// m_premerge_extractors.clear(); for(auto vit : *entries) { sinsp_filter_check* chk = g_filterlist.new_filter_check_from_fldname(vit.m_field, m_inspector, false); if(chk == NULL) { throw sinsp_exception("invalid field name " + vit.m_field); } chk->m_aggregation = (sinsp_field_aggregation)vit.m_aggregation; m_chks_to_free.push_back(chk); chk->parse_field_name(vit.m_field.c_str(), true); if((vit.m_flags & TEF_IS_KEY) != 0) { if(m_is_key_present) { throw sinsp_exception("invalid table configuration: multiple keys specified"); } m_premerge_extractors.insert(m_premerge_extractors.begin(), chk); m_is_key_present = true; } else { m_premerge_extractors.push_back(chk); } } if(m_type == sinsp_table::TT_TABLE) { // // Make sure this is a valid table // if(!m_is_key_present) { throw sinsp_exception("table is missing the key"); } } else { sinsp_filter_check* chk = g_filterlist.new_filter_check_from_fldname("util.cnt", m_inspector, false); if(chk == NULL) { throw sinsp_exception("internal table error"); } chk->m_aggregation = A_NONE; m_chks_to_free.push_back(chk); chk->parse_field_name("util.cnt", true); if(m_is_key_present) { throw sinsp_exception("list table can't have a key"); } m_premerge_extractors.insert(m_premerge_extractors.begin(), chk); m_is_key_present = true; } m_premerge_fld_pointers = new sinsp_table_field[m_premerge_extractors.size()]; m_fld_pointers = m_premerge_fld_pointers; m_n_premerge_fields = (uint32_t)m_premerge_extractors.size(); m_n_fields = m_n_premerge_fields; if(m_n_fields < 2) { throw sinsp_exception("table has no values"); } for(auto it = m_premerge_extractors.begin(); it != m_premerge_extractors.end(); ++it) { m_premerge_types.push_back((*it)->get_field_info()->m_type); m_premerge_legend.push_back(*(*it)->get_field_info()); } m_premerge_vals_array_sz = (m_n_fields - 1) * sizeof(sinsp_table_field); m_vals_array_sz = m_premerge_vals_array_sz; ////////////////////////////////////////////////////////////////////////////////////// // If a merge has been specified, configure it ////////////////////////////////////////////////////////////////////////////////////// uint32_t n_gby_keys = 0; for(auto vit : *entries) { if((vit.m_flags & TEF_IS_GROUPBY_KEY) != 0) { n_gby_keys++; } } if(n_gby_keys == 0) { // // No merge string. We can stop here // m_do_merging = false; return; } else if(n_gby_keys > 1) { throw sinsp_exception("invalid table definition: multiple groupby keys"); } // // Merging not supported for lists // if(m_type != sinsp_table::TT_TABLE) { throw sinsp_exception("group by not supported for list tables"); } m_do_merging = true; for(uint32_t j = 0; j < entries->size(); j++) { auto vit = entries->at(j); // // Skip original key when grouping // if((vit.m_flags & TEF_IS_KEY) != 0) { continue; } sinsp_filter_check* chk = m_premerge_extractors[j]; chk->m_merge_aggregation = (sinsp_field_aggregation)vit.m_groupby_aggregation; if((vit.m_flags & TEF_IS_GROUPBY_KEY) != 0) { if(m_is_groupby_key_present) { throw sinsp_exception("invalid table configuration: more than one groupby key specified"); } m_is_groupby_key_present = true; m_postmerge_extractors.insert(m_postmerge_extractors.begin(), chk); m_groupby_columns.insert(m_groupby_columns.begin(), j); } else { m_postmerge_extractors.push_back(chk); m_groupby_columns.push_back(j); } } m_postmerge_fld_pointers = new sinsp_table_field[m_postmerge_extractors.size()]; m_n_postmerge_fields = (uint32_t)m_postmerge_extractors.size(); if(!m_is_groupby_key_present) { throw sinsp_exception("table is missing the groupby key"); } if(m_groupby_columns.size() < 2) { throw sinsp_exception("groupby table has no values"); } for(auto it = m_postmerge_extractors.begin(); it != m_postmerge_extractors.end(); ++it) { m_postmerge_types.push_back((*it)->get_field_info()->m_type); m_postmerge_legend.push_back(*(*it)->get_field_info()); } m_postmerge_vals_array_sz = (m_n_postmerge_fields - 1) * sizeof(sinsp_table_field); } void sinsp_table::add_row(bool merging) { uint32_t j; sinsp_table_field key(m_fld_pointers[0].m_val, m_fld_pointers[0].m_len, m_fld_pointers[0].m_cnt); if(m_type == sinsp_table::TT_TABLE) { // // This is a table. Do a proper key lookup and update the entry // auto it = m_table->find(key); if(it == m_table->end()) { // // New entry // key.m_val = key.m_val; key.m_cnt = 1; m_vals = (sinsp_table_field*)m_buffer->reserve(m_vals_array_sz); for(j = 1; j < m_n_fields; j++) { uint32_t vlen = get_field_len(j); m_vals[j - 1].m_val = m_fld_pointers[j].m_val; m_vals[j - 1].m_len = vlen; m_vals[j - 1].m_cnt = m_fld_pointers[j].m_cnt; } (*m_table)[key] = m_vals; } else { // // Existing entry // m_vals = it->second; for(j = 1; j < m_n_fields; j++) { if(merging) { add_fields(j, &m_fld_pointers[j], m_postmerge_extractors[j]->m_merge_aggregation); } else { add_fields(j, &m_fld_pointers[j], m_premerge_extractors[j]->m_aggregation); } } } } else { // // We are in list mode. Just appen the row to the end of the sample // if(m_paused) { return; } sinsp_sample_row row; // // This is a list. Create the new entry and push it back. // key.m_val = key.m_val; key.m_cnt = 1; row.m_key = key; m_vals = (sinsp_table_field*)m_buffer->reserve(m_vals_array_sz); for(j = 1; j < m_n_fields; j++) { uint32_t vlen = get_field_len(j); m_vals[j - 1].m_val = m_fld_pointers[j].m_val; m_vals[j - 1].m_len = vlen; m_vals[j - 1].m_cnt = 1; row.m_values.push_back(m_vals[j - 1]); } m_full_sample_data.push_back(row); } } void sinsp_table::process_event(sinsp_evt* evt) { uint32_t j; // // Apply the filter // if(m_filter) { if(!m_filter->run(evt)) { return; } } // // Extract the values and create the row to add // for(j = 0; j < m_n_premerge_fields; j++) { uint32_t len; uint8_t* val = m_premerge_extractors[j]->extract(evt, &len); sinsp_table_field* pfld = &(m_premerge_fld_pointers[j]); // // XXX For the moment, we only support defaults for numeric fields. // At a certain point we will want to introduce the concept of zero // for other fields too. // if(val == NULL) { if(m_use_defaults) { pfld->m_val = get_default_val(&m_premerge_legend[j]); if(pfld->m_val == NULL) { return; } pfld->m_len = get_field_len(j); pfld->m_val = m_buffer->copy(pfld->m_val, pfld->m_len); pfld->m_cnt = 0; } else { return; } } else { pfld->m_val = val; pfld->m_len = get_field_len(j); pfld->m_val = m_buffer->copy(val, pfld->m_len); pfld->m_cnt = 1; } } // // Add the row // add_row(false); return; } void sinsp_table::process_proctable(sinsp_evt* evt) { sinsp_evt tevt; scap_evt tscapevt; threadinfo_map_t* threadtable = m_inspector->m_thread_manager->get_threads(); ASSERT(threadtable != NULL); uint64_t ts = evt->get_ts(); uint64_t ts_s = ts - (ts % ONE_SECOND_IN_NS); tscapevt.ts = ts_s - 1; // // Note: as the event type for this fake event, we pick one of the unused // numbers, so we guarantee that filter checks will not wrongly pick it up // tscapevt.type = PPME_SYSDIGEVENT_X; tscapevt.len = 0; tevt.m_inspector = m_inspector; tevt.m_info = &(g_infotables.m_event_info[PPME_SYSDIGEVENT_X]); tevt.m_pevt = NULL; tevt.m_cpuid = 0; tevt.m_evtnum = 0; tevt.m_pevt = &tscapevt; tevt.m_fdinfo = NULL; for(auto it = threadtable->begin(); it != threadtable->end(); ++it) { tevt.m_tinfo = &it->second; tscapevt.tid = tevt.m_tinfo->m_tid; if(m_filter) { if(!m_filter->run(evt)) { continue; } } process_event(&tevt); } } void sinsp_table::flush(sinsp_evt* evt) { if(!m_paused) { if(m_next_flush_time_ns != 0) { // // Time to emit the sample! // Add the proctable as a sample at the end of the second // process_proctable(evt); // // If there is a merging step, switch the types to point to the merging ones. // if(m_do_merging) { m_types = &m_postmerge_types; m_table = &m_merge_table; m_n_fields = m_n_postmerge_fields; m_vals_array_sz = m_postmerge_vals_array_sz; m_fld_pointers = m_postmerge_fld_pointers; m_extractors = &m_postmerge_extractors; } // // Emit the sample // create_sample(); if(m_type == sinsp_table::TT_TABLE) { // // Switch the data storage so that the current one is still usable by the // consumers of the table. // switch_buffers(); // // Clear the current data storage // m_buffer->clear(); } // // Reinitialize the tables // m_premerge_table.clear(); m_merge_table.clear(); } } uint64_t ts = evt->get_ts(); m_next_flush_time_ns = ts - (ts % m_refresh_interval_ns) + m_refresh_interval_ns; return; } void sinsp_table::stdout_print(vector<sinsp_sample_row>* sample_data, uint64_t time_delta) { vector<filtercheck_field_info>* legend = get_legend(); for(auto it = sample_data->begin(); it != sample_data->end(); ++it) { for(uint32_t j = 0; j < m_n_fields - 1; j++) { sinsp_filter_check* extractor = m_extractors->at(j + 1); uint64_t td = 0; if(extractor->m_aggregation == A_TIME_AVG || extractor->m_merge_aggregation == A_TIME_AVG) { td = time_delta; } m_printer->set_val(m_types->at(j + 1), it->m_values[j].m_val, it->m_values[j].m_len, it->m_values[j].m_cnt, legend->at(j + 1).m_print_format); char* prstr = m_printer->tostring_nice(NULL, 10, td); printf("%s ", prstr); //printf("%s ", m_printer->tostring(NULL)); } printf("\n"); } printf("----------------------\n"); } void sinsp_table::filter_sample() { vector<filtercheck_field_info>* legend = get_legend(); m_filtered_sample_data.clear(); for(auto it : m_full_sample_data) { for(uint32_t j = 0; j < it.m_values.size(); j++) { ppm_param_type type; if(m_do_merging) { type = m_postmerge_types[j + 1]; } else { type = m_premerge_types[j + 1]; } if(type == PT_CHARBUF || type == PT_BYTEBUF || type == PT_SYSCALLID || type == PT_PORT || type == PT_L4PROTO || type == PT_SOCKFAMILY || type == PT_IPV4ADDR || type == PT_UID || type == PT_GID) { m_printer->set_val(type, it.m_values[j].m_val, it.m_values[j].m_len, it.m_values[j].m_cnt, legend->at(j + 1).m_print_format); string strval = m_printer->tostring_nice(NULL, 0, 0); if(strval.find(m_freetext_filter) != string::npos) { m_filtered_sample_data.push_back(it); break; } } } } } // // Returns the key of the first match, or NULL if no match // sinsp_table_field* sinsp_table::search_in_sample(string text) { vector<filtercheck_field_info>* legend = get_legend(); for(auto it = m_full_sample_data.begin(); it != m_full_sample_data.end(); ++it) { for(uint32_t j = 0; j < it->m_values.size(); j++) { ppm_param_type type; if(m_do_merging) { ASSERT(m_types->size() == it->m_values.size() + 2); type = m_types->at(j + 2); } else { ASSERT(m_types->size() == it->m_values.size() + 1); type = m_types->at(j + 1); } if(type == PT_CHARBUF || type == PT_BYTEBUF || type == PT_SYSCALLID || type == PT_PORT || type == PT_L4PROTO || type == PT_SOCKFAMILY || type == PT_IPV4ADDR || type == PT_UID || type == PT_GID) { m_printer->set_val(type, it->m_values[j].m_val, it->m_values[j].m_len, it->m_values[j].m_cnt, legend->at(j + 1).m_print_format); string strval = m_printer->tostring_nice(NULL, 0, 0); if(strval.find(text) != string::npos) { return &(it->m_key); } } } } return NULL; } void sinsp_table::sort_sample() { if(m_type == sinsp_table::TT_LIST) { if(m_sorting_col == -1 || !m_just_sorted) { return; } m_just_sorted = false; } if(m_sample_data->size() != 0) { if(m_sorting_col >= (int32_t)m_sample_data->at(0).m_values.size()) { throw sinsp_exception("invalid table sorting column"); } table_row_cmp cc; cc.m_colid = m_sorting_col; cc.m_ascending = m_is_sorting_ascending; uint32_t tyid = m_do_merging? m_sorting_col + 2 : m_sorting_col + 1; cc.m_type = m_premerge_types[tyid]; sort(m_sample_data->begin(), m_sample_data->end(), cc); } } vector<sinsp_sample_row>* sinsp_table::get_sample(uint64_t time_delta) { // // No sample generation happens when the table is paused // if(!m_paused) { // // If we have a freetext filter, we start by filtering the sample // if(m_freetext_filter != "") { filter_sample(); m_sample_data = &m_filtered_sample_data; } else { m_sample_data = &m_full_sample_data; } // // Sort the sample // sort_sample(); } // // If required, emit the sample to stdout // #ifndef _WIN32 if(m_print_to_stdout) { #endif stdout_print(m_sample_data, time_delta); #ifndef _WIN32 } #endif // // Restore the lists used for event processing // m_types = &m_premerge_types; m_table = &m_premerge_table; m_n_fields = m_n_premerge_fields; m_vals_array_sz = m_premerge_vals_array_sz; m_fld_pointers = m_premerge_fld_pointers; m_extractors = &m_premerge_extractors; return m_sample_data; } void sinsp_table::set_sorting_col(uint32_t col) { uint32_t n_fields; vector<ppm_param_type>* types; if(m_do_merging) { n_fields = m_n_postmerge_fields; types = &m_postmerge_types; } else { n_fields = m_n_premerge_fields; types = &m_premerge_types; } if(col == 0) { if(m_type == sinsp_table::TT_TABLE) { throw sinsp_exception("cannot sort by key"); } else { m_sorting_col = -1; return; } } if(col >= n_fields) { throw sinsp_exception("invalid table sorting column"); } if(col == (uint32_t)(m_sorting_col + 1)) { m_is_sorting_ascending = !m_is_sorting_ascending; } else { switch(types->at(col)) { case PT_INT8: case PT_INT16: case PT_INT32: case PT_INT64: case PT_UINT8: case PT_UINT16: case PT_UINT32: case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: case PT_DOUBLE: case PT_BOOL: m_is_sorting_ascending = false; break; default: m_is_sorting_ascending = true; break; } } m_just_sorted = true; m_sorting_col = col - 1; } uint32_t sinsp_table::get_sorting_col() { return (uint32_t)m_sorting_col + 1; } void sinsp_table::create_sample() { if(m_type == sinsp_table::TT_TABLE) { uint32_t j; m_full_sample_data.clear(); sinsp_sample_row row; // // If merging is on, perform the merge and switch to the merged table // if(m_do_merging) { m_table = &m_merge_table; m_merge_table.clear(); for(auto it = m_premerge_table.begin(); it != m_premerge_table.end(); ++it) { for(j = 0; j < m_n_postmerge_fields; j++) { sinsp_table_field* pfld = &(m_postmerge_fld_pointers[j]); uint32_t col = m_groupby_columns[j]; if(col == 0) { pfld->m_val = it->first.m_val; pfld->m_len = it->first.m_len; pfld->m_cnt = it->first.m_cnt; } else { pfld->m_val = it->second[col - 1].m_val; pfld->m_len = it->second[col - 1].m_len; pfld->m_cnt = it->second[col - 1].m_cnt; } } add_row(true); } } else { m_table = &m_premerge_table; } // // Emit the table // for(auto it = m_table->begin(); it != m_table->end(); ++it) { row.m_key = it->first; row.m_values.clear(); sinsp_table_field* fields = it->second; for(j = 0; j < m_n_fields - 1; j++) { row.m_values.push_back(fields[j]); } m_full_sample_data.push_back(row); } } else { // // If this is a list, there's nothing to be done, since m_full_sample_data // is already prepared and doesn't need to be cleaned. // return; } } void sinsp_table::add_fields_sum(ppm_param_type type, sinsp_table_field *dst, sinsp_table_field *src) { uint8_t* operand1 = dst->m_val; uint8_t* operand2 = src->m_val; switch(type) { case PT_INT8: *(int8_t*)operand1 += *(int8_t*)operand2; return; case PT_INT16: *(int16_t*)operand1 += *(int16_t*)operand2; return; case PT_INT32: *(int32_t*)operand1 += *(int32_t*)operand2; return; case PT_INT64: *(int64_t*)operand1 += *(int64_t*)operand2; return; case PT_UINT8: *(uint8_t*)operand1 += *(uint8_t*)operand2; return; case PT_UINT16: *(uint16_t*)operand1 += *(uint16_t*)operand2; return; case PT_UINT32: case PT_BOOL: *(uint32_t*)operand1 += *(uint32_t*)operand2; return; case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: *(uint64_t*)operand1 += *(uint64_t*)operand2; return; case PT_DOUBLE: *(double*)operand1 += *(double*)operand2; return; default: return; } } void sinsp_table::add_fields_sum_of_avg(ppm_param_type type, sinsp_table_field *dst, sinsp_table_field *src) { uint8_t* operand1 = dst->m_val; uint8_t* operand2 = src->m_val; uint32_t cnt1 = dst->m_cnt; uint32_t cnt2 = src->m_cnt; switch(type) { case PT_INT8: if(cnt1 > 1) { *(int8_t*)operand1 = *(int8_t*)operand1 / cnt1; } *(int8_t*)operand1 += (*(int8_t*)operand2) / cnt2; break; case PT_INT16: if(cnt1 > 1) { *(int16_t*)operand1 = *(int16_t*)operand1 / cnt1; } *(int16_t*)operand1 += (*(int16_t*)operand2) / cnt2; break; case PT_INT32: if(cnt1 > 1) { *(int32_t*)operand1 = *(int32_t*)operand1 / cnt1; } *(int32_t*)operand1 += (*(int32_t*)operand2) / cnt2; break; case PT_INT64: if(cnt1 > 1) { *(int64_t*)operand1 = *(int64_t*)operand1 / cnt1; } *(int64_t*)operand1 += (*(int64_t*)operand2) / cnt2; break; case PT_UINT8: if(cnt1 > 1) { *(uint8_t*)operand1 = *(uint8_t*)operand1 / cnt1; } *(uint8_t*)operand1 += (*(uint8_t*)operand2) / cnt2; break; case PT_UINT16: if(cnt1 > 1) { *(uint16_t*)operand1 = *(uint16_t*)operand1 / cnt1; } *(uint16_t*)operand1 += (*(uint16_t*)operand2) / cnt2; break; case PT_UINT32: case PT_BOOL: if(cnt1 > 1) { *(uint32_t*)operand1 = *(uint32_t*)operand1 / cnt1; } *(uint32_t*)operand1 += (*(uint32_t*)operand2) / cnt2; break; case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: if(cnt1 > 1) { *(uint64_t*)operand1 = *(uint64_t*)operand1 / cnt1; } *(uint64_t*)operand1 += (*(uint64_t*)operand2) / cnt2; break; case PT_DOUBLE: if(cnt1 > 1) { *(double*)operand1 = *(double*)operand1 / cnt1; } *(double*)operand1 += (*(double*)operand2) / cnt2; break; default: break; } src->m_cnt = 1; dst->m_cnt = 1; } void sinsp_table::add_fields_max(ppm_param_type type, sinsp_table_field *dst, sinsp_table_field *src) { uint8_t* operand1 = dst->m_val; uint8_t* operand2 = src->m_val; switch(type) { case PT_INT8: if(*(int8_t*)operand1 < *(int8_t*)operand2) { *(int8_t*)operand1 = *(int8_t*)operand2; } return; case PT_INT16: if(*(int16_t*)operand1 < *(int16_t*)operand2) { *(int16_t*)operand1 = *(int16_t*)operand2; } return; case PT_INT32: if(*(int32_t*)operand1 < *(int32_t*)operand2) { *(int32_t*)operand1 = *(int32_t*)operand2; } return; case PT_INT64: if(*(int64_t*)operand1 < *(int64_t*)operand2) { *(int64_t*)operand1 = *(int64_t*)operand2; } return; case PT_UINT8: if(*(uint8_t*)operand1 < *(uint8_t*)operand2) { *(uint8_t*)operand1 = *(uint8_t*)operand2; } return; case PT_UINT16: if(*(uint16_t*)operand1 < *(uint16_t*)operand2) { *(uint16_t*)operand1 = *(uint16_t*)operand2; } return; case PT_UINT32: case PT_BOOL: if(*(uint32_t*)operand1 < *(uint32_t*)operand2) { *(uint32_t*)operand1 = *(uint32_t*)operand2; } return; case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: if(*(uint64_t*)operand1 < *(uint64_t*)operand2) { *(uint64_t*)operand1 = *(uint64_t*)operand2; } return; case PT_DOUBLE: if(*(double*)operand1 < *(double*)operand2) { *(double*)operand1 = *(double*)operand2; } return; case PT_CHARBUF: case PT_BYTEBUF: if(dst->m_len >= src->m_len) { memcpy(dst->m_val, src->m_val, src->m_len); } else { dst->m_val = m_buffer->copy(src->m_val, src->m_len); } dst->m_len = src->m_len; default: return; } } void sinsp_table::add_fields(uint32_t dst_id, sinsp_table_field* src, uint32_t aggr) { ppm_param_type type = (*m_types)[dst_id]; sinsp_table_field* dst = &(m_vals[dst_id - 1]); switch(aggr) { case A_NONE: return; case A_SUM: case A_TIME_AVG: if(src->m_cnt < 2) { add_fields_sum(type, dst, src); } else { add_fields_sum_of_avg(type, dst, src); } return; case A_AVG: dst->m_cnt += src->m_cnt; add_fields_sum(type, dst, src); return; case A_MAX: add_fields_max(type, dst, src); return; default: ASSERT(false); return; } } uint32_t sinsp_table::get_field_len(uint32_t id) { ppm_param_type type; sinsp_table_field *fld; type = (*m_types)[id]; fld = &(m_fld_pointers[id]); switch(type) { case PT_INT8: return 1; case PT_INT16: return 2; case PT_INT32: return 4; case PT_INT64: case PT_FD: case PT_PID: case PT_ERRNO: return 8; case PT_FLAGS8: case PT_UINT8: case PT_SIGTYPE: return 1; case PT_FLAGS16: case PT_UINT16: case PT_PORT: case PT_SYSCALLID: return 2; case PT_UINT32: case PT_FLAGS32: case PT_BOOL: case PT_IPV4ADDR: case PT_SIGSET: return 4; case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: return 8; case PT_CHARBUF: return (uint32_t)(strlen((char*)fld->m_val) + 1); case PT_BYTEBUF: return fld->m_len; case PT_DOUBLE: return sizeof(double); case PT_SOCKADDR: case PT_SOCKTUPLE: case PT_FDLIST: case PT_FSPATH: default: ASSERT(false); return false; } } uint8_t* sinsp_table::get_default_val(filtercheck_field_info* fld) { switch(fld->m_type) { case PT_INT8: case PT_INT16: case PT_INT32: case PT_INT64: case PT_UINT8: case PT_UINT16: case PT_UINT32: case PT_UINT64: case PT_BOOL: case PT_RELTIME: case PT_ABSTIME: if(fld->m_print_format == PF_DEC) { return (uint8_t*)&m_zero_u64; } else { return NULL; } case PT_DOUBLE: return (uint8_t*)&m_zero_double; case PT_CHARBUF: return (uint8_t*)&m_zero_u64; case PT_PORT: case PT_IPV4ADDR: return NULL; default: ASSERT(false); return NULL; } } void sinsp_table::switch_buffers() { if(m_buffer == &m_buffer1) { m_buffer = &m_buffer2; } else { m_buffer = &m_buffer1; } } pair<filtercheck_field_info*, string> sinsp_table::get_row_key_name_and_val(uint32_t rownum) { pair<filtercheck_field_info*, string> res; vector<sinsp_filter_check*>* extractors; vector<ppm_param_type>* types; if(m_do_merging) { extractors = &m_postmerge_extractors; types = &m_postmerge_types; } else { extractors = &m_premerge_extractors; types = &m_premerge_types; } if(rownum >= m_sample_data->size()) { ASSERT(m_sample_data->size() == 0); res.first = NULL; res.second = ""; } else { vector<filtercheck_field_info>* legend = get_legend(); res.first = (filtercheck_field_info*)((*extractors)[0])->get_field_info(); ASSERT(res.first != NULL); m_printer->set_val(types->at(0), m_sample_data->at(rownum).m_key.m_val, m_sample_data->at(rownum).m_key.m_len, m_sample_data->at(rownum).m_key.m_cnt, legend->at(0).m_print_format); res.second = m_printer->tostring(NULL); } return res; } sinsp_table_field* sinsp_table::get_row_key(uint32_t rownum) { if(rownum >= m_sample_data->size()) { return NULL; } return &m_sample_data->at(rownum).m_key; } int32_t sinsp_table::get_row_from_key(sinsp_table_field* key) { uint32_t j; for(j = 0; j < m_sample_data->size(); j++) { sinsp_table_field* rowkey = &(m_sample_data->at(j).m_key); if(rowkey->m_len == key->m_len) { if(memcmp(rowkey->m_val, key->m_val, key->m_len) == 0) { return j; } } } return -1; } void sinsp_table::set_paused(bool paused) { m_paused = paused; } void sinsp_table::clear() { if(m_type == sinsp_table::TT_LIST) { m_full_sample_data.clear(); m_buffer->clear(); } else { ASSERT(false); } }
gpl-2.0
akkolad/augenblick
wp-content/plugins/polylang/install/upgrade.php
17833
<?php /** * manages Polylang upgrades * * @since 1.2 */ class PLL_Upgrade { public $options; /** * constructor * * @since 1.2 */ public function __construct( &$options ) { $this->options = &$options; } /** * check if upgrade is possible otherwise die to avoid activation * * @since 1.2 */ public function can_activate() { if ( ! $this->can_upgrade() ) { ob_start(); $this->admin_notices(); // FIXME the error message is displayed two times die( ob_get_contents() ); } } /** * upgrades if possible otherwise returns false to stop Polylang loading * * @since 1.2 * * @return bool true if upgrade is possible, false otherwise */ public function upgrade() { if ( ! $this->can_upgrade() ) { add_action( 'all_admin_notices', array( $this, 'admin_notices' ) ); return false; } add_action( 'admin_init', array( $this, '_upgrade' ) ); return true; } /** * check if we the previous version is not too old * upgrades if OK * /!\ never start any upgrade before admin_init as it is likely to conflict with some other plugins * * @since 1.2 * * @return bool true if upgrade is possible, false otherwise */ public function can_upgrade() { // don't manage upgrade from version < 0.8 return version_compare( $this->options['version'], '0.8', '>=' ); } /** * displays a notice when ugrading from a too old version * * @since 1.0 */ public function admin_notices() { load_plugin_textdomain( 'polylang', false, basename( POLYLANG_DIR ) . '/languages' ); printf( '<div class="error"><p>%s</p><p>%s</p></div>', esc_html__( 'Polylang has been deactivated because you upgraded from a too old version.', 'polylang' ), sprintf( /* translators: %s are Polylang version numbers */ esc_html__( 'Please upgrade first to %s before ugrading to %s.', 'polylang' ), '<strong>0.9.8</strong>', POLYLANG_VERSION ) ); } /** * upgrades the plugin depending on the previous version * * @since 1.2 */ public function _upgrade() { foreach ( array( '0.9', '1.0', '1.1', '1.2', '1.2.1', '1.2.3', '1.3', '1.4', '1.4.1', '1.4.4', '1.5', '1.6', '1.7.4', '1.8' ) as $version ) { if ( version_compare( $this->options['version'], $version, '<' ) ) { call_user_func( array( $this, 'upgrade_' . str_replace( '.', '_', $version ) ) ); } } $delete_pre_1_2_data = get_transient( 'pll_upgrade_1_4' ); if ( false !== $delete_pre_1_2_data && absint( $delete_pre_1_2_data ) < time() ) { $this->delete_pre_1_2_data(); } $this->options['previous_version'] = $this->options['version']; // remember the previous version of Polylang since v1.7.7 $this->options['version'] = POLYLANG_VERSION; update_option( 'polylang', $this->options ); } /** * upgrades if the previous version is < 0.9 * * @since 1.2 */ protected function upgrade_0_9() { $this->options['sync'] = defined( 'PLL_SYNC' ) && ! PLL_SYNC ? 0 : 1; // the option replaces PLL_SYNC in 0.9 } /** * upgrades if the previous version is < 1.0 * * @since 1.2 */ protected function upgrade_1_0() { // the option replaces PLL_MEDIA_SUPPORT in 1.0 $this->options['media_support'] = defined( 'PLL_MEDIA_SUPPORT' ) && ! PLL_MEDIA_SUPPORT ? 0 : 1; // split the synchronization options in 1.0 $this->options['sync'] = empty( $this->options['sync'] ) ? array() : array_keys( PLL_Settings_Sync::list_metas_to_sync() ); // set default values for post types and taxonomies to translate $this->options['post_types'] = array_values( get_post_types( array( '_builtin' => false, 'show_ui' => true ) ) ); $this->options['taxonomies'] = array_values( get_taxonomies( array( '_builtin' => false, 'show_ui' => true ) ) ); update_option( 'polylang', $this->options ); flush_rewrite_rules(); // rewrite rules have been modified in 1.0 } /** * upgrades if the previous version is < 1.1 * * @since 1.2 */ protected function upgrade_1_1() { // update strings register with icl_register_string $strings = get_option( 'polylang_wpml_strings' ); if ( $strings ) { foreach ( $strings as $key => $string ) { $strings[ $key ]['icl'] = 1; } update_option( 'polylang_wpml_strings', $strings ); } // move polylang_widgets options if ( $widgets = get_option( 'polylang_widgets' ) ) { $this->options['widgets'] = $widgets; delete_option( 'polylang_widgets' ); } } /** * upgrades if the previous version is < 1.2 * * @since 1.2 */ protected function upgrade_1_2() { $this->options['domains'] = array(); // option added in 1.2 // need to register the taxonomies foreach ( array( 'language', 'term_language', 'post_translations', 'term_translations' ) as $taxonomy ) { register_taxonomy( $taxonomy, null , array( 'label' => false, 'public' => false, 'query_var' => false, 'rewrite' => false ) ); } // abort if the db upgrade has already been done previously if ( get_terms( 'term_language', array( 'hide_empty' => 0 ) ) ) { return; } set_time_limit( 0 ); // in case we upgrade a huge site // upgrade old model based on metas to new model based on taxonomies global $wpdb; $wpdb->termmeta = $wpdb->prefix . 'termmeta'; // registers the termmeta table in wpdb $languages = get_terms( 'language', array( 'hide_empty' => 0 ) ); // don't use get_languages_list which can't work with the old model foreach ( $languages as $lang ) { // first update language with new storage for locale and text direction $text_direction = get_metadata( 'term', $lang->term_id, '_rtl', true ); $desc = serialize( array( 'locale' => $lang->description, 'rtl' => $text_direction ) ); wp_update_term( (int) $lang->term_id, 'language', array( 'description' => $desc ) ); // add language to new 'term_language' taxonomy $term_lang = wp_insert_term( $lang->name, 'term_language', array( 'slug' => 'pll_' . $lang->slug ) ); $lang_tt_ids[ $lang->term_id ] = $term_lang['term_taxonomy_id']; // keep the term taxonomy id for future } // get all terms with a language defined $terms = $wpdb->get_results( "SELECT term_id, meta_value FROM $wpdb->termmeta WHERE meta_key = '_language'" ); foreach ( $terms as $key => $term ) { $terms[ $key ] = $wpdb->prepare( '( %d, %d )', $term->term_id, $lang_tt_ids[ $term->meta_value ] ); } $terms = array_unique( $terms ); // assign language to each term if ( ! empty( $terms ) ) { $wpdb->query( "INSERT INTO $wpdb->term_relationships ( object_id, term_taxonomy_id ) VALUES " . implode( ',', $terms ) ); } // translations foreach ( array( 'post', 'term' ) as $type ) { $table = $type . 'meta'; $terms = $slugs = $tts = $trs = array(); // get all translated objects $objects = $wpdb->get_col( "SELECT DISTINCT meta_value FROM {$wpdb->$table} WHERE meta_key = '_translations'" ); if ( empty( $objects ) ) { continue; } foreach ( $objects as $obj ) { $term = uniqid( 'pll_' ); // the term name $terms[] = $wpdb->prepare( '( "%1$s", "%1$s" )', $term ); $slugs[] = $wpdb->prepare( '"%s"', $term ); $translations = maybe_unserialize( maybe_unserialize( $obj ) ); // 2 unserialize due to an old storage bug $description[ $term ] = serialize( $translations ); } $terms = array_unique( $terms ); // insert terms if ( ! empty( $terms ) ) { $wpdb->query( "INSERT INTO $wpdb->terms ( slug, name ) VALUES " . implode( ',', $terms ) ); } // get all terms with their term_id $terms = $wpdb->get_results( "SELECT term_id, slug FROM $wpdb->terms WHERE slug IN ( " . implode( ',', $slugs ) . " )" ); // prepare terms taxonomy relationship foreach ( $terms as $term ) { $tts[] = $wpdb->prepare( '( %d, "%s", "%s" )', $term->term_id, $type . '_translations', $description[ $term->slug ] ); } $tts = array_unique( $tts ); // insert term_taxonomy if ( ! empty( $tts ) ) { $wpdb->query( "INSERT INTO $wpdb->term_taxonomy ( term_id, taxonomy, description ) VALUES " . implode( ',', $tts ) ); } // get all terms with term_taxonomy_id $terms = get_terms( $type . '_translations', array( 'hide_empty' => false ) ); // prepare objects relationships foreach ( $terms as $term ) { $translations = unserialize( $term->description ); foreach ( $translations as $object_id ) { if ( ! empty( $object_id ) ) { $trs[] = $wpdb->prepare( '( %d, %d )', $object_id, $term->term_taxonomy_id ); } } } $trs = array_unique( $trs ); // insert term_relationships if ( ! empty( $trs ) ) { $wpdb->query( "INSERT INTO $wpdb->term_relationships ( object_id, term_taxonomy_id ) VALUES " . implode( ',', $trs ) ); } } // upgrade of string translations is now in upgrade_1_2_1 // upgrade of nav menus is now in upgrade_1_2_3 } /** * upgrades if the previous version is < 1.2.1 * * @since 1.2.1 */ protected function upgrade_1_2_1() { // strings translations foreach ( get_terms( 'language', array( 'hide_empty' => 0 ) ) as $lang ) { if ( $strings = get_option( 'polylang_mo' . $lang->term_id ) ) { $mo = new PLL_MO(); foreach ( $strings as $msg ) { $mo->add_entry( $mo->make_entry( $msg[0], $msg[1] ) ); } $mo->export_to_db( $lang ); } } } /** * upgrades if the previous version is < 1.2.3 * uprades multilingual menus depending on the old version due to multiple changes in menus management * * @since 1.2.3 */ public function upgrade_1_2_3() { // old version < 1.1 // multilingal locations and switcher item were stored in a dedicated option if ( version_compare( $this->options['version'], '1.1', '<' ) ) { if ( $menu_lang = get_option( 'polylang_nav_menus' ) ) { foreach ( $menu_lang as $location => $arr ) { if ( ! in_array( $location, array_keys( get_registered_nav_menus() ) ) ) { continue; } $switch_options = array_slice( $arr, -5, 5 ); $translations = array_diff_key( $arr, $switch_options ); $has_switcher = array_shift( $switch_options ); foreach ( get_terms( 'language', array( 'hide_empty' => 0 ) ) as $lang ) { // move nav menus locations if ( ! empty( $translations[ $lang->slug ] ) ) { $locations[ $location ][ $lang->slug ] = $translations[ $lang->slug ]; } // create the menu items for the language switcher if ( ! empty( $has_switcher ) ) { $menu_item_db_id = wp_update_nav_menu_item( $translations[ $lang->slug ], 0, array( 'menu-item-title' => __( 'Language switcher', 'polylang' ), 'menu-item-url' => '#pll_switcher', 'menu-item-status' => 'publish', ) ); update_post_meta( $menu_item_db_id, '_pll_menu_item', $switch_options ); } } } if ( ! empty( $locations ) ) { $this->options['nav_menus'][ get_option( 'stylesheet' ) ] = $locations; } delete_option( 'polylang_nav_menus' ); } } elseif ( empty( $this->options['nav_menus'] ) ) { $menus = get_theme_mod( 'nav_menu_locations' ); if ( is_array( $menus ) ) { // if old version < 1.2 // clean the WP option as it was a bad idea to pollute it if ( version_compare( $this->options['version'], '1.2', '<' ) ) { foreach ( $menus as $loc => $menu ) { if ( $pos = strpos( $loc, '#' ) ) { unset( $menus[ $loc ] ); } } set_theme_mod( 'nav_menu_locations', $menus ); } // get the multilingual locations foreach ( $menus as $loc => $menu ) { foreach ( get_terms( 'language', array( 'hide_empty' => 0 ) ) as $lang ) { $arr[ $loc ][ $lang->slug ] = pll_get_term( $menu, $lang ); } } if ( ! empty( $arr ) ) { $this->options['nav_menus'][ get_option( 'stylesheet' ) ] = $arr; } } } } /** * upgrades if the previous version is < 1.3 * moves the user biographies in default language to the 'description' user meta * * @since 1.3 */ protected function upgrade_1_3() { $usermeta = 'description_' . $this->options['default_lang']; $query = new WP_User_Query( array( 'blog_id' => $GLOBALS['blog_id'], 'meta_key' => $usermeta ) ); foreach ( $query->get_results() as $user ) { $desc = get_user_meta( $user->ID, $usermeta, true ); if ( ! empty( $desc ) ) { update_user_meta( $user->ID, 'description', $desc ); delete_user_meta( $user->ID, $usermeta ); } } } /** * upgrades if the previous version is < 1.4 * sets a transient to delete old model data * deletes language cache (due to bug correction in home urls in 1.3.1 and added mo_id in 1.4) * * @since 1.4 */ protected function upgrade_1_4() { set_transient( 'pll_upgrade_1_4', time() + 60 * 24 * 60 * 60 ); // 60 days delete_transient( 'pll_languages_list' ); } /** * old data were not deleted in 1.2, just in case... * delete them at first upgrade at least 60 days after upgrade to 1.4 * * @since 1.4 */ protected function delete_pre_1_2_data() { // suppress data of the old model < 1.2 global $wpdb; $wpdb->termmeta = $wpdb->prefix . 'termmeta'; // registers the termmeta table in wpdb in case WP < 4.4 // do nothing if the termmeta table does not exists if ( count( $wpdb->get_results( "SHOW TABLES LIKE '$wpdb->termmeta'" ) ) ) { $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_translations'" ); $wpdb->query( "DELETE FROM $wpdb->termmeta WHERE meta_key = '_language'" ); $wpdb->query( "DELETE FROM $wpdb->termmeta WHERE meta_key = '_rtl'" ); $wpdb->query( "DELETE FROM $wpdb->termmeta WHERE meta_key = '_translations'" ); } // delete the strings translations $languages = get_terms( 'language', array( 'hide_empty' => false ) ); foreach ( $languages as $lang ) { delete_option( 'polylang_mo' . $lang->term_id ); } delete_transient( 'pll_upgrade_1_4' ); } /** * upgrades if the previous version is < 1.4.1 * disables the browser detection when using multiple domains * * @since 1.4.1 */ protected function upgrade_1_4_1() { if ( 3 == $this->options['force_lang'] ) { $this->options['browser'] = $this->options['hide_default'] = 0; } } /** * upgrades if the previous version is < 1.4.4 * uprades widgets options for language filter * * @since 1.4.4 */ protected function upgrade_1_4_4() { foreach ( $GLOBALS['wp_registered_widgets'] as $widget ) { if ( ! empty( $this->options['widgets'][ $widget['id'] ] ) && ! empty( $widget['callback'][0] ) && ! empty( $widget['params'][0]['number'] ) ) { $obj = $widget['callback'][0]; if ( is_object( $obj ) && method_exists( $obj, 'get_settings' ) && method_exists( $obj, 'save_settings' ) ) { $settings = $obj->get_settings(); $settings[ $widget['params'][0]['number'] ]['pll_lang'] = $this->options['widgets'][ $widget['id'] ]; $obj->save_settings( $settings ); } } } unset( $this->options['widgets'] ); } /** * upgrades if the previous version is < 1.5 * deletes language cache (due to host property added and bug on search url) * * @since 1.5 */ protected function upgrade_1_5() { delete_transient( 'pll_languages_list' ); } /** * upgrades if the previous version is < 1.6 * upgrades core language files to get the .po file (only for WP 4.0+) * * @since 1.6 */ protected function upgrade_1_6() { if ( version_compare( $GLOBALS['wp_version'], '4.0', '>=' ) ) { self::download_language_packs(); } } /** * downloads language packs * intended to be used only one time (at upgrade to Polylang 1.6 or first upgrade of WP 4.0 or later) * adapted from wp_download_language_pack * rewritten because wp_download_language_pack checks the existence of .mo and I need to download .po * * @since 1.6 */ static function download_language_packs() { $languages = pll_languages_list( array( 'fields' => 'locale' ) ); // prevents upgrade if the .po file is already here. Let WP manage the upgrades :) foreach ( $languages as $key => $locale ) { if ( file_exists( WP_LANG_DIR . "/$locale.po" ) ) { unset( $languages[ $key ] ); } } if ( empty( $languages ) ) { return; } require_once( ABSPATH . 'wp-admin/includes/translation-install.php' ); $translations = wp_get_available_translations(); if ( ! $translations ) { return; } foreach ( $translations as $translation ) { if ( in_array( $translation['language'], $languages ) ) { $translation['type'] = 'core'; $translations_to_load[] = (object) $translation; } } if ( ! empty( $translations_to_load ) ) { require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); $upgrader = new Language_Pack_Upgrader( new Automatic_Upgrader_Skin ); $upgrader->bulk_upgrade( $translations_to_load, array( 'clear_update_cache' => false ) ); } } /** * upgrades if the previous version is < 1.7.4 * * @since 1.7.4 */ protected function upgrade_1_7_4() { delete_transient( 'pll_languages_list' ); // deletes language cache (due to flag properties added in 1.7, page on front removed in 1.7.2, home url fixes in 1.7.4) flush_rewrite_rules(); // flush rewrite rules due to custom taxonomy rewrite rule bug fix } /** * upgrades if the previous version is < 1.8 * * @since 1.8 */ protected function upgrade_1_8() { // adds the flag code in languages stored in DB include( PLL_SETTINGS_INC . '/languages.php' ); $terms = get_terms( 'language', array( 'hide_empty' => 0 ) ); foreach ( $terms as $lang ) { $description = maybe_unserialize( $lang->description ); if ( isset( $languages[ $description['locale'] ] ) ) { $description['flag_code'] = $languages[ $description['locale'] ][4]; $description = serialize( $description ); wp_update_term( (int) $lang->term_id, 'language', array( 'description' => $description ) ); } } delete_transient( 'pll_languages_list' ); } }
gpl-2.0
dberc/tpzsimul.gems
opal/system/pipepool.C
6630
/* Copyright (C) 1999-2008 by Mark D. Hill and David A. Wood for the Wisconsin Multifacet Project. Contact: gems@cs.wisc.edu http://www.cs.wisc.edu/gems/ -------------------------------------------------------------------- This file is part of the Opal Timing-First Microarchitectural Simulator, a component of the Multifacet GEMS (General Execution-driven Multiprocessor Simulator) software toolset originally developed at the University of Wisconsin-Madison. Opal was originally developed by Carl Mauer based upon code by Craig Zilles. Substantial further development of Multifacet GEMS at the University of Wisconsin was performed by Alaa Alameldeen, Brad Beckmann, Jayaram Bobba, Ross Dickson, Dan Gibson, Pacia Harper, Derek Hower, Milo Martin, Michael Marty, Carl Mauer, Michelle Moravan, Kevin Moore, Andrew Phelps, Manoj Plakal, Daniel Sorin, Haris Volos, Min Xu, and Luke Yen. -------------------------------------------------------------------- If your use of this software contributes to a published paper, we request that you (1) cite our summary paper that appears on our website (http://www.cs.wisc.edu/gems/) and (2) e-mail a citation for your published paper to gems@cs.wisc.edu. If you redistribute derivatives of this software, we request that you notify us and either (1) ask people to register with us at our website (http://www.cs.wisc.edu/gems/) or (2) collect registration information and periodically send it to us. -------------------------------------------------------------------- Multifacet GEMS is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. Multifacet GEMS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the Multifacet GEMS; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA The GNU General Public License is contained in the file LICENSE. ### END HEADER ### */ /* * FileName: pipepool * Synopsis: implements a pool of pipestate objects waiting for something. * Author: cmauer * Version: $Id: pipepool.C 1.1 02/10/02 18:26:23-00:00 cmauer@cottons.cs.wisc.edu $ */ /*------------------------------------------------------------------------*/ /* Includes */ /*------------------------------------------------------------------------*/ #include "hfa.h" #include "wait.h" #include "pipestate.h" #include "pipepool.h" /*------------------------------------------------------------------------*/ /* Macro declarations */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Variable declarations */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Forward declarations */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Constructor(s) / destructor */ /*------------------------------------------------------------------------*/ //************************************************************************** pipepool_t::pipepool_t( ) { m_head = new pipestate_t( NULL ); m_head->initHead(); m_count = 0; } //************************************************************************** pipepool_t::~pipepool_t( ) { } //************************************************************************** void pipepool_t::insertOrdered( pipestate_t *state ) { state->insertOrdered( m_head ); m_count++; } //************************************************************************** pipestate_t *pipepool_t::removeHead( void ) { pipestate_t *element = m_head->removeHead(); if (element != NULL) m_count--; return (element); } //************************************************************************** bool pipepool_t::removeElement( pipestate_t *state ) { bool found = m_head->removeElement( state ); if (found) { m_count--; } return (found); } //************************************************************************** pipestate_t *pipepool_t::walkList( pipestate_t *state ) { if (state == NULL) { state = m_head; } pipestate_t *next = state->m_next; if (next == m_head) { return NULL; } return next; } //************************************************************************** void pipepool_t::print( void ) { DEBUG_OUT("Pipepool_t: %d elements\n", m_count); pipestate_t *cur = m_head->m_next; while (cur != m_head) { cur->print(); cur = cur->m_next; } } /*------------------------------------------------------------------------*/ /* Public methods */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Accessor(s) / mutator(s) */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Private methods */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Static methods */ /*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/ /* Global functions */ /*------------------------------------------------------------------------*/ /** [Memo]. * [Internal Documentation] */ //**************************************************************************
gpl-2.0
azlanismail/prismgames
src/userinterface/GUIOptionsDialog.java
6900
//============================================================================== // // Copyright (c) 2002- // Authors: // * Andrew Hinton <ug60axh@cs.bham.ac.uk> (University of Birmingham) // * Dave Parker <david.parker@comlab.ox.ac.uk> (University of Oxford, formerly University of Birmingham) // //------------------------------------------------------------------------------ // // This file is part of PRISM. // // PRISM is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // PRISM 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 PRISM; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //============================================================================== package userinterface; import java.util.*; import javax.swing.*; import prism.*; import settings.*; public class GUIOptionsDialog extends javax.swing.JDialog { private ArrayList panels; private PrismSettings settings; /** Creates new form GUIOptionsDialog */ public GUIOptionsDialog(GUIPrism parent) { super(parent, true); settings = parent.getPrism().getSettings(); panels = new ArrayList(); initComponents(); this.getRootPane().setDefaultButton(cancelButton); setLocationRelativeTo(getParent()); // centre //setResizable(false); for(int i = 0; i < settings.optionOwners.length; i++) { SettingTable table = new SettingTable(this); ArrayList al = new ArrayList(); settings.optionOwners[i].setDisplay(table); al.add(settings.optionOwners[i]); table.setOwners(al); panels.add(table); theTabs.add(table); theTabs.setTitleAt(panels.indexOf(table), settings.propertyOwnerNames[i]); } } public void addPanel(OptionsPanel p) { // defunct } public void show() { super.show(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents()//GEN-BEGIN:initComponents { jPanel1 = new javax.swing.JPanel(); theTabs = new javax.swing.JTabbedPane(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); defaultButton = new javax.swing.JButton(); saveSettingsButton = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); cancelButton = new javax.swing.JButton(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { closeDialog(evt); } }); jPanel1.setLayout(new java.awt.BorderLayout()); theTabs.setMinimumSize(new java.awt.Dimension(400, 50)); theTabs.setPreferredSize(new java.awt.Dimension(400, 500)); jPanel1.add(theTabs, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel2.setMinimumSize(new java.awt.Dimension(400, 35)); jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); defaultButton.setMnemonic('D'); defaultButton.setText("Load Defaults"); defaultButton.setMaximumSize(new java.awt.Dimension(220, 50)); defaultButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { defaultButtonActionPerformed(evt); } }); jPanel3.add(defaultButton); saveSettingsButton.setMnemonic('S'); saveSettingsButton.setText("Save Options"); saveSettingsButton.setPreferredSize(new java.awt.Dimension(120, 25)); saveSettingsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveSettingsButtonActionPerformed(evt); } }); jPanel3.add(saveSettingsButton); jPanel2.add(jPanel3, java.awt.BorderLayout.CENTER); jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); cancelButton.setText("Okay"); cancelButton.setMaximumSize(new java.awt.Dimension(200, 50)); cancelButton.setMinimumSize(new java.awt.Dimension(80, 25)); cancelButton.setPreferredSize(new java.awt.Dimension(80, 25)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); jPanel4.add(cancelButton); jPanel2.add(jPanel4, java.awt.BorderLayout.EAST); getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); pack(); }//GEN-END:initComponents private void saveSettingsButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveSettingsButtonActionPerformed {//GEN-HEADEREND:event_saveSettingsButtonActionPerformed settings.notifySettingsListeners(); try { settings.saveSettingsFile(); } catch(PrismException e) { GUIPrism.getGUI().errorDialog("Error saving settings:\n"+e.getMessage()); } }//GEN-LAST:event_saveSettingsButtonActionPerformed private void defaultButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_defaultButtonActionPerformed {//GEN-HEADEREND:event_defaultButtonActionPerformed String[] selection = {"Yes", "No"}; int selectionNo = -1; selectionNo = JOptionPane.showOptionDialog(this, "Are you sure you wish to load the default settings?\nAll previous settings will be lost.", "Save Settings", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, selection, selection[0]); if (selectionNo == 0) { settings.loadDefaults(); settings.notifySettingsListeners(); } }//GEN-LAST:event_defaultButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed {//GEN-HEADEREND:event_cancelButtonActionPerformed hide(); }//GEN-LAST:event_cancelButtonActionPerformed /** Closes the dialog */ private void closeDialog(java.awt.event.WindowEvent evt)//GEN-FIRST:event_closeDialog { setVisible(false); dispose(); }//GEN-LAST:event_closeDialog // Variables declaration - do not modify//GEN-BEGIN:variables javax.swing.JButton cancelButton; javax.swing.JButton defaultButton; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JButton saveSettingsButton; javax.swing.JTabbedPane theTabs; // End of variables declaration//GEN-END:variables }
gpl-2.0
lostdj/Jaklin-OpenJFX
modules/graphics/src/test/java/javafx/scene/shape/LineTest.java
4445
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.shape; import com.sun.javafx.sg.prism.NGLine; import com.sun.javafx.sg.prism.NGNode; import javafx.scene.NodeTest; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; public class LineTest { @Test public void testPropertyPropagation_visible() throws Exception { final Line node = new StubLine(); NodeTest.testBooleanPropertyPropagation(node, "visible", false, true); } @Test public void testPropertyPropagation_startX() throws Exception { final Line node = new StubLine(); NodeTest.testDoublePropertyPropagation(node, "startX", "x1", 100, 200); } @Test public void testPropertyPropagation_startY() throws Exception { final Line node = new StubLine(); NodeTest.testDoublePropertyPropagation(node, "startY", "y1", 100, 200); } @Test public void testPropertyPropagation_endX() throws Exception { final Line node = new StubLine(); NodeTest.testDoublePropertyPropagation(node, "endX", "x2", 100, 200); } @Test public void testPropertyPropagation_endY() throws Exception { final Line node = new StubLine(); NodeTest.testDoublePropertyPropagation(node, "endY", "y2", 100, 200); } @Test public void testBoundPropertySync_startX() throws Exception { NodeTest.assertDoublePropertySynced( new StubLine(0.0 ,0.0, 100.0, 100.0), "startX", "x1", 10.0); } @Test public void testBoundPropertySync_startY() throws Exception { NodeTest.assertDoublePropertySynced( new StubLine(0.0 ,0.0, 100.0, 100.0), "startY", "y1", 50.0); } @Test public void testBoundPropertySync_endX() throws Exception { NodeTest.assertDoublePropertySynced( new StubLine(0.0 ,0.0, 100.0, 100.0), "endX", "x2", 200.0); } @Test public void testBoundPropertySync_endY() throws Exception { NodeTest.assertDoublePropertySynced( new StubLine(0.0 ,0.0, 100.0, 100.0), "endY", "y2", 300.0); } @Test public void toStringShouldReturnNonEmptyString() { String s = new StubLine().toString(); assertNotNull(s); assertFalse(s.isEmpty()); } public class StubLine extends Line { public StubLine() { super(); } public StubLine(double startX, double startY, double endX, double endY) { super(startX, startY, endX, endY); } @Override protected NGNode impl_createPeer() { return new StubNGLine(); } } public class StubNGLine extends NGLine { private float x1; private float y1; private float x2; private float y2; public float getX1() {return x1;} public float getX2() {return x2;} public float getY1() {return y1;} public float getY2() {return y2;} @Override public void updateLine(float x1, float y1, float x2, float y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } } }
gpl-2.0
josircg/raizcidadanista
raizcidadanista/filebrowser/management/commands/fb_version_generate.py
3873
# coding: utf-8 # PYTHON IMPORTS import os import re # DJANGO IMPORTS from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.utils.six.moves import input # FILEBROWSER IMPORTS from filebrowser.settings import EXTENSION_LIST, EXCLUDE, DIRECTORY, VERSIONS, EXTENSIONS from filebrowser.base import FileListing, FileObject filter_re = [] for exp in EXCLUDE: filter_re.append(re.compile(exp)) for k, v in VERSIONS.items(): exp = (r'_%s(%s)') % (k, '|'.join(EXTENSION_LIST)) filter_re.append(re.compile(exp)) class Command(BaseCommand): args = '<media_path>' help = "(Re)Generate image versions." def handle(self, *args, **options): media_path = "" if len(args): media_path = args[0] path = media_path else: path = DIRECTORY if not os.path.isdir(os.path.join(settings.MEDIA_ROOT, path)): raise CommandError('<media_path> must be a directory in MEDIA_ROOT (If you don\'t add a media_path the default path is DIRECTORY).\n"%s" is no directory.' % path) # get version name while 1: self.stdout.write('\nSelect a version you want to generate:\n') for version in VERSIONS: self.stdout.write(' * %s\n' % version) version_name = input('(leave blank to generate all versions): ') if version_name == "": selected_version = None break else: try: tmp = VERSIONS[version_name] selected_version = version_name break except: self.stderr.write('Error: Version "%s" doesn\'t exist.\n' % version_name) version_name = None continue # filelisting filelisting = FileListing(path, filter_func=self.filter_images) # FIXME filterfunc: no hidden files, exclude list, no versions, just images! for fileobject in filelisting.files_walk_filtered(): if fileobject.filetype == "Image": if selected_version: self.stdout.write('generating version "%s" for: %s\n' % (selected_version, fileobject.path)) versionobject = fileobject.version_generate(selected_version) # FIXME force? else: self.stdout.write('generating all versions for: %s\n' % fileobject.path) for version in VERSIONS: versionobject = fileobject.version_generate(selected_version) # FIXME force? # # walkt throu the filebrowser directory # # for all/new files (except file versions itself and excludes) # for dirpath,dirnames,filenames in os.walk(path, followlinks=True): # rel_dir = os.path.relpath(dirpath, os.path.realpath(settings.MEDIA_ROOT)) # for filename in filenames: # filtered = False # # no "hidden" files (stating with ".") # if filename.startswith('.'): # continue # # check the exclude list # for re_prefix in filter_re: # if re_prefix.search(filename): # filtered = True # if filtered: # continue # (tmp, extension) = os.path.splitext(filename) # if extension in EXTENSIONS["Image"]: # self.createVersions(os.path.join(rel_dir, filename), selected_version) def filter_images(self, item): filtered = item.filename.startswith('.') for re_prefix in filter_re: if re_prefix.search(item.filename): filtered = True if filtered: return False return True
gpl-3.0
SketchMagento/mage_crowdfunding
app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
8505
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Catalog * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Configurable product type resource model * * @category Mage * @package Mage_Catalog * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Catalog_Model_Resource_Product_Type_Configurable extends Mage_Core_Model_Resource_Db_Abstract { /** * Init resource * */ protected function _construct() { $this->_init('catalog/product_super_link', 'link_id'); } /** * Save configurable product relations * * @param Mage_Catalog_Model_Product|int $mainProduct the parent id * @param array $productIds the children id array * @return Mage_Catalog_Model_Resource_Product_Type_Configurable */ public function saveProducts($mainProduct, $productIds) { $isProductInstance = false; if ($mainProduct instanceof Mage_Catalog_Model_Product) { $mainProductId = $mainProduct->getId(); $isProductInstance = true; } else { $mainProductId = $mainProduct; } $old = $mainProduct->getTypeInstance()->getUsedProductIds(); $insert = array_diff($productIds, $old); $delete = array_diff($old, $productIds); if ((!empty($insert) || !empty($delete)) && $isProductInstance) { $mainProduct->setIsRelationsChanged(true); } if (!empty($delete)) { $where = array( 'parent_id = ?' => $mainProductId, 'product_id IN(?)' => $delete ); $this->_getWriteAdapter()->delete($this->getMainTable(), $where); } if (!empty($insert)) { $data = array(); foreach ($insert as $childId) { $data[] = array( 'product_id' => (int)$childId, 'parent_id' => (int)$mainProductId ); } $this->_getWriteAdapter()->insertMultiple($this->getMainTable(), $data); } // configurable product relations should be added to relation table Mage::getResourceSingleton('catalog/product_relation') ->processRelations($mainProductId, $productIds); return $this; } /** * Retrieve Required children ids * Return grouped array, ex array( * group => array(ids) * ) * * @param int $parentId * @param bool $required * @return array */ public function getChildrenIds($parentId, $required = true) { $childrenIds = array(); $select = $this->_getReadAdapter()->select() ->from(array('l' => $this->getMainTable()), array('product_id', 'parent_id')) ->join( array('e' => $this->getTable('catalog/product')), 'e.entity_id = l.product_id AND e.required_options = 0', array() ) ->where('parent_id = ?', $parentId); $childrenIds = array(0 => array()); foreach ($this->_getReadAdapter()->fetchAll($select) as $row) { $childrenIds[0][$row['product_id']] = $row['product_id']; } return $childrenIds; } /** * Retrieve parent ids array by requered child * * @param int|array $childId * @return array */ public function getParentIdsByChild($childId) { $parentIds = array(); $select = $this->_getReadAdapter()->select() ->from($this->getMainTable(), array('product_id', 'parent_id')) ->where('product_id IN(?)', $childId); foreach ($this->_getReadAdapter()->fetchAll($select) as $row) { $parentIds[] = $row['parent_id']; } return $parentIds; } /** * Collect product options with values according to the product instance and attributes, that were received * * @param Mage_Catalog_Model_Product $product * @param array $attributes * @return array */ public function getConfigurableOptions($product, $attributes) { $attributesOptionsData = array(); foreach ($attributes as $superAttribute) { $select = $this->_getReadAdapter()->select() ->from( array( 'super_attribute' => $this->getTable('catalog/product_super_attribute') ), array( 'sku' => 'entity.sku', 'product_id' => 'super_attribute.product_id', 'attribute_code' => 'attribute.attribute_code', 'option_title' => 'option_value.value', 'pricing_value' => 'attribute_pricing.pricing_value', 'pricing_is_percent' => 'attribute_pricing.is_percent' ) )->joinInner( array( 'product_link' => $this->getTable('catalog/product_super_link') ), 'product_link.parent_id = super_attribute.product_id', array() )->joinInner( array( 'attribute' => $this->getTable('eav/attribute') ), 'attribute.attribute_id = super_attribute.attribute_id', array() )->joinInner( array( 'entity' => $this->getTable('catalog/product') ), 'entity.entity_id = product_link.product_id', array() )->joinInner( array( 'entity_value' => $superAttribute->getBackendTable() ), implode( ' AND ', array( $this->_getReadAdapter() ->quoteInto('entity_value.entity_type_id = ?', $product->getEntityTypeId()), 'entity_value.attribute_id = super_attribute.attribute_id', 'entity_value.store_id = 0', 'entity_value.entity_id = product_link.product_id' ) ), array() )->joinLeft( array( 'option_value' => $this->getTable('eav/attribute_option_value') ), implode(' AND ', array( 'option_value.option_id = entity_value.value', 'option_value.store_id = ' . Mage_Core_Model_App::ADMIN_STORE_ID, )), array() )->joinLeft( array( 'attribute_pricing' => $this->getTable('catalog/product_super_attribute_pricing') ), implode(' AND ', array( 'super_attribute.product_super_attribute_id = attribute_pricing.product_super_attribute_id', 'entity_value.value = attribute_pricing.value_index' )), array() )->where('super_attribute.product_id = ?', $product->getId()); $attributesOptionsData[$superAttribute->getAttributeId()] = $this->_getReadAdapter()->fetchAll($select); } return $attributesOptionsData; } }
gpl-3.0
ideasiii/ControllerPlatform
Controller-WheelPies/extLibs/mongo-cxx-driver/src/mongo/client/sasl_client_conversation.cpp
774
/* * Copyright (C) 2014 MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mongo/client/sasl_client_conversation.h" namespace mongo { SaslClientConversation::~SaslClientConversation(){}; } // namespace mongo
gpl-3.0
fillycheezstake/ardupilot
ArduPlane/ArduPlane.cpp
26552
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /* Lead developer: Andrew Tridgell Authors: Doug Weibel, Jose Julio, Jordi Munoz, Jason Short, Randy Mackay, Pat Hickey, John Arne Birkeland, Olivier Adler, Amilcar Lucas, Gregory Fletcher, Paul Riseborough, Brandon Jones, Jon Challinger Thanks to: Chris Anderson, Michael Oborne, Paul Mather, Bill Premerlani, James Cohen, JB from rotorFX, Automatik, Fefenin, Peter Meister, Remzibi, Yury Smirnov, Sandro Benigno, Max Levine, Roberto Navoni, Lorenz Meier, Yury MonZon Please contribute your ideas! See http://dev.ardupilot.com for details 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/>. */ #include "Plane.h" #define SCHED_TASK(func) FUNCTOR_BIND(&plane, &Plane::func, void) /* scheduler table - all regular tasks are listed here, along with how often they should be called (in 20ms units) and the maximum time they are expected to take (in microseconds) */ const AP_Scheduler::Task Plane::scheduler_tasks[] PROGMEM = { { SCHED_TASK(read_radio), 1, 700 }, // 0 { SCHED_TASK(check_short_failsafe), 1, 1000 }, { SCHED_TASK(ahrs_update), 1, 6400 }, { SCHED_TASK(update_speed_height), 1, 1600 }, { SCHED_TASK(update_flight_mode), 1, 1400 }, { SCHED_TASK(stabilize), 1, 3500 }, { SCHED_TASK(set_servos), 1, 1600 }, { SCHED_TASK(read_control_switch), 7, 1000 }, { SCHED_TASK(gcs_retry_deferred), 1, 1000 }, { SCHED_TASK(update_GPS_50Hz), 1, 2500 }, { SCHED_TASK(update_GPS_10Hz), 5, 2500 }, // 10 { SCHED_TASK(navigate), 5, 3000 }, { SCHED_TASK(update_compass), 5, 1200 }, { SCHED_TASK(read_airspeed), 5, 1200 }, { SCHED_TASK(update_alt), 5, 3400 }, { SCHED_TASK(adjust_altitude_target), 5, 1000 }, { SCHED_TASK(obc_fs_check), 5, 1000 }, { SCHED_TASK(gcs_update), 1, 1700 }, { SCHED_TASK(gcs_data_stream_send), 1, 3000 }, { SCHED_TASK(update_events), 1, 1500 }, // 20 { SCHED_TASK(check_usb_mux), 5, 300 }, { SCHED_TASK(read_battery), 5, 1000 }, { SCHED_TASK(compass_accumulate), 1, 1500 }, { SCHED_TASK(barometer_accumulate), 1, 900 }, { SCHED_TASK(update_notify), 1, 300 }, { SCHED_TASK(read_rangefinder), 1, 500 }, #if OPTFLOW == ENABLED { SCHED_TASK(update_optical_flow), 1, 500 }, #endif { SCHED_TASK(one_second_loop), 50, 1000 }, { SCHED_TASK(check_long_failsafe), 15, 1000 }, { SCHED_TASK(read_receiver_rssi), 5, 1000 }, { SCHED_TASK(airspeed_ratio_update), 50, 1000 }, // 30 { SCHED_TASK(update_mount), 1, 1500 }, { SCHED_TASK(log_perf_info), 500, 1000 }, { SCHED_TASK(compass_save), 3000, 2500 }, { SCHED_TASK(update_logging1), 5, 1700 }, { SCHED_TASK(update_logging2), 5, 1700 }, #if FRSKY_TELEM_ENABLED == ENABLED { SCHED_TASK(frsky_telemetry_send), 10, 100 }, #endif { SCHED_TASK(terrain_update), 5, 500 }, { SCHED_TASK(update_is_flying_5Hz), 10, 100 }, }; void Plane::setup() { cliSerial = hal.console; // load the default values of variables listed in var_info[] AP_Param::setup_sketch_defaults(); AP_Notify::flags.failsafe_battery = false; notify.init(false); rssi_analog_source = hal.analogin->channel(ANALOG_INPUT_NONE); init_ardupilot(); // initialise the main loop scheduler scheduler.init(&scheduler_tasks[0], ARRAY_SIZE(scheduler_tasks)); } void Plane::loop() { // wait for an INS sample ins.wait_for_sample(); uint32_t timer = micros(); delta_us_fast_loop = timer - fast_loopTimer_us; G_Dt = delta_us_fast_loop * 1.0e-6f; if (delta_us_fast_loop > G_Dt_max && fast_loopTimer_us != 0) { G_Dt_max = delta_us_fast_loop; } if (delta_us_fast_loop < G_Dt_min || G_Dt_min == 0) { G_Dt_min = delta_us_fast_loop; } fast_loopTimer_us = timer; mainLoop_count++; // tell the scheduler one tick has passed scheduler.tick(); // run all the tasks that are due to run. Note that we only // have to call this once per loop, as the tasks are scheduled // in multiples of the main loop tick. So if they don't run on // the first call to the scheduler they won't run on a later // call until scheduler.tick() is called again uint32_t remaining = (timer + 20000) - micros(); if (remaining > 19500) { remaining = 19500; } scheduler.run(remaining); } // update AHRS system void Plane::ahrs_update() { hal.util->set_soft_armed(arming.is_armed() && hal.util->safety_switch_state() != AP_HAL::Util::SAFETY_DISARMED); #if HIL_SUPPORT if (g.hil_mode == 1) { // update hil before AHRS update gcs_update(); } #endif ahrs.update(); if (should_log(MASK_LOG_ATTITUDE_FAST)) { Log_Write_Attitude(); } if (should_log(MASK_LOG_IMU)) { Log_Write_IMU(); #if HAL_CPU_CLASS >= HAL_CPU_CLASS_75 DataFlash.Log_Write_IMUDT(ins); #endif } // calculate a scaled roll limit based on current pitch roll_limit_cd = g.roll_limit_cd * cosf(ahrs.pitch); pitch_limit_min_cd = aparm.pitch_limit_min_cd * fabsf(cosf(ahrs.roll)); // updated the summed gyro used for ground steering and // auto-takeoff. Dot product of DCM.c with gyro vector gives earth // frame yaw rate steer_state.locked_course_err += ahrs.get_yaw_rate_earth() * G_Dt; steer_state.locked_course_err = wrap_PI(steer_state.locked_course_err); } /* update 50Hz speed/height controller */ void Plane::update_speed_height(void) { if (auto_throttle_mode) { // Call TECS 50Hz update. Note that we call this regardless of // throttle suppressed, as this needs to be running for // takeoff detection SpdHgt_Controller->update_50hz(tecs_hgt_afe()); } } /* update camera mount */ void Plane::update_mount(void) { #if MOUNT == ENABLED camera_mount.update(); #endif #if CAMERA == ENABLED camera.trigger_pic_cleanup(); #endif } /* read and update compass */ void Plane::update_compass(void) { if (g.compass_enabled && compass.read()) { ahrs.set_compass(&compass); compass.learn_offsets(); if (should_log(MASK_LOG_COMPASS)) { DataFlash.Log_Write_Compass(compass); } } else { ahrs.set_compass(NULL); } } /* if the compass is enabled then try to accumulate a reading */ void Plane::compass_accumulate(void) { if (g.compass_enabled) { compass.accumulate(); } } /* try to accumulate a baro reading */ void Plane::barometer_accumulate(void) { barometer.accumulate(); } /* do 10Hz logging */ void Plane::update_logging1(void) { if (should_log(MASK_LOG_ATTITUDE_MED) && !should_log(MASK_LOG_ATTITUDE_FAST)) { Log_Write_Attitude(); } if (should_log(MASK_LOG_ATTITUDE_MED) && !should_log(MASK_LOG_IMU)) Log_Write_IMU(); } /* do 10Hz logging - part2 */ void Plane::update_logging2(void) { if (should_log(MASK_LOG_CTUN)) Log_Write_Control_Tuning(); if (should_log(MASK_LOG_NTUN)) Log_Write_Nav_Tuning(); if (should_log(MASK_LOG_RC)) Log_Write_RC(); #if HAL_CPU_CLASS >= HAL_CPU_CLASS_75 if (should_log(MASK_LOG_IMU)) DataFlash.Log_Write_Vibration(ins); #endif } /* check for OBC failsafe check */ void Plane::obc_fs_check(void) { #if OBC_FAILSAFE == ENABLED // perform OBC failsafe checks obc.check(OBC_MODE(control_mode), failsafe.last_heartbeat_ms, geofence_breached(), failsafe.last_valid_rc_ms); #endif } /* update aux servo mappings */ void Plane::update_aux(void) { RC_Channel_aux::enable_aux_servos(); } void Plane::one_second_loop() { if (should_log(MASK_LOG_CURRENT)) Log_Write_Current(); // send a heartbeat gcs_send_message(MSG_HEARTBEAT); // make it possible to change control channel ordering at runtime set_control_channels(); // make it possible to change orientation at runtime ahrs.set_orientation(); // sync MAVLink system ID mavlink_system.sysid = g.sysid_this_mav; update_aux(); // update notify flags AP_Notify::flags.pre_arm_check = arming.pre_arm_checks(false); AP_Notify::flags.pre_arm_gps_check = true; AP_Notify::flags.armed = arming.is_armed() || arming.arming_required() == AP_Arming::NO; crash_detection_update(); #if AP_TERRAIN_AVAILABLE if (should_log(MASK_LOG_GPS)) { terrain.log_terrain_data(DataFlash); } #endif // piggyback the status log entry on the MODE log entry flag if (should_log(MASK_LOG_MODE)) { Log_Write_Status(); } #if HAL_CPU_CLASS >= HAL_CPU_CLASS_75 ins.set_raw_logging(should_log(MASK_LOG_IMU_RAW)); #endif } void Plane::log_perf_info() { if (scheduler.debug() != 0) { gcs_send_text_fmt(PSTR("G_Dt_max=%lu G_Dt_min=%lu\n"), (unsigned long)G_Dt_max, (unsigned long)G_Dt_min); } #if HAL_CPU_CLASS >= HAL_CPU_CLASS_75 if (should_log(MASK_LOG_PM)) Log_Write_Performance(); #endif G_Dt_max = 0; G_Dt_min = 0; resetPerfData(); } void Plane::compass_save() { if (g.compass_enabled) { compass.save_offsets(); } } void Plane::terrain_update(void) { #if AP_TERRAIN_AVAILABLE terrain.update(); // tell the rangefinder our height, so it can go into power saving // mode if available float height; if (terrain.height_above_terrain(height, true)) { rangefinder.set_estimated_terrain_height(height); } #endif } /* once a second update the airspeed calibration ratio */ void Plane::airspeed_ratio_update(void) { if (!airspeed.enabled() || gps.status() < AP_GPS::GPS_OK_FIX_3D || gps.ground_speed() < 4) { // don't calibrate when not moving return; } if (airspeed.get_airspeed() < aparm.airspeed_min && gps.ground_speed() < (uint32_t)aparm.airspeed_min) { // don't calibrate when flying below the minimum airspeed. We // check both airspeed and ground speed to catch cases where // the airspeed ratio is way too low, which could lead to it // never coming up again return; } if (abs(ahrs.roll_sensor) > roll_limit_cd || ahrs.pitch_sensor > aparm.pitch_limit_max_cd || ahrs.pitch_sensor < pitch_limit_min_cd) { // don't calibrate when going beyond normal flight envelope return; } const Vector3f &vg = gps.velocity(); airspeed.update_calibration(vg); gcs_send_airspeed_calibration(vg); } /* read the GPS and update position */ void Plane::update_GPS_50Hz(void) { static uint32_t last_gps_reading[GPS_MAX_INSTANCES]; gps.update(); for (uint8_t i=0; i<gps.num_sensors(); i++) { if (gps.last_message_time_ms(i) != last_gps_reading[i]) { last_gps_reading[i] = gps.last_message_time_ms(i); if (should_log(MASK_LOG_GPS)) { Log_Write_GPS(i); } } } } /* read update GPS position - 10Hz update */ void Plane::update_GPS_10Hz(void) { // get position from AHRS have_position = ahrs.get_position(current_loc); static uint32_t last_gps_msg_ms; if (gps.last_message_time_ms() != last_gps_msg_ms && gps.status() >= AP_GPS::GPS_OK_FIX_3D) { last_gps_msg_ms = gps.last_message_time_ms(); if (ground_start_count > 1) { ground_start_count--; } else if (ground_start_count == 1) { // We countdown N number of good GPS fixes // so that the altitude is more accurate // ------------------------------------- if (current_loc.lat == 0) { ground_start_count = 5; } else { init_home(); // set system clock for log timestamps hal.util->set_system_clock(gps.time_epoch_usec()); if (g.compass_enabled) { // Set compass declination automatically const Location &loc = gps.location(); compass.set_initial_location(loc.lat, loc.lng); } ground_start_count = 0; } } // see if we've breached the geo-fence geofence_check(false); #if CAMERA == ENABLED if (camera.update_location(current_loc) == true) { do_take_picture(); } #endif if (!hal.util->get_soft_armed()) { update_home(); } // update wind estimate ahrs.estimate_wind(); } calc_gndspeed_undershoot(); } /* main handling for AUTO mode */ void Plane::handle_auto_mode(void) { uint8_t nav_cmd_id; // we should be either running a mission or RTLing home if (mission.state() == AP_Mission::MISSION_RUNNING) { nav_cmd_id = mission.get_current_nav_cmd().id; }else{ nav_cmd_id = auto_rtl_command.id; } switch(nav_cmd_id) { case MAV_CMD_NAV_TAKEOFF: takeoff_calc_roll(); takeoff_calc_pitch(); calc_throttle(); break; case MAV_CMD_NAV_LAND: calc_nav_roll(); calc_nav_pitch(); if (auto_state.land_complete) { // during final approach constrain roll to the range // allowed for level flight nav_roll_cd = constrain_int32(nav_roll_cd, -g.level_roll_limit*100UL, g.level_roll_limit*100UL); } calc_throttle(); if (auto_state.land_complete) { // we are in the final stage of a landing - force // zero throttle channel_throttle->servo_out = 0; } break; default: // we are doing normal AUTO flight, the special cases // are for takeoff and landing steer_state.hold_course_cd = -1; auto_state.land_complete = false; calc_nav_roll(); calc_nav_pitch(); calc_throttle(); break; } } /* main flight mode dependent update code */ void Plane::update_flight_mode(void) { enum FlightMode effective_mode = control_mode; if (control_mode == AUTO && g.auto_fbw_steer) { effective_mode = FLY_BY_WIRE_A; } if (effective_mode != AUTO) { // hold_course is only used in takeoff and landing steer_state.hold_course_cd = -1; } switch (effective_mode) { case AUTO: handle_auto_mode(); break; case RTL: case LOITER: case GUIDED: calc_nav_roll(); calc_nav_pitch(); calc_throttle(); break; case TRAINING: { training_manual_roll = false; training_manual_pitch = false; update_load_factor(); // if the roll is past the set roll limit, then // we set target roll to the limit if (ahrs.roll_sensor >= roll_limit_cd) { nav_roll_cd = roll_limit_cd; } else if (ahrs.roll_sensor <= -roll_limit_cd) { nav_roll_cd = -roll_limit_cd; } else { training_manual_roll = true; nav_roll_cd = 0; } // if the pitch is past the set pitch limits, then // we set target pitch to the limit if (ahrs.pitch_sensor >= aparm.pitch_limit_max_cd) { nav_pitch_cd = aparm.pitch_limit_max_cd; } else if (ahrs.pitch_sensor <= pitch_limit_min_cd) { nav_pitch_cd = pitch_limit_min_cd; } else { training_manual_pitch = true; nav_pitch_cd = 0; } if (fly_inverted()) { nav_pitch_cd = -nav_pitch_cd; } break; } case ACRO: { // handle locked/unlocked control if (acro_state.locked_roll) { nav_roll_cd = acro_state.locked_roll_err; } else { nav_roll_cd = ahrs.roll_sensor; } if (acro_state.locked_pitch) { nav_pitch_cd = acro_state.locked_pitch_cd; } else { nav_pitch_cd = ahrs.pitch_sensor; } break; } case AUTOTUNE: case FLY_BY_WIRE_A: { // set nav_roll and nav_pitch using sticks nav_roll_cd = channel_roll->norm_input() * roll_limit_cd; nav_roll_cd = constrain_int32(nav_roll_cd, -roll_limit_cd, roll_limit_cd); update_load_factor(); float pitch_input = channel_pitch->norm_input(); if (pitch_input > 0) { nav_pitch_cd = pitch_input * aparm.pitch_limit_max_cd; } else { nav_pitch_cd = -(pitch_input * pitch_limit_min_cd); } adjust_nav_pitch_throttle(); nav_pitch_cd = constrain_int32(nav_pitch_cd, pitch_limit_min_cd, aparm.pitch_limit_max_cd.get()); if (fly_inverted()) { nav_pitch_cd = -nav_pitch_cd; } if (failsafe.ch3_failsafe && g.short_fs_action == 2) { // FBWA failsafe glide nav_roll_cd = 0; nav_pitch_cd = 0; channel_throttle->servo_out = 0; } if (g.fbwa_tdrag_chan > 0) { // check for the user enabling FBWA taildrag takeoff mode bool tdrag_mode = (hal.rcin->read(g.fbwa_tdrag_chan-1) > 1700); if (tdrag_mode && !auto_state.fbwa_tdrag_takeoff_mode) { if (auto_state.highest_airspeed < g.takeoff_tdrag_speed1) { auto_state.fbwa_tdrag_takeoff_mode = true; gcs_send_text_P(SEVERITY_LOW, PSTR("FBWA tdrag mode\n")); } } } break; } case FLY_BY_WIRE_B: // Thanks to Yury MonZon for the altitude limit code! nav_roll_cd = channel_roll->norm_input() * roll_limit_cd; nav_roll_cd = constrain_int32(nav_roll_cd, -roll_limit_cd, roll_limit_cd); update_load_factor(); update_fbwb_speed_height(); break; case CRUISE: /* in CRUISE mode we use the navigation code to control roll when heading is locked. Heading becomes unlocked on any aileron or rudder input */ if ((channel_roll->control_in != 0 || rudder_input != 0)) { cruise_state.locked_heading = false; cruise_state.lock_timer_ms = 0; } if (!cruise_state.locked_heading) { nav_roll_cd = channel_roll->norm_input() * roll_limit_cd; nav_roll_cd = constrain_int32(nav_roll_cd, -roll_limit_cd, roll_limit_cd); update_load_factor(); } else { calc_nav_roll(); } update_fbwb_speed_height(); break; case STABILIZE: nav_roll_cd = 0; nav_pitch_cd = 0; // throttle is passthrough break; case CIRCLE: // we have no GPS installed and have lost radio contact // or we just want to fly around in a gentle circle w/o GPS, // holding altitude at the altitude we set when we // switched into the mode nav_roll_cd = roll_limit_cd / 3; update_load_factor(); calc_nav_pitch(); calc_throttle(); break; case MANUAL: // servo_out is for Sim control only // --------------------------------- channel_roll->servo_out = channel_roll->pwm_to_angle(); channel_pitch->servo_out = channel_pitch->pwm_to_angle(); steering_control.steering = steering_control.rudder = channel_rudder->pwm_to_angle(); break; //roll: -13788.000, pitch: -13698.000, thr: 0.000, rud: -13742.000 case INITIALISING: // handled elsewhere break; } } void Plane::update_navigation() { // wp_distance is in ACTUAL meters, not the *100 meters we get from the GPS // ------------------------------------------------------------------------ // distance and bearing calcs only switch(control_mode) { case AUTO: update_commands(); break; case RTL: if (g.rtl_autoland == 1 && !auto_state.checked_for_autoland && nav_controller->reached_loiter_target() && labs(altitude_error_cm) < 1000) { // we've reached the RTL point, see if we have a landing sequence jump_to_landing_sequence(); // prevent running the expensive jump_to_landing_sequence // on every loop auto_state.checked_for_autoland = true; } else if (g.rtl_autoland == 2 && !auto_state.checked_for_autoland) { // Go directly to the landing sequence jump_to_landing_sequence(); // prevent running the expensive jump_to_landing_sequence // on every loop auto_state.checked_for_autoland = true; } // fall through to LOITER case LOITER: case GUIDED: // allow loiter direction to be changed in flight if (g.loiter_radius < 0) { loiter.direction = -1; } else { loiter.direction = 1; } update_loiter(); break; case CRUISE: update_cruise(); break; case MANUAL: case STABILIZE: case TRAINING: case INITIALISING: case ACRO: case FLY_BY_WIRE_A: case AUTOTUNE: case FLY_BY_WIRE_B: case CIRCLE: // nothing to do break; } } /* set the flight stage */ void Plane::set_flight_stage(AP_SpdHgtControl::FlightStage fs) { //if just now entering land flight stage if (fs == AP_SpdHgtControl::FLIGHT_LAND_APPROACH && flight_stage != AP_SpdHgtControl::FLIGHT_LAND_APPROACH) { #if GEOFENCE_ENABLED == ENABLED if (g.fence_autoenable == 1) { if (! geofence_set_enabled(false, AUTO_TOGGLED)) { gcs_send_text_P(SEVERITY_HIGH, PSTR("Disable fence failed (autodisable)")); } else { gcs_send_text_P(SEVERITY_HIGH, PSTR("Fence disabled (autodisable)")); } } else if (g.fence_autoenable == 2) { if (! geofence_set_floor_enabled(false)) { gcs_send_text_P(SEVERITY_HIGH, PSTR("Disable fence floor failed (autodisable)")); } else { gcs_send_text_P(SEVERITY_HIGH, PSTR("Fence floor disabled (auto disable)")); } } #endif } flight_stage = fs; } void Plane::update_alt() { barometer.update(); if (should_log(MASK_LOG_IMU)) { Log_Write_Baro(); } // calculate the sink rate. float sink_rate; Vector3f vel; if (ahrs.get_velocity_NED(vel)) { sink_rate = vel.z; } else if (gps.status() >= AP_GPS::GPS_OK_FIX_3D && gps.have_vertical_velocity()) { sink_rate = gps.velocity().z; } else { sink_rate = -barometer.get_climb_rate(); } // low pass the sink rate to take some of the noise out auto_state.sink_rate = 0.8f * auto_state.sink_rate + 0.2f*sink_rate; geofence_check(true); update_flight_stage(); } /* recalculate the flight_stage */ void Plane::update_flight_stage(void) { // Update the speed & height controller states if (auto_throttle_mode && !throttle_suppressed) { if (control_mode==AUTO) { if (auto_state.takeoff_complete == false) { set_flight_stage(AP_SpdHgtControl::FLIGHT_TAKEOFF); } else if (mission.get_current_nav_cmd().id == MAV_CMD_NAV_LAND && auto_state.land_complete == true) { set_flight_stage(AP_SpdHgtControl::FLIGHT_LAND_FINAL); } else if (mission.get_current_nav_cmd().id == MAV_CMD_NAV_LAND) { set_flight_stage(AP_SpdHgtControl::FLIGHT_LAND_APPROACH); } else { set_flight_stage(AP_SpdHgtControl::FLIGHT_NORMAL); } } else { set_flight_stage(AP_SpdHgtControl::FLIGHT_NORMAL); } SpdHgt_Controller->update_pitch_throttle(relative_target_altitude_cm(), target_airspeed_cm, flight_stage, auto_state.takeoff_pitch_cd, throttle_nudge, tecs_hgt_afe(), aerodynamic_load_factor); if (should_log(MASK_LOG_TECS)) { Log_Write_TECS_Tuning(); } } // tell AHRS the airspeed to true airspeed ratio airspeed.set_EAS2TAS(barometer.get_EAS2TAS()); } #if OPTFLOW == ENABLED // called at 50hz void Plane::update_optical_flow(void) { static uint32_t last_of_update = 0; // exit immediately if not enabled if (!optflow.enabled()) { return; } // read from sensor optflow.update(); // write to log and send to EKF if new data has arrived if (optflow.last_update() != last_of_update) { last_of_update = optflow.last_update(); uint8_t flowQuality = optflow.quality(); Vector2f flowRate = optflow.flowRate(); Vector2f bodyRate = optflow.bodyRate(); ahrs.writeOptFlowMeas(flowQuality, flowRate, bodyRate, last_of_update); Log_Write_Optflow(); } } #endif /* compatibility with old pde style build */ void setup(void); void loop(void); void setup(void) { plane.setup(); } void loop(void) { plane.loop(); } AP_HAL_MAIN();
gpl-3.0
EITIorg/eiti
public_html/sites/all/modules/contrib/webform_steps/webform_steps_w3/webform4.php
2318
<?php /** * Implements hook_form_FORM_ID_alter(). */ function webform_steps_w3_form_webform_admin_settings_alter(&$form, &$form_state) { $form['progressbar_migrate'] = array( '#type' => 'fieldset', '#title' => t('Progressbar migration'), '#description' => t('Import progressbar settings stored by the webform3 compatibility module (webform_steps_w3) into webform. Note that configurations made with webform4 might be overriden.'), '#weight' => -100, ); $form['progressbar_migrate']['submit'] = array( '#type' => 'submit', '#value' => t('Start migration'), '#submit' => array('webform_steps_w3_migrate'), ); } /** * Copy setting from webform_steps_w3_progressbar to webform. */ function webform_steps_w3_migrate() { $sql = <<<SQL UPDATE {webform} w INNER JOIN {webform_steps_w3_progressbar} w3 USING(nid) SET w.progressbar_bar = w3.progressbar_bar, w.progressbar_page_number = w3.progressbar_page_number, w.progressbar_percent = w3.progressbar_percent, w.progressbar_pagebreak_labels = w3.progressbar_pagebreak_labels, w.progressbar_label_first = w3.progressbar_label_first SQL; db_query($sql); drupal_set_message(t('All configurations have now been migrated to webform4. You can now safely disable and uninstall webform_steps_w3.')); } /** * Implements hook_node_load(). */ function webform_steps_w3_node_load($nodes, $types) { // Quick check to see if we need to do anything at all for these nodes. $webform_types = webform_variable_get('webform_node_types'); if (count(array_intersect($types, $webform_types)) == 0) { return; } $defaults = webform_steps_w3_node_defaults(); // Select all webforms that match these node IDs. $q = db_select('webform', 'w'); $q->leftJoin('webform_steps_w3_progressbar', 'settings', 'w.nid=settings.nid'); $q->addfield('settings', 'nid', 'has_settings'); $result = $q->fields('w', array('nid')) ->fields('settings', array_keys($defaults)) ->condition('w.nid', array_keys($nodes), 'IN') ->execute() ->fetchAllAssoc('nid', PDO::FETCH_ASSOC); foreach ($result as $nid => $settings) { // Add progressbar settings to each node. if ($settings['has_settings']) { unset($settings['has_settings']); $nodes[$nid]->webform = $settings + $nodes[$nid]->webform; } } }
gpl-3.0
garthylou/pootle
pootle/static/js/auth/components/SocialAuthError.js
1428
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ 'use strict'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AuthContent from './AuthContent'; let SocialAuthError = React.createClass({ mixins: [PureRenderMixin], propTypes: { socialError: React.PropTypes.object, }, /* Layout */ render() { let errorMsg; if (this.props.socialError) { errorMsg = interpolate( gettext('An error occurred while attempting to sign in via %s.'), [this.props.socialError.provider] ); } else { errorMsg = gettext('An error occurred while attempting to sign in via your social account.'); } let errorFace = { fontSize: '400%', marginBottom: '0.5em', }; return ( <AuthContent> <h2 style={errorFace}>{`{õ_õ}`}</h2> <p>{errorMsg}</p> {this.props.socialError && <p>{`${this.props.socialError.exception.name}: ${this.props.socialError.exception.msg} `}</p> } {this.props.socialError && <a href={this.props.socialError.retry_url}> {gettext('Try again')} </a> } </AuthContent> ); } }); export default SocialAuthError;
gpl-3.0
jesseyu/nongfei-missionplane
Android/src/com/MAVLink/common/msg_gps_status.java
4994
// MESSAGE GPS_STATUS PACKING package com.MAVLink.common; import com.MAVLink.MAVLinkPacket; import com.MAVLink.Messages.MAVLinkMessage; import com.MAVLink.Messages.MAVLinkPayload; //import android.util.Log; /** * The positioning status, as reported by GPS. This message is intended to display status information about each satellite visible to the receiver. See message GLOBAL_POSITION for the global position estimate. This message can contain information for up to 20 satellites. */ public class msg_gps_status extends MAVLinkMessage{ public static final int MAVLINK_MSG_ID_GPS_STATUS = 25; public static final int MAVLINK_MSG_LENGTH = 101; private static final long serialVersionUID = MAVLINK_MSG_ID_GPS_STATUS; /** * Number of satellites visible */ public byte satellites_visible; /** * Global satellite ID */ public byte satellite_prn[] = new byte[20]; /** * 0: Satellite not used, 1: used for localization */ public byte satellite_used[] = new byte[20]; /** * Elevation (0: right on top of receiver, 90: on the horizon) of satellite */ public byte satellite_elevation[] = new byte[20]; /** * Direction of satellite, 0: 0 deg, 255: 360 deg. */ public byte satellite_azimuth[] = new byte[20]; /** * Signal to noise ratio of satellite */ public byte satellite_snr[] = new byte[20]; /** * Generates the payload for a mavlink message for a message of this type * @return */ public MAVLinkPacket pack(){ MAVLinkPacket packet = new MAVLinkPacket(); packet.len = MAVLINK_MSG_LENGTH; packet.sysid = 255; packet.compid = 190; packet.msgid = MAVLINK_MSG_ID_GPS_STATUS; packet.payload.putByte(satellites_visible); for (int i = 0; i < satellite_prn.length; i++) { packet.payload.putByte(satellite_prn[i]); } for (int i = 0; i < satellite_used.length; i++) { packet.payload.putByte(satellite_used[i]); } for (int i = 0; i < satellite_elevation.length; i++) { packet.payload.putByte(satellite_elevation[i]); } for (int i = 0; i < satellite_azimuth.length; i++) { packet.payload.putByte(satellite_azimuth[i]); } for (int i = 0; i < satellite_snr.length; i++) { packet.payload.putByte(satellite_snr[i]); } return packet; } /** * Decode a gps_status message into this class fields * * @param payload The message to decode */ public void unpack(MAVLinkPayload payload) { payload.resetIndex(); this.satellites_visible = payload.getByte(); for (int i = 0; i < this.satellite_prn.length; i++) { this.satellite_prn[i] = payload.getByte(); } for (int i = 0; i < this.satellite_used.length; i++) { this.satellite_used[i] = payload.getByte(); } for (int i = 0; i < this.satellite_elevation.length; i++) { this.satellite_elevation[i] = payload.getByte(); } for (int i = 0; i < this.satellite_azimuth.length; i++) { this.satellite_azimuth[i] = payload.getByte(); } for (int i = 0; i < this.satellite_snr.length; i++) { this.satellite_snr[i] = payload.getByte(); } } /** * Constructor for a new message, just initializes the msgid */ public msg_gps_status(){ msgid = MAVLINK_MSG_ID_GPS_STATUS; } /** * Constructor for a new message, initializes the message with the payload * from a mavlink packet * */ public msg_gps_status(MAVLinkPacket mavLinkPacket){ this.sysid = mavLinkPacket.sysid; this.compid = mavLinkPacket.compid; this.msgid = MAVLINK_MSG_ID_GPS_STATUS; unpack(mavLinkPacket.payload); //Log.d("MAVLink", "GPS_STATUS"); //Log.d("MAVLINK_MSG_ID_GPS_STATUS", toString()); } /** * Returns a string with the MSG name and data */ public String toString(){ return "MAVLINK_MSG_ID_GPS_STATUS -"+" satellites_visible:"+satellites_visible+" satellite_prn:"+satellite_prn+" satellite_used:"+satellite_used+" satellite_elevation:"+satellite_elevation+" satellite_azimuth:"+satellite_azimuth+" satellite_snr:"+satellite_snr+""; } }
gpl-3.0
jbval/core
core/ajax/object.ajax.php
5782
<?php /* This file is part of Jeedom. * * Jeedom 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. * * Jeedom 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 Jeedom. If not, see <http://www.gnu.org/licenses/>. */ try { require_once(dirname(__FILE__) . '/../../core/php/core.inc.php'); include_file('core', 'authentification', 'php'); if (!isConnect()) { throw new Exception(__('401 - Accès non autorisé', __FILE__)); } if (init('action') == 'remove') { if (!isConnect('admin')) { throw new Exception(__('401 - Accès non autorisé', __FILE__)); } $object = object::byId(init('id')); if (!is_object($object)) { throw new Exception(__('Objet inconnu verifié l\'id', __FILE__)); } $object->remove(); ajax::success(); } if (init('action') == 'byId') { $object = object::byId(init('id')); if (!is_object($object)) { throw new Exception(__('Objet inconnu verifié l\'id : ', __FILE__) . init('id')); } ajax::success(utils::o2a($object)); } if (init('action') == 'all') { ajax::success(utils::o2a(object::buildTree())); } if (init('action') == 'save') { if (!isConnect('admin')) { throw new Exception(__('401 - Accès non autorisé', __FILE__)); } $object_json = json_decode(init('object'), true); if (isset($object_json['id'])) { $object = object::byId($object_json['id']); } if (!isset($object) || !is_object($object)) { $object = new object(); } utils::a2o($object, $object_json); $object->save(); ajax::success(utils::o2a($object)); } if (init('action') == 'uploadImage') { $object = object::byId(init('id')); if (!is_object($object)) { throw new Exception(__('Objet inconnu verifié l\'id', __FILE__)); } if (!isset($_FILES['file'])) { throw new Exception(__('Aucun fichier trouvé. Vérifié parametre PHP (post size limit)', __FILE__)); } $extension = strtolower(strrchr($_FILES['file']['name'], '.')); if (!in_array($extension, array('.jpg', '.png'))) { throw new Exception('Extension du fichier non valide (autorisé .jpg .png) : ' . $extension); } if (filesize($_FILES['file']['tmp_name']) > 5000000) { throw new Exception(__('Le fichier est trop gros (miximum 5mo)', __FILE__)); } $object->setImage('type', str_replace('.', '', $extension)); $object->setImage('size', getimagesize($_FILES['file']['tmp_name'])); $object->setImage('data', base64_encode(file_get_contents($_FILES['file']['tmp_name']))); $object->save(); ajax::success(); } if (init('action') == 'getChild') { $object = object::byId(init('id')); if (!is_object($object)) { throw new Exception(__('Objet inconnu verifié l\'id', __FILE__)); } $return = utils::o2a($object->getChild()); ajax::success($return); } if (init('action') == 'toHtml') { if (init('id') == 'all' || is_json(init('id'))) { if (is_json(init('id'))) { $object_ajax = json_decode(init('id'), true); $objects = array(); foreach ($object_ajax as $id) { $objects[] = object::byId($id); } } else { $objects = object::all(); } $return = array(); foreach ($objects as $object) { if (is_object($object) && $object->getIsVisible() == 1) { $html = ''; foreach ($object->getEqLogic() as $eqLogic) { if ($eqLogic->getIsVisible() == '1') { $html .= $eqLogic->toHtml(init('version')); } } $return[$object->getId()] = $html; } } ajax::success($return); } else { $object = object::byId(init('id')); if (!is_object($object)) { throw new Exception(__('Objet inconnu verifié l\'id', __FILE__)); } $html = ''; foreach ($object->getEqLogic() as $eqLogic) { if ($eqLogic->getIsVisible() == '1') { $html .= $eqLogic->toHtml(init('version')); } } ajax::success($html); } } if (init('action') == 'setOrder') { if (!isConnect('admin')) { throw new Exception(__('401 - Accès non autorisé', __FILE__)); } $position = 1; foreach (json_decode(init('objects'), true) as $id) { $object = object::byId($id); if (is_object($object)) { $object->setPosition($position); $object->save(); $position++; } } ajax::success(); } throw new Exception(__('Aucune methode correspondante à : ', __FILE__) . init('action')); /* * *********Catch exeption*************** */ } catch (Exception $e) { ajax::error(displayExeption($e), $e->getCode()); } ?>
gpl-3.0
wiki2014/Learning-Summary
alps/cts/tests/tests/content/src/android/content/cts/MockReceiverFirst.java
1426
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content.cts; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; /** * This class is used for testing android.content.BroadcastReceiver. * * @see BroadcastReceiver */ public class MockReceiverFirst extends BroadcastReceiver { public static final int RESULT_CODE = 2; public static final String RESULT_DATA = "first"; public static final String RESULT_EXTRAS_FIRST_KEY = "first"; public static final String RESULT_EXTRAS_FIRST_VALUE = "first value"; public void onReceive(Context context, Intent intent) { Bundle map = getResultExtras(false); map.putString(RESULT_EXTRAS_FIRST_KEY, RESULT_EXTRAS_FIRST_VALUE); setResult(RESULT_CODE, RESULT_DATA, map); } }
gpl-3.0
daVoodooShuffle/OpenRA
OpenRA.Mods.Cnc/Traits/Infiltration/InfiltrateForSupportPower.cs
1186
#region Copyright & License Information /* * Copyright 2007-2017 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion using OpenRA.Mods.Common.Traits; using OpenRA.Primitives; using OpenRA.Traits; namespace OpenRA.Mods.Cnc.Traits { class InfiltrateForSupportPowerInfo : ITraitInfo { [ActorReference, FieldLoader.Require] public readonly string Proxy = null; public object Create(ActorInitializer init) { return new InfiltrateForSupportPower(this); } } class InfiltrateForSupportPower : INotifyInfiltrated { readonly InfiltrateForSupportPowerInfo info; public InfiltrateForSupportPower(InfiltrateForSupportPowerInfo info) { this.info = info; } void INotifyInfiltrated.Infiltrated(Actor self, Actor infiltrator) { infiltrator.World.AddFrameEndTask(w => w.CreateActor(info.Proxy, new TypeDictionary { new OwnerInit(infiltrator.Owner) })); } } }
gpl-3.0
Lutske/EMGU_CV
Emgu.RPC/RpcClient.cs
2097
//---------------------------------------------------------------------------- // Copyright (C) 2004-2015 by EMGU Corporation. All rights reserved. //---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using Emgu.RPC.Serial; using Emgu.RPC.Speech; using Emgu.CV; using Emgu.Util; using System.ServiceModel; namespace Emgu.RPC { public class RpcClient : DisposableObject { private Uri _baseUri; private System.ServiceModel.Channels.Binding _binding; private ISpeechService _speech; private CaptureClient _captureClient; private SerialClient _serialClient; public RpcClient(Uri baseUri, System.ServiceModel.Channels.Binding binding) { _baseUri = baseUri; _binding = binding; } public ISpeechService Speech { get { return _speech; } } public CaptureClient Capture { get { return _captureClient; } } public SerialClient Serial { get { return _serialClient; } } public void AddSpeechClient(String uri) { if (_speech == null) { _speech = new ChannelFactory<ISpeechService>( _binding, new EndpointAddress(_baseUri.ToString() + uri) ).CreateChannel(); } } public void AddCaptureClient(String uri) { if (_captureClient == null) { _captureClient = new CaptureClient(_binding, _baseUri.ToString() + uri); } } public void AddSerialClient(String uri) { if (_serialClient == null) { _serialClient = new SerialClient(_binding, _baseUri.ToString() + uri); } } protected override void DisposeObject() { if (_serialClient != null) _serialClient.Dispose(); if (_captureClient != null) _captureClient.Dispose(); } } }
gpl-3.0
ThePirateOld/vice-players
Client/d3dhook/d3d8hook.cpp
1889
//---------------------------------------------------------- // // VC:MP Multiplayer Modification For GTA:VC // Copyright 2004-2005 SA:MP team // // File Author(s): jenksta // License: See LICENSE in root directory // //---------------------------------------------------------- #include "StdInc.h" #include "../detours/detours.h" typedef IDirect3D8 * (WINAPI * Direct3DCreate8_t)(UINT SDKVersion); typedef HRESULT (WINAPI * DirectInput8Create_t)(HINSTANCE, DWORD, REFIID, LPVOID *, LPUNKNOWN); Direct3DCreate8_t m_pfnDirect3DCreate8 = NULL; DirectInput8Create_t m_pfnDirectInput8Create = NULL; IDirect3D8 * WINAPI Direct3DCreate8(UINT SDKVersion) { // Create our device IDirect3D8 * pDevice = m_pfnDirect3DCreate8(SDKVersion); // Create our device hook IDirect3D8Hook * pDeviceHook = new IDirect3D8Hook(pDevice); // Return the device hook pointer return pDeviceHook; } HRESULT WINAPI DirectInput8Create(HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID *ppvOut, LPUNKNOWN punkOuter) { HRESULT hr = m_pfnDirectInput8Create(hinst, dwVersion, riidltf, ppvOut, punkOuter); IDirectInput8 * pDInput = (IDirectInput8 *)*ppvOut; *ppvOut = new IDirectInput8Hook(pDInput); return hr; } void InstallD3D8Hook() { if(!m_pfnDirect3DCreate8) { m_pfnDirect3DCreate8 = (Direct3DCreate8_t)DetourFunction(DetourFindFunction("d3d8.dll", "Direct3DCreate8"), (PBYTE)Direct3DCreate8); } if(!m_pfnDirectInput8Create) { m_pfnDirectInput8Create = (DirectInput8Create_t)DetourFunction(DetourFindFunction("dinput8.dll", "DirectInput8Create"), (PBYTE)DirectInput8Create); } } void UninstallD3D8Hook() { if(m_pfnDirect3DCreate8) { DetourRemove((PBYTE)m_pfnDirect3DCreate8, (PBYTE)Direct3DCreate8); } if(m_pfnDirectInput8Create) { DetourRemove((PBYTE)m_pfnDirectInput8Create, (PBYTE)DirectInput8Create); } }
gpl-3.0
fagensden/FagensDen
GitUI/CommandsDialogs/SettingsDialog/Pages/CommitDialogSettingsPage.Designer.cs
13556
namespace GitUI.CommandsDialogs.SettingsDialog.Pages { partial class CommitDialogSettingsPage { /// <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 Component 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.groupBoxBehaviour = new System.Windows.Forms.GroupBox(); this.tableLayoutPanelBehaviour = new System.Windows.Forms.TableLayoutPanel(); this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages = new System.Windows.Forms.NumericUpDown(); this.lblCommitDialogNumberOfPreviousMessages = new System.Windows.Forms.Label(); this.chkShowErrorsWhenStagingFiles = new System.Windows.Forms.CheckBox(); this.chkWriteCommitMessageInCommitWindow = new System.Windows.Forms.CheckBox(); this.grpAdditionalButtons = new System.Windows.Forms.GroupBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.chkShowCommitAndPush = new System.Windows.Forms.CheckBox(); this.chkShowResetUnstagedChanges = new System.Windows.Forms.CheckBox(); this.chkShowResetAllChanges = new System.Windows.Forms.CheckBox(); this.groupBoxBehaviour.SuspendLayout(); this.tableLayoutPanelBehaviour.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages)).BeginInit(); this.grpAdditionalButtons.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // groupBoxBehaviour // this.groupBoxBehaviour.AutoSize = true; this.groupBoxBehaviour.Controls.Add(this.tableLayoutPanelBehaviour); this.groupBoxBehaviour.Dock = System.Windows.Forms.DockStyle.Top; this.groupBoxBehaviour.Location = new System.Drawing.Point(0, 0); this.groupBoxBehaviour.Name = "groupBoxBehaviour"; this.groupBoxBehaviour.Size = new System.Drawing.Size(1146, 201); this.groupBoxBehaviour.TabIndex = 56; this.groupBoxBehaviour.TabStop = false; this.groupBoxBehaviour.Text = "Behaviour"; // // tableLayoutPanelBehaviour // this.tableLayoutPanelBehaviour.AutoSize = true; this.tableLayoutPanelBehaviour.ColumnCount = 2; this.tableLayoutPanelBehaviour.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanelBehaviour.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanelBehaviour.Controls.Add(this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages, 1, 2); this.tableLayoutPanelBehaviour.Controls.Add(this.lblCommitDialogNumberOfPreviousMessages, 0, 2); this.tableLayoutPanelBehaviour.Controls.Add(this.chkShowErrorsWhenStagingFiles, 0, 0); this.tableLayoutPanelBehaviour.Controls.Add(this.chkWriteCommitMessageInCommitWindow, 0, 1); this.tableLayoutPanelBehaviour.Controls.Add(this.grpAdditionalButtons, 0, 4); this.tableLayoutPanelBehaviour.Dock = System.Windows.Forms.DockStyle.Top; this.tableLayoutPanelBehaviour.Location = new System.Drawing.Point(3, 17); this.tableLayoutPanelBehaviour.Name = "tableLayoutPanelBehaviour"; this.tableLayoutPanelBehaviour.RowCount = 5; this.tableLayoutPanelBehaviour.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanelBehaviour.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanelBehaviour.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanelBehaviour.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanelBehaviour.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanelBehaviour.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanelBehaviour.Size = new System.Drawing.Size(1140, 181); this.tableLayoutPanelBehaviour.TabIndex = 57; // // _NO_TRANSLATE_CommitDialogNumberOfPreviousMessages // this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages.Location = new System.Drawing.Point(307, 62); this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages.Maximum = new decimal(new int[] { 10, 0, 0, 0}); this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages.Name = "_NO_TRANSLATE_CommitDialogNumberOfPreviousMessages"; this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages.Size = new System.Drawing.Size(123, 21); this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages.TabIndex = 3; this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages.Value = new decimal(new int[] { 1, 0, 0, 0}); // // lblCommitDialogNumberOfPreviousMessages // this.lblCommitDialogNumberOfPreviousMessages.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblCommitDialogNumberOfPreviousMessages.AutoSize = true; this.lblCommitDialogNumberOfPreviousMessages.Location = new System.Drawing.Point(3, 66); this.lblCommitDialogNumberOfPreviousMessages.Name = "lblCommitDialogNumberOfPreviousMessages"; this.lblCommitDialogNumberOfPreviousMessages.Size = new System.Drawing.Size(229, 13); this.lblCommitDialogNumberOfPreviousMessages.TabIndex = 2; this.lblCommitDialogNumberOfPreviousMessages.Text = "Number of previous messages in commit dialog"; // // chkShowErrorsWhenStagingFiles // this.chkShowErrorsWhenStagingFiles.AutoSize = true; this.chkShowErrorsWhenStagingFiles.Location = new System.Drawing.Point(3, 3); this.chkShowErrorsWhenStagingFiles.Name = "chkShowErrorsWhenStagingFiles"; this.chkShowErrorsWhenStagingFiles.Size = new System.Drawing.Size(173, 17); this.chkShowErrorsWhenStagingFiles.TabIndex = 0; this.chkShowErrorsWhenStagingFiles.Text = "Show errors when staging files"; this.chkShowErrorsWhenStagingFiles.UseVisualStyleBackColor = true; // // chkWriteCommitMessageInCommitWindow // this.chkWriteCommitMessageInCommitWindow.AutoSize = true; this.chkWriteCommitMessageInCommitWindow.Location = new System.Drawing.Point(3, 26); this.chkWriteCommitMessageInCommitWindow.Name = "chkWriteCommitMessageInCommitWindow"; this.chkWriteCommitMessageInCommitWindow.Size = new System.Drawing.Size(298, 30); this.chkWriteCommitMessageInCommitWindow.TabIndex = 1; this.chkWriteCommitMessageInCommitWindow.Text = "Compose commit messages in Commit dialog\r\n(otherwise the message will be requeste" + "d during commit)"; this.chkWriteCommitMessageInCommitWindow.UseVisualStyleBackColor = true; // // grpAdditionalButtons // this.grpAdditionalButtons.AutoSize = true; this.grpAdditionalButtons.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanelBehaviour.SetColumnSpan(this.grpAdditionalButtons, 2); this.grpAdditionalButtons.Controls.Add(this.flowLayoutPanel1); this.grpAdditionalButtons.Dock = System.Windows.Forms.DockStyle.Fill; this.grpAdditionalButtons.Location = new System.Drawing.Point(3, 89); this.grpAdditionalButtons.Name = "grpAdditionalButtons"; this.grpAdditionalButtons.Size = new System.Drawing.Size(1134, 89); this.grpAdditionalButtons.TabIndex = 5; this.grpAdditionalButtons.TabStop = false; this.grpAdditionalButtons.Text = "Show additional buttons in commit button area"; // // flowLayoutPanel1 // this.flowLayoutPanel1.AutoSize = true; this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.flowLayoutPanel1.Controls.Add(this.chkShowCommitAndPush); this.flowLayoutPanel1.Controls.Add(this.chkShowResetUnstagedChanges); this.flowLayoutPanel1.Controls.Add(this.chkShowResetAllChanges); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 17); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(1128, 69); this.flowLayoutPanel1.TabIndex = 0; // // chkShowCommitAndPush // this.chkShowCommitAndPush.AutoSize = true; this.chkShowCommitAndPush.Location = new System.Drawing.Point(3, 3); this.chkShowCommitAndPush.Name = "chkShowCommitAndPush"; this.chkShowCommitAndPush.Size = new System.Drawing.Size(97, 17); this.chkShowCommitAndPush.TabIndex = 0; this.chkShowCommitAndPush.Text = "Commit && Push"; this.chkShowCommitAndPush.UseVisualStyleBackColor = true; // // chkShowResetUnstagedChanges // this.chkShowResetUnstagedChanges.AutoSize = true; this.chkShowResetUnstagedChanges.Location = new System.Drawing.Point(3, 26); this.chkShowResetUnstagedChanges.Name = "chkShowResetUnstagedChanges"; this.chkShowResetUnstagedChanges.Size = new System.Drawing.Size(148, 17); this.chkShowResetUnstagedChanges.TabIndex = 1; this.chkShowResetUnstagedChanges.Text = "Reset Unstaged Changes"; this.chkShowResetUnstagedChanges.UseVisualStyleBackColor = true; // // chkShowResetAllChanges // this.chkShowResetAllChanges.AutoSize = true; this.chkShowResetAllChanges.Location = new System.Drawing.Point(3, 49); this.chkShowResetAllChanges.Name = "chkShowResetAllChanges"; this.chkShowResetAllChanges.Size = new System.Drawing.Size(113, 17); this.chkShowResetAllChanges.TabIndex = 2; this.chkShowResetAllChanges.Text = "Reset All Changes"; this.chkShowResetAllChanges.UseVisualStyleBackColor = true; // // CommitDialogSettingsPage // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoScroll = true; this.Controls.Add(this.groupBoxBehaviour); this.Name = "CommitDialogSettingsPage"; this.Size = new System.Drawing.Size(1146, 421); this.groupBoxBehaviour.ResumeLayout(false); this.groupBoxBehaviour.PerformLayout(); this.tableLayoutPanelBehaviour.ResumeLayout(false); this.tableLayoutPanelBehaviour.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this._NO_TRANSLATE_CommitDialogNumberOfPreviousMessages)).EndInit(); this.grpAdditionalButtons.ResumeLayout(false); this.grpAdditionalButtons.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBoxBehaviour; private System.Windows.Forms.CheckBox chkWriteCommitMessageInCommitWindow; private System.Windows.Forms.CheckBox chkShowErrorsWhenStagingFiles; private System.Windows.Forms.Label lblCommitDialogNumberOfPreviousMessages; private System.Windows.Forms.NumericUpDown _NO_TRANSLATE_CommitDialogNumberOfPreviousMessages; private System.Windows.Forms.TableLayoutPanel tableLayoutPanelBehaviour; private System.Windows.Forms.GroupBox grpAdditionalButtons; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.CheckBox chkShowCommitAndPush; private System.Windows.Forms.CheckBox chkShowResetUnstagedChanges; private System.Windows.Forms.CheckBox chkShowResetAllChanges; } }
gpl-3.0
Evilazaro/MCSDAzureTraining
Design and Implement Cloud Services/HOLs/HOL-DeployingCloudServices-VS2012/Source/Ex4-SecuringAppWithSSL/End/MyTodo.WebUx/Models/Feed.cs
1449
// ---------------------------------------------------------------------------------- // Microsoft Developer & Platform Evangelism // // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // ---------------------------------------------------------------------------------- // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. // ---------------------------------------------------------------------------------- namespace MyTodo.WebUx.Models { using System; using System.Collections.Generic; using System.Collections.ObjectModel; public class Feed { public Feed(IList<FeedItem> items) { this.Items = new Collection<FeedItem>(items); } public string Title { get; set; } public string Description { get; set; } public Uri Url { get; set; } public string Language { get; set; } public ICollection<FeedItem> Items { get; private set; } } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace-archive/ValueObjects/src/ims/pathways/vo/PathwayRTTStatusRefVoCollection.java
5324
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.pathways.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to Pathways.PathwayRTTStatus business object (ID: 1088100010). */ public class PathwayRTTStatusRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<PathwayRTTStatusRefVo> { private static final long serialVersionUID = 1L; private ArrayList<PathwayRTTStatusRefVo> col = new ArrayList<PathwayRTTStatusRefVo>(); public final String getBoClassName() { return "ims.pathways.domain.objects.PathwayRTTStatus"; } public ims.domain.IDomainGetter[] getIDomainGetterItems() { ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()]; col.toArray(result); return result; } public boolean add(PathwayRTTStatusRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, PathwayRTTStatusRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(PathwayRTTStatusRefVo instance) { return col.indexOf(instance); } public PathwayRTTStatusRefVo get(int index) { return this.col.get(index); } public boolean set(int index, PathwayRTTStatusRefVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(PathwayRTTStatusRefVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(PathwayRTTStatusRefVo instance) { return indexOf(instance) >= 0; } public Object clone() { PathwayRTTStatusRefVoCollection clone = new PathwayRTTStatusRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((PathwayRTTStatusRefVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { return true; } public String[] validate() { return null; } public PathwayRTTStatusRefVo[] toArray() { PathwayRTTStatusRefVo[] arr = new PathwayRTTStatusRefVo[col.size()]; col.toArray(arr); return arr; } public PathwayRTTStatusRefVoCollection sort() { return sort(SortOrder.ASCENDING); } public PathwayRTTStatusRefVoCollection sort(SortOrder order) { return sort(new PathwayRTTStatusRefVoComparator(order)); } @SuppressWarnings("unchecked") public PathwayRTTStatusRefVoCollection sort(Comparator comparator) { Collections.sort(this.col, comparator); return this; } public Iterator<PathwayRTTStatusRefVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class PathwayRTTStatusRefVoComparator implements Comparator { private int direction = 1; public PathwayRTTStatusRefVoComparator() { this(SortOrder.ASCENDING); } public PathwayRTTStatusRefVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { this.direction = -1; } } public int compare(Object obj1, Object obj2) { PathwayRTTStatusRefVo voObj1 = (PathwayRTTStatusRefVo)obj1; PathwayRTTStatusRefVo voObj2 = (PathwayRTTStatusRefVo)obj2; return direction*(voObj1.compareTo(voObj2)); } } }
agpl-3.0
dunglas/piy
lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/test/unit/sfDoctrineColumnTest.php
2623
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ include(dirname(__FILE__).'/../bootstrap/unit.php'); $t = new lime_test(23, new lime_output_color()); $conn = Doctrine_Manager::connection(new Doctrine_Adapter_Mock('mysql')); class Test extends sfDoctrineRecord { public function setTableDefinition() { $this->hasColumn('name', 'string', 255, array('notblank' => true)); $this->hasColumn('test as TEST', 'string', 255); $this->hasColumn('email', 'string', 255, array('email' => true, 'notnull' => true)); } public function setUp() { $this->hasMany('TestRelation as TestRelations', array('local' => 'id', 'foreign' => 'test_id')); } } class TestRelation extends sfDoctrineRecord { public function setTableDefinition() { $this->hasColumn('name', 'string', 255); $this->hasColumn('test_id', 'integer'); } public function setUp() { $this->hasOne('Test', array('local' => 'test_id', 'foreign' => 'id')); } } $column = new sfDoctrineColumn('name', Doctrine::getTable('Test')); $t->is($column->getName(), 'name'); $t->is($column->getFieldName(), 'name'); $t->is($column->getPhpName(), 'name'); $t->is($column->isNotNull(), true); $column = new sfDoctrineColumn('test', Doctrine::getTable('Test')); $t->is($column->getName(), 'test'); $t->is($column->getFieldName(), 'TEST'); $t->is($column->getPhpName(), 'TEST'); $t->is($column->getDoctrineType(), 'string'); $t->is($column->getType(), 'VARCHAR'); $t->is($column->getLength(), 255); $t->is($column->getSize(), 255); $t->is($column->hasDefinitionKey('length'), true); $t->is($column->getDefinitionKey('type'), 'string'); $t->is($column->isNotNull(), false); // Is not null and has definition key $column = new sfDoctrineColumn('email', Doctrine::getTable('Test')); $t->is($column->isNotNull(), true); $t->is($column->hasDefinitionKey('email'), true); $t->is($column->getDefinitionKey('email'), true); // Is primary key $column = new sfDoctrineColumn('id', Doctrine::getTable('Test')); $t->is($column->isPrimaryKey(), true); // Relation/foreign key functions $column = new sfDoctrineColumn('test_id', Doctrine::getTable('TestRelation')); $t->is($column->isForeignKey(), true); $t->is($column->getForeignClassName(), 'Test'); $t->is($column->getForeignTable()->getOption('name'), 'Test'); $t->is($column->getTable()->getOption('name'), 'TestRelation'); // Array access $t->is($column['type'], 'integer');
agpl-3.0
gangadhar-kadam/mtn-erpnext
patches/may_2012/customize_form_cleanup.py
215
from __future__ import unicode_literals def execute(): import webnotes webnotes.conn.sql("delete from `tabCustomize Form Field`") webnotes.conn.sql("""delete from `tabSingles` where doctype='Customize Form'""")
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace-archive/Clinical/src/ims/clinical/forms/clinicalnotehistorydialog/GlobalContext.java
2776
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.forms.clinicalnotehistorydialog; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); Clinical = new ClinicalContext(context); } public final class ClinicalContext implements Serializable { private static final long serialVersionUID = 1L; private ClinicalContext(ims.framework.Context context) { this.context = context; } public boolean getCurrentClinicalNoteIsNotNull() { return !cx_ClinicalCurrentClinicalNote.getValueIsNull(context); } public ims.core.vo.ClinicalNotesVo getCurrentClinicalNote() { return (ims.core.vo.ClinicalNotesVo)cx_ClinicalCurrentClinicalNote.getValue(context); } private ims.framework.ContextVariable cx_ClinicalCurrentClinicalNote = new ims.framework.ContextVariable("Clinical.CurrentClinicalNote", "_cvp_Clinical.CurrentClinicalNote"); private ims.framework.Context context; } public ClinicalContext Clinical; }
agpl-3.0
geoiq/digitalgazette
app/models/associations/enmity.rb
246
# # A type of user <> user association. # # It indicates that user does not want anything to do with contact # # Currently unused, but this would be useful if you want to hide the # posts from an annoying user. # class Enmity < Relationship end
agpl-3.0
rossjones/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/domain/PathSpecimenContainerListVoAssembler.java
16763
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.ocrr.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Alexie Ursache */ public class PathSpecimenContainerListVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.ocrr.vo.PathSpecimenContainerListVo copy(ims.ocrr.vo.PathSpecimenContainerListVo valueObjectDest, ims.ocrr.vo.PathSpecimenContainerListVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_PathSpecimenContainer(valueObjectSrc.getID_PathSpecimenContainer()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // Name valueObjectDest.setName(valueObjectSrc.getName()); // Volume valueObjectDest.setVolume(valueObjectSrc.getVolume()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createPathSpecimenContainerListVoCollectionFromPathSpecimenContainer(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.ocrr.configuration.domain.objects.PathSpecimenContainer objects. */ public static ims.ocrr.vo.PathSpecimenContainerListVoCollection createPathSpecimenContainerListVoCollectionFromPathSpecimenContainer(java.util.Set domainObjectSet) { return createPathSpecimenContainerListVoCollectionFromPathSpecimenContainer(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.ocrr.configuration.domain.objects.PathSpecimenContainer objects. */ public static ims.ocrr.vo.PathSpecimenContainerListVoCollection createPathSpecimenContainerListVoCollectionFromPathSpecimenContainer(DomainObjectMap map, java.util.Set domainObjectSet) { ims.ocrr.vo.PathSpecimenContainerListVoCollection voList = new ims.ocrr.vo.PathSpecimenContainerListVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject = (ims.ocrr.configuration.domain.objects.PathSpecimenContainer) iterator.next(); ims.ocrr.vo.PathSpecimenContainerListVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.ocrr.configuration.domain.objects.PathSpecimenContainer objects. */ public static ims.ocrr.vo.PathSpecimenContainerListVoCollection createPathSpecimenContainerListVoCollectionFromPathSpecimenContainer(java.util.List domainObjectList) { return createPathSpecimenContainerListVoCollectionFromPathSpecimenContainer(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.ocrr.configuration.domain.objects.PathSpecimenContainer objects. */ public static ims.ocrr.vo.PathSpecimenContainerListVoCollection createPathSpecimenContainerListVoCollectionFromPathSpecimenContainer(DomainObjectMap map, java.util.List domainObjectList) { ims.ocrr.vo.PathSpecimenContainerListVoCollection voList = new ims.ocrr.vo.PathSpecimenContainerListVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject = (ims.ocrr.configuration.domain.objects.PathSpecimenContainer) domainObjectList.get(i); ims.ocrr.vo.PathSpecimenContainerListVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.ocrr.configuration.domain.objects.PathSpecimenContainer set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractPathSpecimenContainerSet(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.PathSpecimenContainerListVoCollection voCollection) { return extractPathSpecimenContainerSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractPathSpecimenContainerSet(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.PathSpecimenContainerListVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.ocrr.vo.PathSpecimenContainerListVo vo = voCollection.get(i); ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject = PathSpecimenContainerListVoAssembler.extractPathSpecimenContainer(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.ocrr.configuration.domain.objects.PathSpecimenContainer list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractPathSpecimenContainerList(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.PathSpecimenContainerListVoCollection voCollection) { return extractPathSpecimenContainerList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractPathSpecimenContainerList(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.PathSpecimenContainerListVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.ocrr.vo.PathSpecimenContainerListVo vo = voCollection.get(i); ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject = PathSpecimenContainerListVoAssembler.extractPathSpecimenContainer(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.ocrr.configuration.domain.objects.PathSpecimenContainer object. * @param domainObject ims.ocrr.configuration.domain.objects.PathSpecimenContainer */ public static ims.ocrr.vo.PathSpecimenContainerListVo create(ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.ocrr.configuration.domain.objects.PathSpecimenContainer object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.ocrr.vo.PathSpecimenContainerListVo create(DomainObjectMap map, ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.ocrr.vo.PathSpecimenContainerListVo valueObject = (ims.ocrr.vo.PathSpecimenContainerListVo) map.getValueObject(domainObject, ims.ocrr.vo.PathSpecimenContainerListVo.class); if ( null == valueObject ) { valueObject = new ims.ocrr.vo.PathSpecimenContainerListVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.ocrr.configuration.domain.objects.PathSpecimenContainer */ public static ims.ocrr.vo.PathSpecimenContainerListVo insert(ims.ocrr.vo.PathSpecimenContainerListVo valueObject, ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.ocrr.configuration.domain.objects.PathSpecimenContainer */ public static ims.ocrr.vo.PathSpecimenContainerListVo insert(DomainObjectMap map, ims.ocrr.vo.PathSpecimenContainerListVo valueObject, ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_PathSpecimenContainer(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // Name valueObject.setName(domainObject.getName()); // Volume valueObject.setVolume(domainObject.getVolume()); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.ocrr.configuration.domain.objects.PathSpecimenContainer extractPathSpecimenContainer(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.PathSpecimenContainerListVo valueObject) { return extractPathSpecimenContainer(domainFactory, valueObject, new HashMap()); } public static ims.ocrr.configuration.domain.objects.PathSpecimenContainer extractPathSpecimenContainer(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.PathSpecimenContainerListVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_PathSpecimenContainer(); ims.ocrr.configuration.domain.objects.PathSpecimenContainer domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.ocrr.configuration.domain.objects.PathSpecimenContainer)domMap.get(valueObject); } // ims.ocrr.vo.PathSpecimenContainerListVo ID_PathSpecimenContainer field is unknown domainObject = new ims.ocrr.configuration.domain.objects.PathSpecimenContainer(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_PathSpecimenContainer()); if (domMap.get(key) != null) { return (ims.ocrr.configuration.domain.objects.PathSpecimenContainer)domMap.get(key); } domainObject = (ims.ocrr.configuration.domain.objects.PathSpecimenContainer) domainFactory.getDomainObject(ims.ocrr.configuration.domain.objects.PathSpecimenContainer.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_PathSpecimenContainer()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getName() != null && valueObject.getName().equals("")) { valueObject.setName(null); } domainObject.setName(valueObject.getName()); domainObject.setVolume(valueObject.getVolume()); return domainObject; } }
agpl-3.0
MyCollab/mycollab
mycollab-core/src/main/java/com/hp/gagawa/java/elements/Tbody.java
5387
/**Generated by the Gagawa TagBuilder Fri Jan 30 21:29:45 PST 2009*/ /** (c) Copyright 2008 Hewlett-Packard Development Company, L.P. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.hp.gagawa.java.elements; import com.hp.gagawa.java.FertileNode; import com.hp.gagawa.java.Node; import com.hp.gagawa.java.elements.Text; import java.util.List; public class Tbody extends FertileNode { public Tbody(){ super("tbody"); } /** * Appends a child node to the end of this element's DOM tree * @param child node to be appended * @return the node */ public Tbody appendChild(Node child){ if(this == child){ throw new Error("Cannot append a node to itself."); } child.setParent(this); children.add(child); return this; } /** * Appends a child node at the given index * @param index insert point * @param child node to be appended * @return the node */ public Tbody appendChild(int index, Node child){ if(this == child){ throw new Error("Cannot append a node to itself."); } child.setParent(this); children.add(index, child); return this; } /** * Appends a list of children in the order given in the list * @param children nodes to be appended * @return the node */ public Tbody appendChild(List<Node> children){ if(children != null){ for(Node child: children){ appendChild(child); } } return this; } /** * Appends the given children in the order given * @param children nodes to be appended * @return the node */ public Tbody appendChild(Node... children){ for(int i = 0; i < children.length; i++){ appendChild(children[i]); } return this; } /** * Convenience method which appends a text node to this element * @param text the text to be appended * @return the node */ public Tbody appendText(String text){ return appendChild(new Text(text)); } /** * Removes the child node * @param child node to be removed * @return the node */ public Tbody removeChild(Node child){ children.remove(child); return this; } /** * Removes all child nodes * @return the node */ public Tbody removeChildren(){ children.clear(); return this; } public Tbody setAlign(String value){setAttribute("align", value); return this;} public String getAlign(){return getAttribute("align");} public boolean removeAlign(){return removeAttribute("align");} public Tbody setChar(String value){setAttribute("char", value); return this;} public String getChar(){return getAttribute("char");} public boolean removeChar(){return removeAttribute("char");} public Tbody setCharoff(String value){setAttribute("charoff", value); return this;} public String getCharoff(){return getAttribute("charoff");} public boolean removeCharoff(){return removeAttribute("charoff");} public Tbody setValign(String value){setAttribute("valign", value); return this;} public String getValign(){return getAttribute("valign");} public boolean removeValign(){return removeAttribute("valign");} public Tbody setId(String value){setAttribute("id", value); return this;} public String getId(){return getAttribute("id");} public boolean removeId(){return removeAttribute("id");} public Tbody setCSSClass(String value){setAttribute("class", value); return this;} public String getCSSClass(){return getAttribute("class");} public boolean removeCSSClass(){return removeAttribute("class");} public Tbody setTitle(String value){setAttribute("title", value); return this;} public String getTitle(){return getAttribute("title");} public boolean removeTitle(){return removeAttribute("title");} public Tbody setStyle(String value){setAttribute("style", value); return this;} public String getStyle(){return getAttribute("style");} public boolean removeStyle(){return removeAttribute("style");} public Tbody setDir(String value){setAttribute("dir", value); return this;} public String getDir(){return getAttribute("dir");} public boolean removeDir(){return removeAttribute("dir");} public Tbody setLang(String value){setAttribute("lang", value); return this;} public String getLang(){return getAttribute("lang");} public boolean removeLang(){return removeAttribute("lang");} public Tbody setXMLLang(String value){setAttribute("xml:lang", value); return this;} public String getXMLLang(){return getAttribute("xml:lang");} public boolean removeXMLLang(){return removeAttribute("xml:lang");} }
agpl-3.0
firstmoversadvantage/sugarcrm
include/SugarObjects/SugarRegistry.php
2946
<?php if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address 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". ********************************************************************************/ class SugarRegistry { private static $_instances = array(); private $_data = array(); public function __construct() { } public static function getInstance($name = 'default') { if (!isset(self::$_instances[$name])) { self::$_instances[$name] = new self(); } return self::$_instances[$name]; } public function __get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : null; } public function __set($key, $value) { $this->_data[$key] = $value; } public function __isset($key) { return isset($this->_data[$key]); } public function __unset($key) { unset($this->_data[$key]); } public function addToGlobals() { foreach ($this->_data as $k => $v) { $GLOBALS[$k] = $v; } } }
agpl-3.0
akvo/akvo-sites-zz-template
code/wp-content/plugins/the-events-calendar/common/src/Tribe/Models/Post_Types/Base.php
5454
<?php /** * The base, abstract, class modeling a post. * * @since 4.9.18 * * @package Tribe\Models\Post_Types */ namespace Tribe\Models\Post_Types; use Tribe__Cache as Cache; use Tribe__Cache_Listener as Cache_Listener; /** * Class Base * * @since 4.9.18 * * @package Tribe\Models\Post_Types */ abstract class Base { /** * The post object base for this post type instance. * * @since 4.9.18 * * @var \WP_Post */ protected $post; /** * Builds, and returns, a post type model from a given post. * * @since 4.9.18 * * @param \WP_Post|int $post The post ID or post object. * * @return Base|Nothing Either the built Post Type model, or a Nothing model if the post does not exist. */ public static function from_post( $post ) { $post = get_post( $post ); if ( ! $post instanceof \WP_Post ) { return new Nothing(); } $instance = new static; $instance->post = $post; return $instance; } /** * Returns the slug that will be prefixed to the cache key for the model. * * @since 4.9.18 * * @return string The slug that will be prefixed to the cache key for the model. */ abstract protected function get_cache_slug(); /** * Returns the cached model properties for the specified filter, if any. * * @since 4.9.18 * * @param string $filter Type of filter to apply, used here as the stored post values might change. * * @return array|false An array of model properties, or `false` if not found. */ protected function get_cached_properties( $filter ) { $cache_slug = $this->get_cache_slug(); if ( empty( $cache_slug ) ) { return false; } // Cache by post ID and filter. $cache_key = $cache_slug . '_' . $this->post->ID . '_' . $filter; return ( new Cache() )->get( $cache_key, Cache_Listener::TRIGGER_SAVE_POST ); } /** * Builds and returns the properties for the model. * * In this method child classes should also implement any caching trigger mechanism, if any. * * @since 4.9.18 * * @param string $filter The type of filter to build the properties for. * * @return array An array of built properties. */ abstract protected function build_properties( $filter ); /** * Returns an array of the model properties. * * @since 4.9.18 * * @param string $filter The type of filter to get the properties for. * * @return array The model properties. This value might be cached. */ protected function get_properties( $filter ) { $cached = $this->get_cached_properties( $filter); if ( false !== $cached ) { return $cached; } $props = $this->build_properties( $filter ); $cache_slug = $this->get_cache_slug(); /** * Filters the array of properties that will be used to decorate the post object handled by the class. * * @since 4.9.18 * * @param array $props An associative array of all the properties that will be set on the "decorated" post * object. * @param \WP_Post $post The post object handled by the class. */ $props = apply_filters( "tribe_post_type_{$cache_slug}_properties", $props, $this->post ); return $props; } /** * Returns the WP_Post version of this model. * * @since 4.9.18 * * @param string $output The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Post * object,an associative array, or a numeric array, respectively. * @param string $filter Type of filter to apply. Accepts 'raw', 'edit', 'db', or 'display' and other formats * supported by the specific type implementation. * * @return \WP_Post|array|null The post object version of this post type model or `null` if the post is not valid. */ public function to_post( $output = OBJECT, $filter = 'raw' ) { $properties = $this->get_properties( $filter ); // Clone the post to avoid side effects. $post = clone $this->post; // And decorate the clone with the properties. foreach ( $properties as $key => $value ) { $post->{$key} = $value; } switch ( $output ) { case ARRAY_A: return (array) $post; case ARRAY_N: return array_values( (array) $post ); case OBJECT: default; return $post; } } /** * Returns the closure that should be used to cache the post type model when, and if, caching it is required. * * @since 4.9.18 * * @param string $filter The kind of filter applied to the model. * * @return callable The closure, or callable, that should be used to cache this model when, and if, required. */ protected function get_caching_callback( $filter ) { $cache_slug = $this->get_cache_slug(); if ( empty( $cache_slug ) ) { return '__return_true'; } $callback = null; if ( wp_using_ext_object_cache() ) { /* * If any real caching is in place , then define a function to cache this event when, and if, one of the * lazy properties is loaded. * Cache by post ID and filter. */ $cache_key = $cache_slug . '_' . $this->post->ID . '_' . $filter; $cache = new Cache(); $callback = function () use ( $cache, $cache_key, $filter ) { $properties = $this->get_properties( $filter ); /* * Cache without expiration, but only until a post of the types managed by The Events Calendar is * updated or created. */ $cache->set( $cache_key, $properties, 0, Cache_Listener::TRIGGER_SAVE_POST ); }; } return $callback; } }
agpl-3.0
rossjones/openMAXIMS
Source Library/openmaxims_workspace/ICP/src/ims/icp/forms/icpconfig/GlobalContext.java
6780
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.icp.forms.icpconfig; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); ICP = new ICPContext(context); Rules = new RulesContext(context); } public final class ICPContext implements Serializable { private static final long serialVersionUID = 1L; private ICPContext(ims.framework.Context context) { this.context = context; RulesEditorDialog = new RulesEditorDialogContext(context); } public final class RulesEditorDialogContext implements Serializable { private static final long serialVersionUID = 1L; private RulesEditorDialogContext(ims.framework.Context context) { this.context = context; } public boolean getRuleIsNotNull() { return !cx_ICPRulesEditorDialogRule.getValueIsNull(context); } public ims.admin.vo.BusinessRuleVo getRule() { return (ims.admin.vo.BusinessRuleVo)cx_ICPRulesEditorDialogRule.getValue(context); } public void setRule(ims.admin.vo.BusinessRuleVo value) { cx_ICPRulesEditorDialogRule.setValue(context, value); } private ims.framework.ContextVariable cx_ICPRulesEditorDialogRule = new ims.framework.ContextVariable("ICP.RulesEditorDialog.Rule", "_cv_ICP.RulesEditorDialog.Rule"); private ims.framework.Context context; } public boolean getIcpPhaseGoalIsNotNull() { return !cx_ICPIcpPhaseGoal.getValueIsNull(context); } public ims.icp.vo.IcpPhaseGoalVo getIcpPhaseGoal() { return (ims.icp.vo.IcpPhaseGoalVo)cx_ICPIcpPhaseGoal.getValue(context); } public void setIcpPhaseGoal(ims.icp.vo.IcpPhaseGoalVo value) { cx_ICPIcpPhaseGoal.setValue(context, value); } private ims.framework.ContextVariable cx_ICPIcpPhaseGoal = new ims.framework.ContextVariable("ICP.IcpPhaseGoal", "_cv_ICP.IcpPhaseGoal"); public boolean getLinkedItemIsNotNull() { return !cx_ICPLinkedItem.getValueIsNull(context); } public ims.vo.interfaces.IActionICPLinkedItem getLinkedItem() { return (ims.vo.interfaces.IActionICPLinkedItem)cx_ICPLinkedItem.getValue(context); } public void setLinkedItem(ims.vo.interfaces.IActionICPLinkedItem value) { cx_ICPLinkedItem.setValue(context, value); } private ims.framework.ContextVariable cx_ICPLinkedItem = new ims.framework.ContextVariable("ICP.LinkedItem", "_cv_ICP.LinkedItem"); public boolean getLinkedActionsIsNotNull() { return !cx_ICPLinkedActions.getValueIsNull(context); } public ims.icps.configuration.vo.ICPActionRefVoCollection getLinkedActions() { return (ims.icps.configuration.vo.ICPActionRefVoCollection)cx_ICPLinkedActions.getValue(context); } public void setLinkedActions(ims.icps.configuration.vo.ICPActionRefVoCollection value) { cx_ICPLinkedActions.setValue(context, value); } private ims.framework.ContextVariable cx_ICPLinkedActions = new ims.framework.ContextVariable("ICP.LinkedActions", "_cv_ICP.LinkedActions"); public boolean getStageForCloningIsNotNull() { return !cx_ICPStageForCloning.getValueIsNull(context); } public ims.icps.configuration.vo.ICPStageRefVo getStageForCloning() { return (ims.icps.configuration.vo.ICPStageRefVo)cx_ICPStageForCloning.getValue(context); } public void setStageForCloning(ims.icps.configuration.vo.ICPStageRefVo value) { cx_ICPStageForCloning.setValue(context, value); } private ims.framework.ContextVariable cx_ICPStageForCloning = new ims.framework.ContextVariable("ICP.StageForCloning", "_cv_ICP.StageForCloning"); public boolean getPhaseForCloningIsNotNull() { return !cx_ICPPhaseForCloning.getValueIsNull(context); } public ims.icps.configuration.vo.ICPPhaseRefVo getPhaseForCloning() { return (ims.icps.configuration.vo.ICPPhaseRefVo)cx_ICPPhaseForCloning.getValue(context); } public void setPhaseForCloning(ims.icps.configuration.vo.ICPPhaseRefVo value) { cx_ICPPhaseForCloning.setValue(context, value); } private ims.framework.ContextVariable cx_ICPPhaseForCloning = new ims.framework.ContextVariable("ICP.PhaseForCloning", "_cv_ICP.PhaseForCloning"); public RulesEditorDialogContext RulesEditorDialog; private ims.framework.Context context; } public final class RulesContext implements Serializable { private static final long serialVersionUID = 1L; private RulesContext(ims.framework.Context context) { this.context = context; } public boolean getRuleToEditIsNotNull() { return !cx_RulesRuleToEdit.getValueIsNull(context); } public ims.admin.vo.BusinessRuleVo getRuleToEdit() { return (ims.admin.vo.BusinessRuleVo)cx_RulesRuleToEdit.getValue(context); } public void setRuleToEdit(ims.admin.vo.BusinessRuleVo value) { cx_RulesRuleToEdit.setValue(context, value); } private ims.framework.ContextVariable cx_RulesRuleToEdit = new ims.framework.ContextVariable("Rules.RuleToEdit", "_cv_Rules.RuleToEdit"); private ims.framework.Context context; } public ICPContext ICP; public RulesContext Rules; }
agpl-3.0
nemigaservices/k3po
lang/src/main/java/org/kaazing/k3po/lang/internal/ast/matcher/AstShortLengthBytesMatcher.java
1453
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.k3po.lang.internal.ast.matcher; import static java.lang.String.format; import org.kaazing.k3po.lang.internal.el.ExpressionContext; public class AstShortLengthBytesMatcher extends AstFixedLengthBytesMatcher { public AstShortLengthBytesMatcher(String captureName, ExpressionContext environment) { super(Short.SIZE / Byte.SIZE, captureName, environment); } @Override public <R, P> R accept(Visitor<R, P> visitor, P parameter) throws Exception { return visitor.visit(this, parameter); } @Override protected void describe(StringBuilder buf) { String captureName = getCaptureName(); if (captureName == null) { buf.append("short"); } else { buf.append(format("(short:%s)", captureName)); } } }
agpl-3.0
rossjones/openMAXIMS
Source Library/openmaxims_workspace/OCRR/src/ims/ocrr/forms/myorder/GenForm.java
203490
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.forms.myorder; import ims.framework.*; import ims.framework.controls.*; import ims.framework.enumerations.*; import ims.framework.utils.RuntimeAnchoring; public class GenForm extends FormBridge { private static final long serialVersionUID = 1L; public boolean canProvideData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData(); } public boolean hasData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData(); } public IReportField[] getData(IReportSeed[] reportSeeds) { return getData(reportSeeds, false); } public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls) { return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData(); } public static class lyrDetailsLayer extends Layer { private static final long serialVersionUID = 1L; public static class tabClinicalNotesContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class qmbResponsibleHCPComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.HcpLiteVo value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.HcpLiteVo value) { return super.control.removeRow(value); } public ims.core.vo.HcpLiteVo getValue() { return (ims.core.vo.HcpLiteVo)super.control.getValue(); } public void setValue(ims.core.vo.HcpLiteVo value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } public static class qmbOrderingHCPComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.HcpLiteVo value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.HcpLiteVo value) { return super.control.removeRow(value); } public ims.core.vo.HcpLiteVo getValue() { return (ims.core.vo.HcpLiteVo)super.control.getValue(); } public void setValue(ims.core.vo.HcpLiteVo value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 8, 34, 104, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Responsible HCP:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 8, 10, 85, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Ordering HCP:", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 8, 424, 120, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Additional Information:", new Integer(0), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 520, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), new Integer(startTabIndex.intValue() + 10), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Next >>", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // TextBox Controls RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 8, 440, 616, 72, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT); super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), new Integer(startTabIndex.intValue() + 8), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT,Boolean.TRUE, new Integer(4000), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); // Query ComboBox Controls RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 112, 32, 232, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); ComboBox m_qmbResponsibleHCPTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), new Integer(startTabIndex.intValue() + 4), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.TRUE, new Integer(3), null, Boolean.TRUE, new Integer(-1), Boolean.FALSE}); addControl(m_qmbResponsibleHCPTemp); qmbResponsibleHCPComboBox qmbResponsibleHCP = (qmbResponsibleHCPComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(qmbResponsibleHCPComboBox.class, m_qmbResponsibleHCPTemp); super.addComboBox(qmbResponsibleHCP); RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 112, 8, 232, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); ComboBox m_qmbOrderingHCPTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), new Integer(startTabIndex.intValue() + 3), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.TRUE, new Integer(3), null, Boolean.TRUE, new Integer(-1), Boolean.FALSE}); addControl(m_qmbOrderingHCPTemp); qmbOrderingHCPComboBox qmbOrderingHCP = (qmbOrderingHCPComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(qmbOrderingHCPComboBox.class, m_qmbOrderingHCPTemp); super.addComboBox(qmbOrderingHCP); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 8, 64, 616, 352, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper8.getX()), new Integer(anchoringHelper8.getY()), new Integer(anchoringHelper8.getWidth()), new Integer(anchoringHelper8.getHeight()), new Integer(startTabIndex.intValue() + 6), ControlState.READONLY, ControlState.EDITABLE, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); } public Label lblResponsibleHCP() { return (Label)super.getControl(0); } public Label lblOrderingHCP() { return (Label)super.getControl(1); } public Label lblAdditional() { return (Label)super.getControl(2); } public Button btnContinueClinical() { return (Button)super.getControl(3); } public TextBox txtAdditionalNotes() { return (TextBox)super.getControl(4); } public qmbResponsibleHCPComboBox qmbResponsibleHCP() { return (qmbResponsibleHCPComboBox)super.getComboBox(0); } public qmbOrderingHCPComboBox qmbOrderingHCP() { return (qmbOrderingHCPComboBox)super.getComboBox(1); } public DynamicGrid dyngrdQuestions() { return (DynamicGrid)super.getControl(7); } } public static class tabSummaryClinicalInfoContainer extends LayerBridge { private static final long serialVersionUID = 1L; protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 179, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1008), new Integer(anchoringHelper9.getX()), new Integer(anchoringHelper9.getY()), new Integer(anchoringHelper9.getWidth()), new Integer(anchoringHelper9.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Summary Clinical Information:", new Integer(1), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper10 = new RuntimeAnchoring(designSize, runtimeSize, 528, 520, 96, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1009), new Integer(anchoringHelper10.getX()), new Integer(anchoringHelper10.getY()), new Integer(anchoringHelper10.getWidth()), new Integer(anchoringHelper10.getHeight()), new Integer(startTabIndex.intValue() + 13), ControlState.ENABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Next >>", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper11 = new RuntimeAnchoring(designSize, runtimeSize, 8, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1010), new Integer(anchoringHelper11.getX()), new Integer(anchoringHelper11.getY()), new Integer(anchoringHelper11.getWidth()), new Integer(anchoringHelper11.getHeight()), new Integer(startTabIndex.intValue() + 12), ControlState.ENABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "<< Previous", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // TextBox Controls RuntimeAnchoring anchoringHelper12 = new RuntimeAnchoring(designSize, runtimeSize, 8, 32, 616, 480, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1011), new Integer(anchoringHelper12.getX()), new Integer(anchoringHelper12.getY()), new Integer(anchoringHelper12.getWidth()), new Integer(anchoringHelper12.getHeight()), new Integer(startTabIndex.intValue() + 11), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, new Integer(2000), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); } public Button btnSummaryClinicalInfoNext() { return (Button)super.getControl(1); } public Button btnSummaryClinicalInfoPrevious() { return (Button)super.getControl(2); } public TextBox txtSummaryClinicalInfo() { return (TextBox)super.getControl(3); } } public static class tabGenDetailsContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class cmbDepartmentComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.LocationLiteVo value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.LocationLiteVo value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.LocationLiteVo value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.LocationLiteVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.LocationLiteVo value) { return super.control.removeRow(value); } public ims.core.vo.LocationLiteVo getValue() { return (ims.core.vo.LocationLiteVo)super.control.getValue(); } public void setValue(ims.core.vo.LocationLiteVo value) { super.control.setValue(value); } } public static class cmbHospitalComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.framework.interfaces.ILocation value, String text) { super.control.newRow(value, text); } public void newRow(ims.framework.interfaces.ILocation value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.framework.interfaces.ILocation value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.framework.interfaces.ILocation value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.framework.interfaces.ILocation value) { return super.control.removeRow(value); } public ims.framework.interfaces.ILocation getValue() { return (ims.framework.interfaces.ILocation)super.control.getValue(); } public void setValue(ims.framework.interfaces.ILocation value) { super.control.setValue(value); } } public static class cmbOrderCategoryComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.ocrr.vo.lookups.OrderCategory value, String text) { super.control.newRow(value, text); } public void newRow(ims.ocrr.vo.lookups.OrderCategory value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.ocrr.vo.lookups.OrderCategory value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.ocrr.vo.lookups.OrderCategory value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.ocrr.vo.lookups.OrderCategory value) { return super.control.removeRow(value); } public ims.ocrr.vo.lookups.OrderCategory getValue() { return (ims.ocrr.vo.lookups.OrderCategory)super.control.getValue(); } public void setValue(ims.ocrr.vo.lookups.OrderCategory value) { super.control.setValue(value); } } public static class cmbPriorityComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.ocrr.vo.lookups.OrderPriority value, String text) { super.control.newRow(value, text); } public void newRow(ims.ocrr.vo.lookups.OrderPriority value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.ocrr.vo.lookups.OrderPriority value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.ocrr.vo.lookups.OrderPriority value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.ocrr.vo.lookups.OrderPriority value) { return super.control.removeRow(value); } public ims.ocrr.vo.lookups.OrderPriority getValue() { return (ims.ocrr.vo.lookups.OrderPriority)super.control.getValue(); } public void setValue(ims.ocrr.vo.lookups.OrderPriority value) { super.control.setValue(value); } } public static class qmbOrderedByComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.MemberOfStaffLiteVo value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.MemberOfStaffLiteVo value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.MemberOfStaffLiteVo value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.MemberOfStaffLiteVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.MemberOfStaffLiteVo value) { return super.control.removeRow(value); } public ims.core.vo.MemberOfStaffLiteVo getValue() { return (ims.core.vo.MemberOfStaffLiteVo)super.control.getValue(); } public void setValue(ims.core.vo.MemberOfStaffLiteVo value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } public static class qmbClinicianComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.core.vo.HcpLiteVo value, String text) { super.control.newRow(value, text); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.core.vo.HcpLiteVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.core.vo.HcpLiteVo value) { return super.control.removeRow(value); } public ims.core.vo.HcpLiteVo getValue() { return (ims.core.vo.HcpLiteVo)super.control.getValue(); } public void setValue(ims.core.vo.HcpLiteVo value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } public static class qmbLocationComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.vo.ValueObject value, String text) { super.control.newRow(value, text); } public void newRow(ims.vo.ValueObject value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.vo.ValueObject value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.vo.ValueObject value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.vo.ValueObject value) { return super.control.removeRow(value); } public ims.vo.ValueObject getValue() { return (ims.vo.ValueObject)super.control.getValue(); } public void setValue(ims.vo.ValueObject value) { super.control.setValue(value); } public void setEditedText(String text) { super.control.setEditedText(text); } public String getEditedText() { return super.control.getEditedText(); } } public static class grpPatientLocationRadioButton extends RadioButtonBridge { private static final long serialVersionUID = 1L; protected void setContext(Integer startTabIndex, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize) { if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex "); RuntimeAnchoring anchoringHelper13 = new RuntimeAnchoring(designSize, runtimeSize, 559, 35, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); control.addButton(0, anchoringHelper13.getX(), anchoringHelper13.getY(), anchoringHelper13.getWidth(), "Other", startTabIndex.intValue() + 24); RuntimeAnchoring anchoringHelper14 = new RuntimeAnchoring(designSize, runtimeSize, 482, 35, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); control.addButton(1, anchoringHelper14.getX(), anchoringHelper14.getY(), anchoringHelper14.getWidth(), "ED", startTabIndex.intValue() + 23); RuntimeAnchoring anchoringHelper15 = new RuntimeAnchoring(designSize, runtimeSize, 405, 35, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); control.addButton(2, anchoringHelper15.getX(), anchoringHelper15.getY(), anchoringHelper15.getWidth(), "Clinic", startTabIndex.intValue() + 22); RuntimeAnchoring anchoringHelper16 = new RuntimeAnchoring(designSize, runtimeSize, 328, 35, 56, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); control.addButton(3, anchoringHelper16.getX(), anchoringHelper16.getY(), anchoringHelper16.getWidth(), "Ward", startTabIndex.intValue() + 21); } public void setText(grpPatientLocationEnumeration option, String value) { if(option != null && option.id >= 0 && value != null) control.setText(option.id, value); } public grpPatientLocationEnumeration getValue() { switch (super.control.getValue()) { case -1: return grpPatientLocationEnumeration.None; case 0: return grpPatientLocationEnumeration.rdoOther; case 1: return grpPatientLocationEnumeration.rdoAandE; case 2: return grpPatientLocationEnumeration.rdoClinic; case 3: return grpPatientLocationEnumeration.rdoWard; } return null; } public void setValue(grpPatientLocationEnumeration value) { if(value != null) super.control.setValue(value.id); else super.control.setValue(grpPatientLocationEnumeration.None.id); } public boolean isEnabled(grpPatientLocationEnumeration option) { return super.control.isEnabled(option.id); } public void setEnabled(grpPatientLocationEnumeration option, boolean value) { super.control.setEnabled(option.id, value); } public boolean isVisible(grpPatientLocationEnumeration option) { return super.control.isVisible(option.id); } public void setVisible(grpPatientLocationEnumeration option, boolean value) { super.control.setVisible(option.id, value); } public void setVisible(boolean value) { super.control.setVisible(value); } public void setEnabled(boolean value) { super.control.setEnabled(value); } } public static class grpPatientLocationEnumeration implements java.io.Serializable { private static final long serialVersionUID = 1L; public static grpPatientLocationEnumeration None = new grpPatientLocationEnumeration(-1); public static grpPatientLocationEnumeration rdoOther = new grpPatientLocationEnumeration(0); public static grpPatientLocationEnumeration rdoAandE = new grpPatientLocationEnumeration(1); public static grpPatientLocationEnumeration rdoClinic = new grpPatientLocationEnumeration(2); public static grpPatientLocationEnumeration rdoWard = new grpPatientLocationEnumeration(3); private grpPatientLocationEnumeration(int id) { this.id = id; } public boolean equals(Object o) { return this.id == ((grpPatientLocationEnumeration)o).id; } private int id; } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper17 = new RuntimeAnchoring(designSize, runtimeSize, 8, 118, 101, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1012), new Integer(anchoringHelper17.getX()), new Integer(anchoringHelper17.getY()), new Integer(anchoringHelper17.getWidth()), new Integer(anchoringHelper17.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Bleep No / Ext. No:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper18 = new RuntimeAnchoring(designSize, runtimeSize, 328, 97, 67, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1013), new Integer(anchoringHelper18.getX()), new Integer(anchoringHelper18.getY()), new Integer(anchoringHelper18.getWidth()), new Integer(anchoringHelper18.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Department:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper19 = new RuntimeAnchoring(designSize, runtimeSize, 328, 84, 57, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1014), new Integer(anchoringHelper19.getX()), new Integer(anchoringHelper19.getY()), new Integer(anchoringHelper19.getWidth()), new Integer(anchoringHelper19.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Outpatient", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper20 = new RuntimeAnchoring(designSize, runtimeSize, 8, 98, 53, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1015), new Integer(anchoringHelper20.getX()), new Integer(anchoringHelper20.getY()), new Integer(anchoringHelper20.getWidth()), new Integer(anchoringHelper20.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Category:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper21 = new RuntimeAnchoring(designSize, runtimeSize, 8, 68, 49, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1016), new Integer(anchoringHelper21.getX()), new Integer(anchoringHelper21.getY()), new Integer(anchoringHelper21.getWidth()), new Integer(anchoringHelper21.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Clinician:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper22 = new RuntimeAnchoring(designSize, runtimeSize, 8, 20, 29, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1017), new Integer(anchoringHelper22.getX()), new Integer(anchoringHelper22.getY()), new Integer(anchoringHelper22.getWidth()), new Integer(anchoringHelper22.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "HCP:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper23 = new RuntimeAnchoring(designSize, runtimeSize, 352, 162, 85, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1018), new Integer(anchoringHelper23.getX()), new Integer(anchoringHelper23.getY()), new Integer(anchoringHelper23.getWidth()), new Integer(anchoringHelper23.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "PAS Episode ID:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper24 = new RuntimeAnchoring(designSize, runtimeSize, 328, 62, 88, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1019), new Integer(anchoringHelper24.getX()), new Integer(anchoringHelper24.getY()), new Integer(anchoringHelper24.getWidth()), new Integer(anchoringHelper24.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Patient Location:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper25 = new RuntimeAnchoring(designSize, runtimeSize, 8, 200, 96, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1020), new Integer(anchoringHelper25.getX()), new Integer(anchoringHelper25.getY()), new Integer(anchoringHelper25.getWidth()), new Integer(anchoringHelper25.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Paper Report To", new Integer(1), null, new Integer(0)})); RuntimeAnchoring anchoringHelper26 = new RuntimeAnchoring(designSize, runtimeSize, 8, 85, 33, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1021), new Integer(anchoringHelper26.getX()), new Integer(anchoringHelper26.getY()), new Integer(anchoringHelper26.getWidth()), new Integer(anchoringHelper26.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Order", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper27 = new RuntimeAnchoring(designSize, runtimeSize, 8, 162, 75, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1022), new Integer(anchoringHelper27.getX()), new Integer(anchoringHelper27.getY()), new Integer(anchoringHelper27.getWidth()), new Integer(anchoringHelper27.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Order Priority:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper28 = new RuntimeAnchoring(designSize, runtimeSize, 8, 55, 32, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1023), new Integer(anchoringHelper28.getX()), new Integer(anchoringHelper28.getY()), new Integer(anchoringHelper28.getWidth()), new Integer(anchoringHelper28.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Resp.", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper29 = new RuntimeAnchoring(designSize, runtimeSize, 368, 10, 48, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1024), new Integer(anchoringHelper29.getX()), new Integer(anchoringHelper29.getY()), new Integer(anchoringHelper29.getWidth()), new Integer(anchoringHelper29.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Hospital:", new Integer(0), null, new Integer(0)})); RuntimeAnchoring anchoringHelper30 = new RuntimeAnchoring(designSize, runtimeSize, 8, 6, 48, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1025), new Integer(anchoringHelper30.getX()), new Integer(anchoringHelper30.getY()), new Integer(anchoringHelper30.getWidth()), new Integer(anchoringHelper30.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Ordering", new Integer(0), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper31 = new RuntimeAnchoring(designSize, runtimeSize, 8, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1026), new Integer(anchoringHelper31.getX()), new Integer(anchoringHelper31.getY()), new Integer(anchoringHelper31.getWidth()), new Integer(anchoringHelper31.getHeight()), new Integer(startTabIndex.intValue() + 36), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "<< Previous", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper32 = new RuntimeAnchoring(designSize, runtimeSize, 520, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1027), new Integer(anchoringHelper32.getX()), new Integer(anchoringHelper32.getY()), new Integer(anchoringHelper32.getWidth()), new Integer(anchoringHelper32.getHeight()), new Integer(startTabIndex.intValue() + 37), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Next >>", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // TextBox Controls RuntimeAnchoring anchoringHelper33 = new RuntimeAnchoring(designSize, runtimeSize, 104, 116, 208, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1028), new Integer(anchoringHelper33.getX()), new Integer(anchoringHelper33.getY()), new Integer(anchoringHelper33.getWidth()), new Integer(anchoringHelper33.getHeight()), new Integer(startTabIndex.intValue() + 18), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.FALSE, new Integer(50), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.TRUE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); RuntimeAnchoring anchoringHelper34 = new RuntimeAnchoring(designSize, runtimeSize, 440, 160, 176, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1029), new Integer(anchoringHelper34.getX()), new Integer(anchoringHelper34.getY()), new Integer(anchoringHelper34.getWidth()), new Integer(anchoringHelper34.getHeight()), new Integer(startTabIndex.intValue() + 32), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.FALSE, new Integer(0), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""})); // ComboBox Controls RuntimeAnchoring anchoringHelper35 = new RuntimeAnchoring(designSize, runtimeSize, 416, 88, 200, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); ComboBox m_cmbDepartmentTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1030), new Integer(anchoringHelper35.getX()), new Integer(anchoringHelper35.getY()), new Integer(anchoringHelper35.getWidth()), new Integer(anchoringHelper35.getHeight()), new Integer(startTabIndex.intValue() + 26), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)}); addControl(m_cmbDepartmentTemp); cmbDepartmentComboBox cmbDepartment = (cmbDepartmentComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbDepartmentComboBox.class, m_cmbDepartmentTemp); super.addComboBox(cmbDepartment); RuntimeAnchoring anchoringHelper36 = new RuntimeAnchoring(designSize, runtimeSize, 416, 8, 200, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); ComboBox m_cmbHospitalTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1031), new Integer(anchoringHelper36.getX()), new Integer(anchoringHelper36.getY()), new Integer(anchoringHelper36.getWidth()), new Integer(anchoringHelper36.getHeight()), new Integer(startTabIndex.intValue() + 20), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)}); addControl(m_cmbHospitalTemp); cmbHospitalComboBox cmbHospital = (cmbHospitalComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbHospitalComboBox.class, m_cmbHospitalTemp); super.addComboBox(cmbHospital); RuntimeAnchoring anchoringHelper37 = new RuntimeAnchoring(designSize, runtimeSize, 64, 88, 248, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_cmbOrderCategoryTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1032), new Integer(anchoringHelper37.getX()), new Integer(anchoringHelper37.getY()), new Integer(anchoringHelper37.getWidth()), new Integer(anchoringHelper37.getHeight()), new Integer(startTabIndex.intValue() + 17), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)}); addControl(m_cmbOrderCategoryTemp); cmbOrderCategoryComboBox cmbOrderCategory = (cmbOrderCategoryComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbOrderCategoryComboBox.class, m_cmbOrderCategoryTemp); super.addComboBox(cmbOrderCategory); RuntimeAnchoring anchoringHelper38 = new RuntimeAnchoring(designSize, runtimeSize, 128, 160, 184, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_cmbPriorityTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1033), new Integer(anchoringHelper38.getX()), new Integer(anchoringHelper38.getY()), new Integer(anchoringHelper38.getWidth()), new Integer(anchoringHelper38.getHeight()), new Integer(startTabIndex.intValue() + 30), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)}); addControl(m_cmbPriorityTemp); cmbPriorityComboBox cmbPriority = (cmbPriorityComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbPriorityComboBox.class, m_cmbPriorityTemp); super.addComboBox(cmbPriority); // Query ComboBox Controls RuntimeAnchoring anchoringHelper39 = new RuntimeAnchoring(designSize, runtimeSize, 64, 8, 248, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_qmbOrderedByTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1034), new Integer(anchoringHelper39.getX()), new Integer(anchoringHelper39.getY()), new Integer(anchoringHelper39.getWidth()), new Integer(anchoringHelper39.getHeight()), new Integer(startTabIndex.intValue() + 15), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.TRUE, new Integer(1), null, Boolean.TRUE, new Integer(-1), Boolean.FALSE}); addControl(m_qmbOrderedByTemp); qmbOrderedByComboBox qmbOrderedBy = (qmbOrderedByComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(qmbOrderedByComboBox.class, m_qmbOrderedByTemp); super.addComboBox(qmbOrderedBy); RuntimeAnchoring anchoringHelper40 = new RuntimeAnchoring(designSize, runtimeSize, 64, 60, 248, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_qmbClinicianTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1035), new Integer(anchoringHelper40.getX()), new Integer(anchoringHelper40.getY()), new Integer(anchoringHelper40.getWidth()), new Integer(anchoringHelper40.getHeight()), new Integer(startTabIndex.intValue() + 16), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.TRUE, new Integer(1), null, Boolean.TRUE, new Integer(-1), Boolean.FALSE}); addControl(m_qmbClinicianTemp); qmbClinicianComboBox qmbClinician = (qmbClinicianComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(qmbClinicianComboBox.class, m_qmbClinicianTemp); super.addComboBox(qmbClinician); RuntimeAnchoring anchoringHelper41 = new RuntimeAnchoring(designSize, runtimeSize, 416, 60, 200, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); ComboBox m_qmbLocationTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1036), new Integer(anchoringHelper41.getX()), new Integer(anchoringHelper41.getY()), new Integer(anchoringHelper41.getWidth()), new Integer(anchoringHelper41.getHeight()), new Integer(startTabIndex.intValue() + 25), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.TRUE, new Integer(1), null, Boolean.FALSE, new Integer(-1), Boolean.FALSE}); addControl(m_qmbLocationTemp); qmbLocationComboBox qmbLocation = (qmbLocationComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(qmbLocationComboBox.class, m_qmbLocationTemp); super.addComboBox(qmbLocation); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper42 = new RuntimeAnchoring(designSize, runtimeSize, 8, 224, 616, 288, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1037), new Integer(anchoringHelper42.getX()), new Integer(anchoringHelper42.getY()), new Integer(anchoringHelper42.getWidth()), new Integer(anchoringHelper42.getHeight()), new Integer(startTabIndex.intValue() + 34), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, contextMenus.contextMenuOCRRMyOrderReportTo, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); // Image Buttons Controls RuntimeAnchoring anchoringHelper43 = new RuntimeAnchoring(designSize, runtimeSize, 96, 158, 24, 24, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1038), new Integer(anchoringHelper43.getX()), new Integer(anchoringHelper43.getY()), new Integer(anchoringHelper43.getWidth()), new Integer(anchoringHelper43.getHeight()), new Integer(startTabIndex.intValue() + 28), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, form_images_local.Core.Form, form_images_local.Core.Form, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null})); // RadioButton Controls RadioButton tmpgrpPatientLocation = (RadioButton)factory.getControl(RadioButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1039), new Integer(0), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE}); super.addControl(tmpgrpPatientLocation); grpPatientLocationRadioButton grpPatientLocation = (grpPatientLocationRadioButton)RadioButtonBridgeFlyweightFactory.getInstance().createRadioButtonBridge(grpPatientLocationRadioButton.class, tmpgrpPatientLocation); grpPatientLocation.setContext(startTabIndex, designSize, runtimeSize); super.addRadioButton(grpPatientLocation); // Horizontal Line Controls RuntimeAnchoring anchoringHelper44 = new RuntimeAnchoring(designSize, runtimeSize, 8, 144, 616, 8, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); super.addControl(factory.getControl(HorizontalLine.class, new Object[] { control, new Integer(startControlID.intValue() + 1040), new Integer(anchoringHelper44.getX()), new Integer(anchoringHelper44.getY()), new Integer(anchoringHelper44.getWidth()), new Integer(anchoringHelper44.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,new Integer(0)})); } public Label lblBleepNo() { return (Label)super.getControl(0); } public Label lblDepartment() { return (Label)super.getControl(1); } public Label lblOutpatient() { return (Label)super.getControl(2); } public Label lblPasEpisodeID() { return (Label)super.getControl(6); } public Label lblPatientLocation() { return (Label)super.getControl(7); } public Label lbl8() { return (Label)super.getControl(8); } public Button btnPreviousGeneral() { return (Button)super.getControl(14); } public Button btnContinueGeneral() { return (Button)super.getControl(15); } public TextBox txtBleepNo() { return (TextBox)super.getControl(16); } public TextBox txtPasEpisodeID() { return (TextBox)super.getControl(17); } public cmbDepartmentComboBox cmbDepartment() { return (cmbDepartmentComboBox)super.getComboBox(0); } public cmbHospitalComboBox cmbHospital() { return (cmbHospitalComboBox)super.getComboBox(1); } public cmbOrderCategoryComboBox cmbOrderCategory() { return (cmbOrderCategoryComboBox)super.getComboBox(2); } public cmbPriorityComboBox cmbPriority() { return (cmbPriorityComboBox)super.getComboBox(3); } public qmbOrderedByComboBox qmbOrderedBy() { return (qmbOrderedByComboBox)super.getComboBox(4); } public qmbClinicianComboBox qmbClinician() { return (qmbClinicianComboBox)super.getComboBox(5); } public qmbLocationComboBox qmbLocation() { return (qmbLocationComboBox)super.getComboBox(6); } public DynamicGrid dyngrdReportTo() { return (DynamicGrid)super.getControl(25); } public ImageButton imbOrderPriority() { return (ImageButton)super.getControl(26); } public grpPatientLocationRadioButton grpPatientLocation() { return (grpPatientLocationRadioButton)super.getRadioButton(0); } } public static class tabRadDetailsContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class cmbPatMobilityComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.ocrr.vo.lookups.OrderPatMobility value, String text) { super.control.newRow(value, text); } public void newRow(ims.ocrr.vo.lookups.OrderPatMobility value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.ocrr.vo.lookups.OrderPatMobility value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.ocrr.vo.lookups.OrderPatMobility value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.ocrr.vo.lookups.OrderPatMobility value) { return super.control.removeRow(value); } public ims.ocrr.vo.lookups.OrderPatMobility getValue() { return (ims.ocrr.vo.lookups.OrderPatMobility)super.control.getValue(); } public void setValue(ims.ocrr.vo.lookups.OrderPatMobility value) { super.control.setValue(value); } } public static class grdRadOrdersRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdRadOrdersRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setColExamNameReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean isColExamNameReadOnly() { return super.row.isReadOnly(0); } public void showColExamNameOpened() { super.row.showOpened(0); } public void setTooltipForColExamName(String value) { super.row.setTooltip(0, value); } public String getColExamName() { return (String)super.row.get(0); } public void setColExamName(String value) { super.row.set(0, value); } public void setCellColExamNameTooltip(String value) { super.row.setTooltip(0, value); } public void setColLocationReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean isColLocationReadOnly() { return super.row.isReadOnly(1); } public void showColLocationOpened() { super.row.showOpened(1); } public void setTooltipForColLocation(String value) { super.row.setTooltip(1, value); } public ims.framework.controls.GridMutableComboBox getColLocation() { return new ims.framework.controls.GridMutableComboBox(super.row, 1); } public void setCellColLocationTooltip(String value) { super.row.setTooltip(1, value); } public ims.ocrr.vo.OrderInvestigationVo getValue() { return (ims.ocrr.vo.OrderInvestigationVo)super.row.getValue(); } public void setValue(ims.ocrr.vo.OrderInvestigationVo value) { super.row.setValue(value); } } public static class grdRadOrdersRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdRadOrdersRowCollection(GridRowCollection collection) { super(collection); } public grdRadOrdersRow get(int index) { return new grdRadOrdersRow(super.collection.get(index)); } public grdRadOrdersRow newRow() { return new grdRadOrdersRow(super.collection.newRow()); } public grdRadOrdersRow newRow(boolean autoSelect) { return new grdRadOrdersRow(super.collection.newRow(autoSelect)); } public grdRadOrdersRow newRowAt(int index) { return new grdRadOrdersRow(super.collection.newRowAt(index)); } public grdRadOrdersRow newRowAt(int index, boolean autoSelect) { return new grdRadOrdersRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdRadOrdersGrid extends GridBridge { private static final long serialVersionUID = 1L; private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } private void addMutableComboBoxColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean canBeEmpty, boolean autoPostBack, boolean bold, boolean searchable, boolean canGrow, int maxDropDownItems) { super.grid.addMutableComboBoxColumn(caption, captionAlignment, alignment, width, readOnly, canBeEmpty, autoPostBack, bold, searchable, canGrow, maxDropDownItems); } public ims.ocrr.vo.OrderInvestigationVoCollection getValues() { ims.ocrr.vo.OrderInvestigationVoCollection listOfValues = new ims.ocrr.vo.OrderInvestigationVoCollection(); for(int x = 0; x < this.getRows().size(); x++) { listOfValues.add(this.getRows().get(x).getValue()); } return listOfValues; } public ims.ocrr.vo.OrderInvestigationVo getValue() { return (ims.ocrr.vo.OrderInvestigationVo)super.grid.getValue(); } public void setValue(ims.ocrr.vo.OrderInvestigationVo value) { super.grid.setValue(value); } public grdRadOrdersRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdRadOrdersRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdRadOrdersRowCollection getRows() { return new grdRadOrdersRowCollection(super.grid.getRows()); } public grdRadOrdersRow getRowByValue(ims.ocrr.vo.OrderInvestigationVo value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdRadOrdersRow(row); } public void setColExamNameHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getColExamNameHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setColLocationHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getColLocationHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper45 = new RuntimeAnchoring(designSize, runtimeSize, 16, 26, 85, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1041), new Integer(anchoringHelper45.getX()), new Integer(anchoringHelper45.getY()), new Integer(anchoringHelper45.getWidth()), new Integer(anchoringHelper45.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Patient Mobility:", new Integer(0), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper46 = new RuntimeAnchoring(designSize, runtimeSize, 16, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1042), new Integer(anchoringHelper46.getX()), new Integer(anchoringHelper46.getY()), new Integer(anchoringHelper46.getWidth()), new Integer(anchoringHelper46.getHeight()), new Integer(startTabIndex.intValue() + 43), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "<< Previous", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper47 = new RuntimeAnchoring(designSize, runtimeSize, 512, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1043), new Integer(anchoringHelper47.getX()), new Integer(anchoringHelper47.getY()), new Integer(anchoringHelper47.getWidth()), new Integer(anchoringHelper47.getHeight()), new Integer(startTabIndex.intValue() + 47), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Next >>", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // ComboBox Controls RuntimeAnchoring anchoringHelper48 = new RuntimeAnchoring(designSize, runtimeSize, 112, 24, 264, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT); ComboBox m_cmbPatMobilityTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1044), new Integer(anchoringHelper48.getX()), new Integer(anchoringHelper48.getY()), new Integer(anchoringHelper48.getWidth()), new Integer(anchoringHelper48.getHeight()), new Integer(startTabIndex.intValue() + 39), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)}); addControl(m_cmbPatMobilityTemp); cmbPatMobilityComboBox cmbPatMobility = (cmbPatMobilityComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbPatMobilityComboBox.class, m_cmbPatMobilityTemp); super.addComboBox(cmbPatMobility); // CheckBox Controls RuntimeAnchoring anchoringHelper49 = new RuntimeAnchoring(designSize, runtimeSize, 136, 523, 312, 16, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1045), new Integer(anchoringHelper49.getX()), new Integer(anchoringHelper49.getY()), new Integer(anchoringHelper49.getWidth()), new Integer(anchoringHelper49.getHeight()), new Integer(startTabIndex.intValue() + 45), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT ,"Do you wish to print any Radiology Orders to a local printer?", Boolean.TRUE, null})); // Grid Controls RuntimeAnchoring anchoringHelper50 = new RuntimeAnchoring(designSize, runtimeSize, 16, 64, 600, 448, ims.framework.enumerations.ControlAnchoring.ALL); Grid m_grdRadOrdersTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1046), new Integer(anchoringHelper50.getX()), new Integer(anchoringHelper50.getY()), new Integer(anchoringHelper50.getWidth()), new Integer(anchoringHelper50.getHeight()), new Integer(startTabIndex.intValue() + 41), ControlState.READONLY, ControlState.EDITABLE, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, Boolean.FALSE, new Integer(24), Boolean.FALSE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdRadOrdersTemp); grdRadOrdersGrid grdRadOrders = (grdRadOrdersGrid)GridFlyweightFactory.getInstance().createGridBridge(grdRadOrdersGrid.class, m_grdRadOrdersTemp); grdRadOrders.addStringColumn("Exam Name", 0, 0, 360, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdRadOrders.addMutableComboBoxColumn("Location", 0, 0, -1, false, true, false, false, false, true, -1); super.addGrid(grdRadOrders); } public Label lblPatMobility() { return (Label)super.getControl(0); } public Button btnPreviousRad() { return (Button)super.getControl(1); } public Button btnContinueRad() { return (Button)super.getControl(2); } public cmbPatMobilityComboBox cmbPatMobility() { return (cmbPatMobilityComboBox)super.getComboBox(0); } public CheckBox chkPrintLocal() { return (CheckBox)super.getControl(4); } public grdRadOrdersGrid grdRadOrders() { return (grdRadOrdersGrid)super.getGrid(0); } } public static class tabPathDetailsContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class lyrPathologyLayer extends Layer { private static final long serialVersionUID = 1L; public static class tabRequestedTestsContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class cmbRequestedTypeComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionType value, String text) { super.control.newRow(value, text); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionType value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionType value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionType value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.ocrr.vo.lookups.SpecimenCollectionType value) { return super.control.removeRow(value); } public ims.ocrr.vo.lookups.SpecimenCollectionType getValue() { return (ims.ocrr.vo.lookups.SpecimenCollectionType)super.control.getValue(); } public void setValue(ims.ocrr.vo.lookups.SpecimenCollectionType value) { super.control.setValue(value); } } public static class grdTestRow extends GridRowBridge { private static final long serialVersionUID = 1L; protected grdTestRow(GridRow row) { super(row); } public void showOpened(int column) { super.row.showOpened(column); } public void setColTestReadOnly(boolean value) { super.row.setReadOnly(0, value); } public boolean isColTestReadOnly() { return super.row.isReadOnly(0); } public void showColTestOpened() { super.row.showOpened(0); } public void setTooltipForColTest(String value) { super.row.setTooltip(0, value); } public String getColTest() { return (String)super.row.get(0); } public void setColTest(String value) { super.row.set(0, value); } public void setCellColTestTooltip(String value) { super.row.setTooltip(0, value); } public void setColSpecimenReadOnly(boolean value) { super.row.setReadOnly(1, value); } public boolean isColSpecimenReadOnly() { return super.row.isReadOnly(1); } public void showColSpecimenOpened() { super.row.showOpened(1); } public void setTooltipForColSpecimen(String value) { super.row.setTooltip(1, value); } public ims.ocrr.vo.SpecimenVo getColSpecimen() { return (ims.ocrr.vo.SpecimenVo)super.row.get(1); } public void setColSpecimen(ims.ocrr.vo.SpecimenVo value) { super.row.set(1, value); } public void setCellColSpecimenTooltip(String value) { super.row.setTooltip(1, value); } public void setColTestNameHiddenReadOnly(boolean value) { super.row.setReadOnly(2, value); } public boolean isColTestNameHiddenReadOnly() { return super.row.isReadOnly(2); } public void showColTestNameHiddenOpened() { super.row.showOpened(2); } public void setTooltipForColTestNameHidden(String value) { super.row.setTooltip(2, value); } public String getColTestNameHidden() { return (String)super.row.get(2); } public void setColTestNameHidden(String value) { super.row.set(2, value); } public void setCellColTestNameHiddenTooltip(String value) { super.row.setTooltip(2, value); } public void setColHiddenOrderInvestigationSiteReadOnly(boolean value) { super.row.setReadOnly(3, value); } public boolean isColHiddenOrderInvestigationSiteReadOnly() { return super.row.isReadOnly(3); } public void showColHiddenOrderInvestigationSiteOpened() { super.row.showOpened(3); } public void setTooltipForColHiddenOrderInvestigationSite(String value) { super.row.setTooltip(3, value); } public ims.ocrr.vo.OrderInvestigationVo getColHiddenOrderInvestigationSite() { return (ims.ocrr.vo.OrderInvestigationVo)super.row.get(3); } public void setColHiddenOrderInvestigationSite(ims.ocrr.vo.OrderInvestigationVo value) { super.row.set(3, value); } public void setCellColHiddenOrderInvestigationSiteTooltip(String value) { super.row.setTooltip(3, value); } public void setColSiteHiddenReadOnly(boolean value) { super.row.setReadOnly(4, value); } public boolean isColSiteHiddenReadOnly() { return super.row.isReadOnly(4); } public void showColSiteHiddenOpened() { super.row.showOpened(4); } public void setTooltipForColSiteHidden(String value) { super.row.setTooltip(4, value); } public ims.core.helper.GenericInfoAdapter getColSiteHidden() { return (ims.core.helper.GenericInfoAdapter)super.row.get(4); } public void setColSiteHidden(ims.core.helper.GenericInfoAdapter value) { super.row.set(4, value); } public void setCellColSiteHiddenTooltip(String value) { super.row.setTooltip(4, value); } public void setColAddOnsHiddenReadOnly(boolean value) { super.row.setReadOnly(5, value); } public boolean isColAddOnsHiddenReadOnly() { return super.row.isReadOnly(5); } public void showColAddOnsHiddenOpened() { super.row.showOpened(5); } public void setTooltipForColAddOnsHidden(String value) { super.row.setTooltip(5, value); } public ims.ocrr.vo.InvestigationUnderSpecimenVoCollection getColAddOnsHidden() { return (ims.ocrr.vo.InvestigationUnderSpecimenVoCollection)super.row.get(5); } public void setColAddOnsHidden(ims.ocrr.vo.InvestigationUnderSpecimenVoCollection value) { super.row.set(5, value); } public void setCellColAddOnsHiddenTooltip(String value) { super.row.setTooltip(5, value); } public void setColBtnSitesReadOnly(boolean value) { super.row.setReadOnly(6, value); } public boolean isColBtnSitesReadOnly() { return super.row.isReadOnly(6); } public void setColBtnSitesEmpty(boolean value) { super.row.setIsEmpty(6, value); } public boolean isColBtnSitesEmpty() { return super.row.isEmpty(6); } public void showColBtnSitesOpened() { super.row.showOpened(6); } public void setTooltipForColBtnSites(String value) { super.row.setTooltip(6, value); } public ims.framework.utils.Image getColBtnSites() { return (ims.framework.utils.Image)super.row.get(6); } public void setColBtnSites(ims.framework.utils.Image value) { super.row.set(6, value); } public void setCellColBtnSitesTooltip(String value) { super.row.setTooltip(6, value); } public void setColTypeReadOnly(boolean value) { super.row.setReadOnly(7, value); } public boolean isColTypeReadOnly() { return super.row.isReadOnly(7); } public void setColTypeEmpty(boolean value) { super.row.setIsEmpty(7, value); } public boolean isColTypeEmpty() { return super.row.isEmpty(7); } public void showColTypeOpened() { super.row.showOpened(7); } public void setTooltipForColType(String value) { super.row.setTooltip(7, value); } public ims.framework.controls.GridMutableComboBox getColType() { return new ims.framework.controls.GridMutableComboBox(super.row, 7); } public void setCellColTypeTooltip(String value) { super.row.setTooltip(7, value); } public ims.ocrr.vo.OrderInvestigationVo getValue() { return (ims.ocrr.vo.OrderInvestigationVo)super.row.getValue(); } public void setValue(ims.ocrr.vo.OrderInvestigationVo value) { super.row.setValue(value); } public grdTestRow getParentRow() { return super.row.getParent() == null ? null : new grdTestRow(super.row.getParent()); } public grdTestRowCollection getRows() { if(this.collection == null) this.collection = new grdTestRowCollection(super.row.getRows()); return this.collection; } private grdTestRowCollection collection; } public static class grdTestRowCollection extends GridRowCollectionBridge { private static final long serialVersionUID = 1L; private grdTestRowCollection(GridRowCollection collection) { super(collection); } public grdTestRow get(int index) { return new grdTestRow(super.collection.get(index)); } public grdTestRow newRow() { return new grdTestRow(super.collection.newRow()); } public grdTestRow newRow(boolean autoSelect) { return new grdTestRow(super.collection.newRow(autoSelect)); } public grdTestRow newRowAt(int index) { return new grdTestRow(super.collection.newRowAt(index)); } public grdTestRow newRowAt(int index, boolean autoSelect) { return new grdTestRow(super.collection.newRowAt(index, autoSelect)); } } public static class grdTestGrid extends GridBridge { private static final long serialVersionUID = 1L; public GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[] getAllRows() { java.util.ArrayList rows = new java.util.ArrayList(); for(int x = 0; x < getRows().size(); x++) { GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow row = getRows().get(x); rows.add(row); GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[] childRows = getAllRows(row); for(int i = 0; i < childRows.length; i++) { rows.add(childRows[i]); } } GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[] result = new GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[rows.size()]; for(int x = 0; x < rows.size(); x++) { result[x] = (GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow)rows.get(x); } return result; } public GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[] getAllRows(GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow parentRow) { java.util.ArrayList rows = new java.util.ArrayList(); for(int x = 0; x < parentRow.getRows().size(); x++) { GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow row = parentRow.getRows().get(x); rows.add(row); GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[] childRows = getAllRows(row); for(int i = 0; i < childRows.length; i++) { rows.add(childRows[i]); } } GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[] result = new GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow[rows.size()]; for(int x = 0; x < rows.size(); x++) { result[x] = (GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow)rows.get(x); } return result; } public void expandAll() { expandCollapseAll(true); } public void collapseAll() { expandCollapseAll(false); } private void expandCollapseAll(boolean expand) { for(int x = 0; x < getRows().size(); x++) { GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow row = getRows().get(x); row.setExpanded(expand); expandCollapseRow(row, expand); } } private void expandCollapseRow(GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow parentRow, boolean expand) { for(int x = 0; x < parentRow.getRows().size(); x++) { GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow row = parentRow.getRows().get(x); row.setExpanded(expand); expandCollapseRow(row, expand); } } private void addTreeColumn(String caption, int captionAlignment, int width, boolean bold, boolean canGrow) { super.grid.addTreeColumn(caption, captionAlignment, width, bold, canGrow); } private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing) { super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing); } private void addButtonColumn(String caption, int captionAlignment, int alignment, int width, boolean bold, boolean canGrow) { super.grid.addButtonColumn(caption, captionAlignment, alignment, width, bold, canGrow); } private void addMutableComboBoxColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean canBeEmpty, boolean autoPostBack, boolean bold, boolean searchable, boolean canGrow, int maxDropDownItems) { super.grid.addMutableComboBoxColumn(caption, captionAlignment, alignment, width, readOnly, canBeEmpty, autoPostBack, bold, searchable, canGrow, maxDropDownItems); } public ims.ocrr.vo.OrderInvestigationVoCollection getValues() { ims.ocrr.vo.OrderInvestigationVoCollection listOfValues = new ims.ocrr.vo.OrderInvestigationVoCollection(); for(int x = 0; x < this.getRows().size(); x++) { listOfValues.add(this.getRows().get(x).getValue()); } return listOfValues; } public ims.ocrr.vo.OrderInvestigationVo getValue() { return (ims.ocrr.vo.OrderInvestigationVo)super.grid.getValue(); } public void setValue(ims.ocrr.vo.OrderInvestigationVo value) { super.grid.setValue(value); } public grdTestRow getSelectedRow() { return super.grid.getSelectedRow() == null ? null : new grdTestRow(super.grid.getSelectedRow()); } public int getSelectedRowIndex() { return super.grid.getSelectedRowIndex(); } public grdTestRowCollection getRows() { return new grdTestRowCollection(super.grid.getRows()); } public grdTestRow getRowByValue(ims.ocrr.vo.OrderInvestigationVo value) { GridRow row = super.grid.getRowByValue(value); return row == null?null:new grdTestRow(row); } public void setColTestHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(0, value); } public String getColTestHeaderTooltip() { return super.grid.getColumnHeaderTooltip(0); } public void setColSpecimenHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(1, value); } public String getColSpecimenHeaderTooltip() { return super.grid.getColumnHeaderTooltip(1); } public void setColTestNameHiddenHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(2, value); } public String getColTestNameHiddenHeaderTooltip() { return super.grid.getColumnHeaderTooltip(2); } public void setColHiddenOrderInvestigationSiteHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(3, value); } public String getColHiddenOrderInvestigationSiteHeaderTooltip() { return super.grid.getColumnHeaderTooltip(3); } public void setColSiteHiddenHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(4, value); } public String getColSiteHiddenHeaderTooltip() { return super.grid.getColumnHeaderTooltip(4); } public void setColAddOnsHiddenHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(5, value); } public String getColAddOnsHiddenHeaderTooltip() { return super.grid.getColumnHeaderTooltip(5); } public void setColBtnSitesHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(6, value); } public String getColBtnSitesHeaderTooltip() { return super.grid.getColumnHeaderTooltip(6); } public void setColTypeHeaderTooltip(String value) { super.grid.setColumnHeaderTooltip(7, value); } public String getColTypeHeaderTooltip() { return super.grid.getColumnHeaderTooltip(7); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper51 = new RuntimeAnchoring(designSize, runtimeSize, 280, 18, 95, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1047), new Integer(anchoringHelper51.getX()), new Integer(anchoringHelper51.getY()), new Integer(anchoringHelper51.getWidth()), new Integer(anchoringHelper51.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Collection Type:", new Integer(1), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper52 = new RuntimeAnchoring(designSize, runtimeSize, 8, 14, 192, 24, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1048), new Integer(anchoringHelper52.getX()), new Integer(anchoringHelper52.getY()), new Integer(anchoringHelper52.getWidth()), new Integer(anchoringHelper52.getHeight()), new Integer(startTabIndex.intValue() + 50), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Source of Specimen", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // ComboBox Controls RuntimeAnchoring anchoringHelper53 = new RuntimeAnchoring(designSize, runtimeSize, 384, 16, 224, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); ComboBox m_cmbRequestedTypeTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1049), new Integer(anchoringHelper53.getX()), new Integer(anchoringHelper53.getY()), new Integer(anchoringHelper53.getWidth()), new Integer(anchoringHelper53.getHeight()), new Integer(startTabIndex.intValue() + 53), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)}); addControl(m_cmbRequestedTypeTemp); cmbRequestedTypeComboBox cmbRequestedType = (cmbRequestedTypeComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbRequestedTypeComboBox.class, m_cmbRequestedTypeTemp); super.addComboBox(cmbRequestedType); // Grid Controls RuntimeAnchoring anchoringHelper54 = new RuntimeAnchoring(designSize, runtimeSize, 8, 48, 600, 424, ims.framework.enumerations.ControlAnchoring.ALL); Grid m_grdTestTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1050), new Integer(anchoringHelper54.getX()), new Integer(anchoringHelper54.getY()), new Integer(anchoringHelper54.getWidth()), new Integer(anchoringHelper54.getHeight()), new Integer(startTabIndex.intValue() + 54), ControlState.READONLY, ControlState.EDITABLE, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, Boolean.FALSE, new Integer(24), Boolean.FALSE, contextMenus.contextMenuSelectItems, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE}); addControl(m_grdTestTemp); grdTestGrid grdTest = (grdTestGrid)GridFlyweightFactory.getInstance().createGridBridge(grdTestGrid.class, m_grdTestTemp); grdTest.addTreeColumn("Investigations", 0, 375, false, true); grdTest.addStringColumn(" ", 0, 0, 0, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdTest.addStringColumn(" ", 0, 0, 0, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdTest.addStringColumn(" ", 0, 0, 0, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdTest.addStringColumn(" ", 0, 0, 0, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdTest.addStringColumn(" ", 0, 0, 0, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL); grdTest.addButtonColumn(" ", 0, 1, 35, false, true); grdTest.addMutableComboBoxColumn("Collection Type", 0, 0, -1, false, true, true, false, false, true, -1); super.addGrid(grdTest); } public Button btnSites() { return (Button)super.getControl(1); } public cmbRequestedTypeComboBox cmbRequestedType() { return (cmbRequestedTypeComboBox)super.getComboBox(0); } public grdTestGrid grdTest() { return (grdTestGrid)super.getGrid(0); } } public static class tabNowContainer extends LayerBridge { private static final long serialVersionUID = 1L; protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper55 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 600, 464, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1051), new Integer(anchoringHelper55.getX()), new Integer(anchoringHelper55.getY()), new Integer(anchoringHelper55.getWidth()), new Integer(anchoringHelper55.getHeight()), new Integer(startTabIndex.intValue() + 55), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); } public DynamicGrid dyngrdNow() { return (DynamicGrid)super.getControl(0); } } public static class tabPhlebotomyContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class cmbTimeComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionTime value, String text) { super.control.newRow(value, text); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionTime value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionTime value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionTime value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.ocrr.vo.lookups.SpecimenCollectionTime value) { return super.control.removeRow(value); } public ims.ocrr.vo.lookups.SpecimenCollectionTime getValue() { return (ims.ocrr.vo.lookups.SpecimenCollectionTime)super.control.getValue(); } public void setValue(ims.ocrr.vo.lookups.SpecimenCollectionTime value) { super.control.setValue(value); } } public static class cmbDurationComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.ocrr.vo.lookups.OutPatientDuration value, String text) { super.control.newRow(value, text); } public void newRow(ims.ocrr.vo.lookups.OutPatientDuration value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.ocrr.vo.lookups.OutPatientDuration value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.ocrr.vo.lookups.OutPatientDuration value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.ocrr.vo.lookups.OutPatientDuration value) { return super.control.removeRow(value); } public ims.ocrr.vo.lookups.OutPatientDuration getValue() { return (ims.ocrr.vo.lookups.OutPatientDuration)super.control.getValue(); } public void setValue(ims.ocrr.vo.lookups.OutPatientDuration value) { super.control.setValue(value); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper56 = new RuntimeAnchoring(designSize, runtimeSize, 16, 241, 89, 22, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1052), new Integer(anchoringHelper56.getX()), new Integer(anchoringHelper56.getY()), new Integer(anchoringHelper56.getWidth()), new Integer(anchoringHelper56.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Outpatient", new Integer(1), null, new Integer(1)})); RuntimeAnchoring anchoringHelper57 = new RuntimeAnchoring(designSize, runtimeSize, 16, 10, 78, 22, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1053), new Integer(anchoringHelper57.getX()), new Integer(anchoringHelper57.getY()), new Integer(anchoringHelper57.getWidth()), new Integer(anchoringHelper57.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Inpatient", new Integer(1), null, new Integer(1)})); // Button Controls RuntimeAnchoring anchoringHelper58 = new RuntimeAnchoring(designSize, runtimeSize, 520, 240, 88, 24, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1054), new Integer(anchoringHelper58.getX()), new Integer(anchoringHelper58.getY()), new Integer(anchoringHelper58.getWidth()), new Integer(anchoringHelper58.getHeight()), new Integer(startTabIndex.intValue() + 62), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Apply", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper59 = new RuntimeAnchoring(designSize, runtimeSize, 520, 6, 88, 24, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1055), new Integer(anchoringHelper59.getX()), new Integer(anchoringHelper59.getY()), new Integer(anchoringHelper59.getWidth()), new Integer(anchoringHelper59.getHeight()), new Integer(startTabIndex.intValue() + 58), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Apply", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // Date Controls RuntimeAnchoring anchoringHelper60 = new RuntimeAnchoring(designSize, runtimeSize, 248, 8, 112, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1056), new Integer(anchoringHelper60.getX()), new Integer(anchoringHelper60.getY()), new Integer(anchoringHelper60.getWidth()), new Integer(anchoringHelper60.getHeight()), new Integer(startTabIndex.intValue() + 56), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, null, Boolean.TRUE, null, Boolean.FALSE, "Please select Date"})); // ComboBox Controls RuntimeAnchoring anchoringHelper61 = new RuntimeAnchoring(designSize, runtimeSize, 368, 8, 144, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); ComboBox m_cmbTimeTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1057), new Integer(anchoringHelper61.getX()), new Integer(anchoringHelper61.getY()), new Integer(anchoringHelper61.getWidth()), new Integer(anchoringHelper61.getHeight()), new Integer(startTabIndex.intValue() + 57), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), "Please select Round", Boolean.FALSE, new Integer(-1)}); addControl(m_cmbTimeTemp); cmbTimeComboBox cmbTime = (cmbTimeComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbTimeComboBox.class, m_cmbTimeTemp); super.addComboBox(cmbTime); RuntimeAnchoring anchoringHelper62 = new RuntimeAnchoring(designSize, runtimeSize, 368, 242, 144, 20, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); ComboBox m_cmbDurationTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1058), new Integer(anchoringHelper62.getX()), new Integer(anchoringHelper62.getY()), new Integer(anchoringHelper62.getWidth()), new Integer(anchoringHelper62.getHeight()), new Integer(startTabIndex.intValue() + 61), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), "Please select Period", Boolean.FALSE, new Integer(-1)}); addControl(m_cmbDurationTemp); cmbDurationComboBox cmbDuration = (cmbDurationComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbDurationComboBox.class, m_cmbDurationTemp); super.addComboBox(cmbDuration); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper63 = new RuntimeAnchoring(designSize, runtimeSize, 8, 272, 600, 192, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1059), new Integer(anchoringHelper63.getX()), new Integer(anchoringHelper63.getY()), new Integer(anchoringHelper63.getWidth()), new Integer(anchoringHelper63.getHeight()), new Integer(startTabIndex.intValue() + 63), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); RuntimeAnchoring anchoringHelper64 = new RuntimeAnchoring(designSize, runtimeSize, 8, 40, 600, 192, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1060), new Integer(anchoringHelper64.getX()), new Integer(anchoringHelper64.getY()), new Integer(anchoringHelper64.getWidth()), new Integer(anchoringHelper64.getHeight()), new Integer(startTabIndex.intValue() + 59), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); // IntBox Controls RuntimeAnchoring anchoringHelper65 = new RuntimeAnchoring(designSize, runtimeSize, 248, 242, 112, 21, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(IntBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1061), new Integer(anchoringHelper65.getX()), new Integer(anchoringHelper65.getY()), new Integer(anchoringHelper65.getWidth()), new Integer(anchoringHelper65.getHeight()), new Integer(startTabIndex.intValue() + 60), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT,Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null, "Please enter Number", Boolean.FALSE, new Integer(3)})); } public Button btnApplyPhlenbOutPat() { return (Button)super.getControl(2); } public Button btnApplyPhlebInpat() { return (Button)super.getControl(3); } public DateControl dteCollect() { return (DateControl)super.getControl(4); } public cmbTimeComboBox cmbTime() { return (cmbTimeComboBox)super.getComboBox(0); } public cmbDurationComboBox cmbDuration() { return (cmbDurationComboBox)super.getComboBox(1); } public DynamicGrid dyngrdOutPat() { return (DynamicGrid)super.getControl(7); } public DynamicGrid dyngrdInpat() { return (DynamicGrid)super.getControl(8); } public IntBox intDuration() { return (IntBox)super.getControl(9); } } public static class tabPatientContainer extends LayerBridge { private static final long serialVersionUID = 1L; protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper66 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 600, 464, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1062), new Integer(anchoringHelper66.getX()), new Integer(anchoringHelper66.getY()), new Integer(anchoringHelper66.getWidth()), new Integer(anchoringHelper66.getHeight()), new Integer(startTabIndex.intValue() + 64), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); } public DynamicGrid dyngrdPatient() { return (DynamicGrid)super.getControl(0); } } public static class tabOtherContainer extends LayerBridge { private static final long serialVersionUID = 1L; public static class cmbRequestedTypeOtherComboBox extends ComboBoxBridge { private static final long serialVersionUID = 1L; public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionMethod value, String text) { super.control.newRow(value, text); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionMethod value, String text, ims.framework.utils.Image image) { super.control.newRow(value, text, image); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionMethod value, String text, ims.framework.utils.Color textColor) { super.control.newRow(value, text, textColor); } public void newRow(ims.ocrr.vo.lookups.SpecimenCollectionMethod value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor) { super.control.newRow(value, text, image, textColor); } public boolean removeRow(ims.ocrr.vo.lookups.SpecimenCollectionMethod value) { return super.control.removeRow(value); } public ims.ocrr.vo.lookups.SpecimenCollectionMethod getValue() { return (ims.ocrr.vo.lookups.SpecimenCollectionMethod)super.control.getValue(); } public void setValue(ims.ocrr.vo.lookups.SpecimenCollectionMethod value) { super.control.setValue(value); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper67 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 65, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1063), new Integer(anchoringHelper67.getX()), new Integer(anchoringHelper67.getY()), new Integer(anchoringHelper67.getWidth()), new Integer(anchoringHelper67.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Collection:", new Integer(1), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper68 = new RuntimeAnchoring(designSize, runtimeSize, 512, 8, 88, 24, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1064), new Integer(anchoringHelper68.getX()), new Integer(anchoringHelper68.getY()), new Integer(anchoringHelper68.getWidth()), new Integer(anchoringHelper68.getHeight()), new Integer(startTabIndex.intValue() + 68), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Apply", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // Date Controls RuntimeAnchoring anchoringHelper69 = new RuntimeAnchoring(designSize, runtimeSize, 296, 8, 120, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1065), new Integer(anchoringHelper69.getX()), new Integer(anchoringHelper69.getY()), new Integer(anchoringHelper69.getWidth()), new Integer(anchoringHelper69.getHeight()), new Integer(startTabIndex.intValue() + 66), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.FALSE, null})); // ComboBox Controls RuntimeAnchoring anchoringHelper70 = new RuntimeAnchoring(designSize, runtimeSize, 80, 8, 192, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT); ComboBox m_cmbRequestedTypeOtherTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1066), new Integer(anchoringHelper70.getX()), new Integer(anchoringHelper70.getY()), new Integer(anchoringHelper70.getWidth()), new Integer(anchoringHelper70.getHeight()), new Integer(startTabIndex.intValue() + 65), ControlState.UNKNOWN, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)}); addControl(m_cmbRequestedTypeOtherTemp); cmbRequestedTypeOtherComboBox cmbRequestedTypeOther = (cmbRequestedTypeOtherComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbRequestedTypeOtherComboBox.class, m_cmbRequestedTypeOtherTemp); super.addComboBox(cmbRequestedTypeOther); // Time Controls RuntimeAnchoring anchoringHelper71 = new RuntimeAnchoring(designSize, runtimeSize, 424, 8, 48, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(TimeControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1067), new Integer(anchoringHelper71.getX()), new Integer(anchoringHelper71.getY()), new Integer(anchoringHelper71.getWidth()), new Integer(anchoringHelper71.getHeight()), new Integer(startTabIndex.intValue() + 67), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, Boolean.FALSE, null, Boolean.FALSE, ""})); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper72 = new RuntimeAnchoring(designSize, runtimeSize, 8, 40, 600, 432, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1068), new Integer(anchoringHelper72.getX()), new Integer(anchoringHelper72.getY()), new Integer(anchoringHelper72.getWidth()), new Integer(anchoringHelper72.getHeight()), new Integer(startTabIndex.intValue() + 70), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); } public Button btnApplyOther() { return (Button)super.getControl(1); } public DateControl dteCollectOther() { return (DateControl)super.getControl(2); } public cmbRequestedTypeOtherComboBox cmbRequestedTypeOther() { return (cmbRequestedTypeOtherComboBox)super.getComboBox(0); } public TimeControl timCollectOther() { return (TimeControl)super.getControl(4); } public DynamicGrid dyngrdOther() { return (DynamicGrid)super.getControl(5); } } public static class tabSpecAlreadyCollectedContainer extends LayerBridge { private static final long serialVersionUID = 1L; protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Label Controls RuntimeAnchoring anchoringHelper73 = new RuntimeAnchoring(designSize, runtimeSize, 96, 9, 188, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1069), new Integer(anchoringHelper73.getX()), new Integer(anchoringHelper73.getY()), new Integer(anchoringHelper73.getWidth()), new Integer(anchoringHelper73.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Specimen Collection Date/Time:", new Integer(1), null, new Integer(0)})); // Button Controls RuntimeAnchoring anchoringHelper74 = new RuntimeAnchoring(designSize, runtimeSize, 516, 7, 88, 24, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1070), new Integer(anchoringHelper74.getX()), new Integer(anchoringHelper74.getY()), new Integer(anchoringHelper74.getWidth()), new Integer(anchoringHelper74.getHeight()), new Integer(startTabIndex.intValue() + 73), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Apply", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // Date Controls RuntimeAnchoring anchoringHelper75 = new RuntimeAnchoring(designSize, runtimeSize, 300, 7, 120, 20, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1071), new Integer(anchoringHelper75.getX()), new Integer(anchoringHelper75.getY()), new Integer(anchoringHelper75.getWidth()), new Integer(anchoringHelper75.getHeight()), new Integer(startTabIndex.intValue() + 71), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.FALSE, null})); // Time Controls RuntimeAnchoring anchoringHelper76 = new RuntimeAnchoring(designSize, runtimeSize, 428, 7, 48, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(TimeControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1072), new Integer(anchoringHelper76.getX()), new Integer(anchoringHelper76.getY()), new Integer(anchoringHelper76.getWidth()), new Integer(anchoringHelper76.getHeight()), new Integer(startTabIndex.intValue() + 72), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, Boolean.FALSE, null, Boolean.FALSE, ""})); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper77 = new RuntimeAnchoring(designSize, runtimeSize, 12, 39, 600, 432, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1073), new Integer(anchoringHelper77.getX()), new Integer(anchoringHelper77.getY()), new Integer(anchoringHelper77.getWidth()), new Integer(anchoringHelper77.getHeight()), new Integer(startTabIndex.intValue() + 74), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE})); } public Button btnApplySpecAlreadyCollected() { return (Button)super.getControl(1); } public DateControl dteSpecAlreadyCollected() { return (DateControl)super.getControl(2); } public TimeControl timSpecAlreadyCollected() { return (TimeControl)super.getControl(3); } public DynamicGrid dyngrdSpecAlreadyCollected() { return (DynamicGrid)super.getControl(4); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); RuntimeAnchoring anchoringHelper78 = new RuntimeAnchoring(designSize, runtimeSize, 0, 8, 632, 504, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabRequestedTests = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1074), new Integer(anchoringHelper78.getX()), new Integer(anchoringHelper78.getY()), new Integer(anchoringHelper78.getWidth()), new Integer(anchoringHelper78.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Requested Investigations", new Integer(startControlID.intValue() + -1), new Boolean(true), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabRequestedTestsContainer m_tabRequestedTestsContainer = (tabRequestedTestsContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabRequestedTestsContainer.class, m_tabRequestedTests, factory); super.addContainer(m_tabRequestedTests, m_tabRequestedTestsContainer); ims.framework.utils.SizeInfo m_tabRequestedTestsDesignSize = new ims.framework.utils.SizeInfo(632, 504); ims.framework.utils.SizeInfo m_tabRequestedTestsRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper78.getWidth(), anchoringHelper78.getHeight()); m_tabRequestedTestsContainer.setContext(form, appForm, m_tabRequestedTests, loader, form_images_local, contextMenus, startControlID, m_tabRequestedTestsDesignSize, m_tabRequestedTestsRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper79 = new RuntimeAnchoring(designSize, runtimeSize, 0, 8, 632, 504, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabNow = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1075), new Integer(anchoringHelper79.getX()), new Integer(anchoringHelper79.getY()), new Integer(anchoringHelper79.getWidth()), new Integer(anchoringHelper79.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Now", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabNowContainer m_tabNowContainer = (tabNowContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabNowContainer.class, m_tabNow, factory); super.addContainer(m_tabNow, m_tabNowContainer); ims.framework.utils.SizeInfo m_tabNowDesignSize = new ims.framework.utils.SizeInfo(632, 504); ims.framework.utils.SizeInfo m_tabNowRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper79.getWidth(), anchoringHelper79.getHeight()); m_tabNowContainer.setContext(form, appForm, m_tabNow, loader, form_images_local, contextMenus, startControlID, m_tabNowDesignSize, m_tabNowRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper80 = new RuntimeAnchoring(designSize, runtimeSize, 0, 8, 632, 504, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabPhlebotomy = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1076), new Integer(anchoringHelper80.getX()), new Integer(anchoringHelper80.getY()), new Integer(anchoringHelper80.getWidth()), new Integer(anchoringHelper80.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Phlebotomy/Specimen Collection", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabPhlebotomyContainer m_tabPhlebotomyContainer = (tabPhlebotomyContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabPhlebotomyContainer.class, m_tabPhlebotomy, factory); super.addContainer(m_tabPhlebotomy, m_tabPhlebotomyContainer); ims.framework.utils.SizeInfo m_tabPhlebotomyDesignSize = new ims.framework.utils.SizeInfo(632, 504); ims.framework.utils.SizeInfo m_tabPhlebotomyRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper80.getWidth(), anchoringHelper80.getHeight()); m_tabPhlebotomyContainer.setContext(form, appForm, m_tabPhlebotomy, loader, form_images_local, contextMenus, startControlID, m_tabPhlebotomyDesignSize, m_tabPhlebotomyRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper81 = new RuntimeAnchoring(designSize, runtimeSize, 0, 8, 632, 504, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabPatient = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1077), new Integer(anchoringHelper81.getX()), new Integer(anchoringHelper81.getY()), new Integer(anchoringHelper81.getWidth()), new Integer(anchoringHelper81.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Patient", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabPatientContainer m_tabPatientContainer = (tabPatientContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabPatientContainer.class, m_tabPatient, factory); super.addContainer(m_tabPatient, m_tabPatientContainer); ims.framework.utils.SizeInfo m_tabPatientDesignSize = new ims.framework.utils.SizeInfo(632, 504); ims.framework.utils.SizeInfo m_tabPatientRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper81.getWidth(), anchoringHelper81.getHeight()); m_tabPatientContainer.setContext(form, appForm, m_tabPatient, loader, form_images_local, contextMenus, startControlID, m_tabPatientDesignSize, m_tabPatientRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper82 = new RuntimeAnchoring(designSize, runtimeSize, 0, 8, 632, 504, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabOther = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1078), new Integer(anchoringHelper82.getX()), new Integer(anchoringHelper82.getY()), new Integer(anchoringHelper82.getWidth()), new Integer(anchoringHelper82.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Other", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabOtherContainer m_tabOtherContainer = (tabOtherContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabOtherContainer.class, m_tabOther, factory); super.addContainer(m_tabOther, m_tabOtherContainer); ims.framework.utils.SizeInfo m_tabOtherDesignSize = new ims.framework.utils.SizeInfo(632, 504); ims.framework.utils.SizeInfo m_tabOtherRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper82.getWidth(), anchoringHelper82.getHeight()); m_tabOtherContainer.setContext(form, appForm, m_tabOther, loader, form_images_local, contextMenus, startControlID, m_tabOtherDesignSize, m_tabOtherRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper83 = new RuntimeAnchoring(designSize, runtimeSize, 0, 8, 632, 504, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabSpecAlreadyCollected = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1079), new Integer(anchoringHelper83.getX()), new Integer(anchoringHelper83.getY()), new Integer(anchoringHelper83.getWidth()), new Integer(anchoringHelper83.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Specimen Already Collected", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabSpecAlreadyCollectedContainer m_tabSpecAlreadyCollectedContainer = (tabSpecAlreadyCollectedContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabSpecAlreadyCollectedContainer.class, m_tabSpecAlreadyCollected, factory); super.addContainer(m_tabSpecAlreadyCollected, m_tabSpecAlreadyCollectedContainer); ims.framework.utils.SizeInfo m_tabSpecAlreadyCollectedDesignSize = new ims.framework.utils.SizeInfo(632, 504); ims.framework.utils.SizeInfo m_tabSpecAlreadyCollectedRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper83.getWidth(), anchoringHelper83.getHeight()); m_tabSpecAlreadyCollectedContainer.setContext(form, appForm, m_tabSpecAlreadyCollected, loader, form_images_local, contextMenus, startControlID, m_tabSpecAlreadyCollectedDesignSize, m_tabSpecAlreadyCollectedRuntimeSize, startTabIndex, skipContextValidation); } public void hide() { tabRequestedTests().setVisible(false); tabNow().setVisible(false); tabPhlebotomy().setVisible(false); tabPatient().setVisible(false); tabOther().setVisible(false); tabSpecAlreadyCollected().setVisible(false); } public void showtabRequestedTests() { tabNow().setVisible(false); tabPhlebotomy().setVisible(false); tabPatient().setVisible(false); tabOther().setVisible(false); tabSpecAlreadyCollected().setVisible(false); tabRequestedTests().setVisible(true); } public void showtabNow() { tabRequestedTests().setVisible(false); tabPhlebotomy().setVisible(false); tabPatient().setVisible(false); tabOther().setVisible(false); tabSpecAlreadyCollected().setVisible(false); tabNow().setVisible(true); } public void showtabPhlebotomy() { tabRequestedTests().setVisible(false); tabNow().setVisible(false); tabPatient().setVisible(false); tabOther().setVisible(false); tabSpecAlreadyCollected().setVisible(false); tabPhlebotomy().setVisible(true); } public void showtabPatient() { tabRequestedTests().setVisible(false); tabNow().setVisible(false); tabPhlebotomy().setVisible(false); tabOther().setVisible(false); tabSpecAlreadyCollected().setVisible(false); tabPatient().setVisible(true); } public void showtabOther() { tabRequestedTests().setVisible(false); tabNow().setVisible(false); tabPhlebotomy().setVisible(false); tabPatient().setVisible(false); tabSpecAlreadyCollected().setVisible(false); tabOther().setVisible(true); } public void showtabSpecAlreadyCollected() { tabRequestedTests().setVisible(false); tabNow().setVisible(false); tabPhlebotomy().setVisible(false); tabPatient().setVisible(false); tabOther().setVisible(false); tabSpecAlreadyCollected().setVisible(true); } public tabRequestedTestsContainer tabRequestedTests() { return (tabRequestedTestsContainer)super.layers.get(0); } public tabNowContainer tabNow() { return (tabNowContainer)super.layers.get(1); } public tabPhlebotomyContainer tabPhlebotomy() { return (tabPhlebotomyContainer)super.layers.get(2); } public tabPatientContainer tabPatient() { return (tabPatientContainer)super.layers.get(3); } public tabOtherContainer tabOther() { return (tabOtherContainer)super.layers.get(4); } public tabSpecAlreadyCollectedContainer tabSpecAlreadyCollected() { return (tabSpecAlreadyCollectedContainer)super.layers.get(5); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); // Layer Clasess lyrPathologyLayer m_lyrPathologyLayer = (lyrPathologyLayer)LayerFlyweightFactory.getInstance().createLayer(lyrPathologyLayer.class, this, factory); super.addLayer(m_lyrPathologyLayer); m_lyrPathologyLayer.setContext(form, appForm, control, loader, form_images_local, contextMenus, startControlID, designSize, runtimeSize, startTabIndex, skipContextValidation); // Button Controls RuntimeAnchoring anchoringHelper84 = new RuntimeAnchoring(designSize, runtimeSize, 512, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1080), new Integer(anchoringHelper84.getX()), new Integer(anchoringHelper84.getY()), new Integer(anchoringHelper84.getWidth()), new Integer(anchoringHelper84.getHeight()), new Integer(startTabIndex.intValue() + 76), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Next >>", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper85 = new RuntimeAnchoring(designSize, runtimeSize, 8, 520, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1081), new Integer(anchoringHelper85.getX()), new Integer(anchoringHelper85.getY()), new Integer(anchoringHelper85.getWidth()), new Integer(anchoringHelper85.getHeight()), new Integer(startTabIndex.intValue() + 75), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "<< Previous", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); } public lyrPathologyLayer lyrPathology() { return (lyrPathologyLayer)super.getLayer(0); } public Button btnGenerateSpecimens() { return (Button)super.getControl(6); } public Button btnPreviousPathology() { return (Button)super.getControl(7); } } protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception { if(form == null) throw new RuntimeException("Invalid form"); if(appForm == null) throw new RuntimeException("Invalid application form"); if(control == null); // this is to avoid eclipse warning only. if(loader == null); // this is to avoid eclipse warning only. if(form_images_local == null); // this is to avoid eclipse warning only. if(contextMenus == null); // this is to avoid eclipse warning only. if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(designSize == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); RuntimeAnchoring anchoringHelper86 = new RuntimeAnchoring(designSize, runtimeSize, 192, 16, 640, 576, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabClinicalNotes = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1082), new Integer(anchoringHelper86.getX()), new Integer(anchoringHelper86.getY()), new Integer(anchoringHelper86.getWidth()), new Integer(anchoringHelper86.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Clinical Details", new Integer(startControlID.intValue() + -1), new Boolean(true), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabClinicalNotesContainer m_tabClinicalNotesContainer = (tabClinicalNotesContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabClinicalNotesContainer.class, m_tabClinicalNotes, factory); super.addContainer(m_tabClinicalNotes, m_tabClinicalNotesContainer); ims.framework.utils.SizeInfo m_tabClinicalNotesDesignSize = new ims.framework.utils.SizeInfo(640, 576); ims.framework.utils.SizeInfo m_tabClinicalNotesRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper86.getWidth(), anchoringHelper86.getHeight()); m_tabClinicalNotesContainer.setContext(form, appForm, m_tabClinicalNotes, loader, form_images_local, contextMenus, startControlID, m_tabClinicalNotesDesignSize, m_tabClinicalNotesRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper87 = new RuntimeAnchoring(designSize, runtimeSize, 192, 16, 640, 576, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabSummaryClinicalInfo = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1083), new Integer(anchoringHelper87.getX()), new Integer(anchoringHelper87.getY()), new Integer(anchoringHelper87.getWidth()), new Integer(anchoringHelper87.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Summary Clinical Information", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabSummaryClinicalInfoContainer m_tabSummaryClinicalInfoContainer = (tabSummaryClinicalInfoContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabSummaryClinicalInfoContainer.class, m_tabSummaryClinicalInfo, factory); super.addContainer(m_tabSummaryClinicalInfo, m_tabSummaryClinicalInfoContainer); ims.framework.utils.SizeInfo m_tabSummaryClinicalInfoDesignSize = new ims.framework.utils.SizeInfo(640, 576); ims.framework.utils.SizeInfo m_tabSummaryClinicalInfoRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper87.getWidth(), anchoringHelper87.getHeight()); m_tabSummaryClinicalInfoContainer.setContext(form, appForm, m_tabSummaryClinicalInfo, loader, form_images_local, contextMenus, startControlID, m_tabSummaryClinicalInfoDesignSize, m_tabSummaryClinicalInfoRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper88 = new RuntimeAnchoring(designSize, runtimeSize, 192, 16, 640, 576, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabGenDetails = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1084), new Integer(anchoringHelper88.getX()), new Integer(anchoringHelper88.getY()), new Integer(anchoringHelper88.getWidth()), new Integer(anchoringHelper88.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"General Order Details", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabGenDetailsContainer m_tabGenDetailsContainer = (tabGenDetailsContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabGenDetailsContainer.class, m_tabGenDetails, factory); super.addContainer(m_tabGenDetails, m_tabGenDetailsContainer); ims.framework.utils.SizeInfo m_tabGenDetailsDesignSize = new ims.framework.utils.SizeInfo(640, 576); ims.framework.utils.SizeInfo m_tabGenDetailsRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper88.getWidth(), anchoringHelper88.getHeight()); m_tabGenDetailsContainer.setContext(form, appForm, m_tabGenDetails, loader, form_images_local, contextMenus, startControlID, m_tabGenDetailsDesignSize, m_tabGenDetailsRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper89 = new RuntimeAnchoring(designSize, runtimeSize, 192, 16, 640, 576, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabRadDetails = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1085), new Integer(anchoringHelper89.getX()), new Integer(anchoringHelper89.getY()), new Integer(anchoringHelper89.getWidth()), new Integer(anchoringHelper89.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Radiology Details", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabRadDetailsContainer m_tabRadDetailsContainer = (tabRadDetailsContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabRadDetailsContainer.class, m_tabRadDetails, factory); super.addContainer(m_tabRadDetails, m_tabRadDetailsContainer); ims.framework.utils.SizeInfo m_tabRadDetailsDesignSize = new ims.framework.utils.SizeInfo(640, 576); ims.framework.utils.SizeInfo m_tabRadDetailsRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper89.getWidth(), anchoringHelper89.getHeight()); m_tabRadDetailsContainer.setContext(form, appForm, m_tabRadDetails, loader, form_images_local, contextMenus, startControlID, m_tabRadDetailsDesignSize, m_tabRadDetailsRuntimeSize, startTabIndex, skipContextValidation); RuntimeAnchoring anchoringHelper90 = new RuntimeAnchoring(designSize, runtimeSize, 192, 16, 640, 576, ims.framework.enumerations.ControlAnchoring.ALL); Container m_tabPathDetails = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1086), new Integer(anchoringHelper90.getX()), new Integer(anchoringHelper90.getY()), new Integer(anchoringHelper90.getWidth()), new Integer(anchoringHelper90.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Pathology Specimen Details", new Integer(startControlID.intValue() + -1), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(false)}); tabPathDetailsContainer m_tabPathDetailsContainer = (tabPathDetailsContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabPathDetailsContainer.class, m_tabPathDetails, factory); super.addContainer(m_tabPathDetails, m_tabPathDetailsContainer); ims.framework.utils.SizeInfo m_tabPathDetailsDesignSize = new ims.framework.utils.SizeInfo(640, 576); ims.framework.utils.SizeInfo m_tabPathDetailsRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper90.getWidth(), anchoringHelper90.getHeight()); m_tabPathDetailsContainer.setContext(form, appForm, m_tabPathDetails, loader, form_images_local, contextMenus, startControlID, m_tabPathDetailsDesignSize, m_tabPathDetailsRuntimeSize, startTabIndex, skipContextValidation); } public void hide() { tabClinicalNotes().setVisible(false); tabSummaryClinicalInfo().setVisible(false); tabGenDetails().setVisible(false); tabRadDetails().setVisible(false); tabPathDetails().setVisible(false); } public void showtabClinicalNotes() { tabSummaryClinicalInfo().setVisible(false); tabGenDetails().setVisible(false); tabRadDetails().setVisible(false); tabPathDetails().setVisible(false); tabClinicalNotes().setVisible(true); } public void showtabSummaryClinicalInfo() { tabClinicalNotes().setVisible(false); tabGenDetails().setVisible(false); tabRadDetails().setVisible(false); tabPathDetails().setVisible(false); tabSummaryClinicalInfo().setVisible(true); } public void showtabGenDetails() { tabClinicalNotes().setVisible(false); tabSummaryClinicalInfo().setVisible(false); tabRadDetails().setVisible(false); tabPathDetails().setVisible(false); tabGenDetails().setVisible(true); } public void showtabRadDetails() { tabClinicalNotes().setVisible(false); tabSummaryClinicalInfo().setVisible(false); tabGenDetails().setVisible(false); tabPathDetails().setVisible(false); tabRadDetails().setVisible(true); } public void showtabPathDetails() { tabClinicalNotes().setVisible(false); tabSummaryClinicalInfo().setVisible(false); tabGenDetails().setVisible(false); tabRadDetails().setVisible(false); tabPathDetails().setVisible(true); } public tabClinicalNotesContainer tabClinicalNotes() { return (tabClinicalNotesContainer)super.layers.get(0); } public tabSummaryClinicalInfoContainer tabSummaryClinicalInfo() { return (tabSummaryClinicalInfoContainer)super.layers.get(1); } public tabGenDetailsContainer tabGenDetails() { return (tabGenDetailsContainer)super.layers.get(2); } public tabRadDetailsContainer tabRadDetails() { return (tabRadDetailsContainer)super.layers.get(3); } public tabPathDetailsContainer tabPathDetails() { return (tabPathDetailsContainer)super.layers.get(4); } } private void validateContext(ims.framework.Context context) { if(context == null) return; if(!context.isValidContextType(ims.core.vo.CareContextShortVo.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.CareContextShortVo' of the global context variable 'Core.CurrentCareContext' is not supported."); if(!context.isValidContextType(ims.core.vo.ClinicalContactShortVo.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.ClinicalContactShortVo' of the global context variable 'Core.CurrentClinicalContact' is not supported."); if(!context.isValidContextType(ims.core.vo.PatientShort.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.PatientShort' of the global context variable 'Core.PatientShort' is not supported."); if(!context.isValidContextType(ims.RefMan.vo.CatsReferralRefVo.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.RefMan.vo.CatsReferralRefVo' of the global context variable 'RefMan.CatsReferral' is not supported."); if(!context.isValidContextType(ims.ocrr.vo.RoleDisciplineSecurityLevelLiteGCVo.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.ocrr.vo.RoleDisciplineSecurityLevelLiteGCVo' of the global context variable 'OCRR.RoleDisciplineSecurityLevels' is not supported."); if(!context.isValidContextType(FormName.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'FormName' of the global context variable 'Core.SelectingPatientForm' is not supported."); } private void validateMandatoryContext(Context context) { if(new ims.framework.ContextVariable("Core.PatientShort", "_cvp_Core.PatientShort").getValueIsNull(context)) throw new ims.framework.exceptions.FormMandatoryContextMissingException("The required context data 'Core.PatientShort' is not available."); } public boolean supportsRecordedInError() { return false; } public ims.vo.ValueObject getRecordedInErrorVo() { return null; } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception { setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception { setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception { if(loader == null); // this is to avoid eclipse warning only. if(factory == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(appForm == null) throw new RuntimeException("Invalid application form"); if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(control == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); this.context = context; this.componentIdentifier = startControlID.toString(); this.formInfo = form.getFormInfo(); this.globalContext = new GlobalContext(context); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { validateContext(context); validateMandatoryContext(context); } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(848, 632); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); super.setFormReferences(FormReferencesFlyweightFactory.getInstance().create(Forms.class)); super.setImageReferences(ImageReferencesFlyweightFactory.getInstance().create(Images.class)); super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false)); super.setLocalContext(new LocalContext(context, form.getFormInfo(), componentIdentifier)); // Context Menus contextMenus = new ContextMenus(); contextMenus.contextMenuOCRRMyOrderAddInvestigation = factory.createMenu(startControlID.intValue() + 1); contextMenus.contextMenuOCRRMyOrderAddInvestigationADDINVESTIGATIONItem = factory.createMenuItem(startControlID.intValue() + 1, "Add Investigation", true, false, new Integer(116105), true, false); contextMenus.contextMenuOCRRMyOrderAddInvestigation.add(contextMenus.contextMenuOCRRMyOrderAddInvestigationADDINVESTIGATIONItem); contextMenus.contextMenuOCRRMyOrderAddInvestigationREMOVEINVESTIGATIONItem = factory.createMenuItem(startControlID.intValue() + 2, "Remove Investigation", true, false, new Integer(102148), true, false); contextMenus.contextMenuOCRRMyOrderAddInvestigation.add(contextMenus.contextMenuOCRRMyOrderAddInvestigationREMOVEINVESTIGATIONItem); form.registerMenu(contextMenus.contextMenuOCRRMyOrderAddInvestigation); contextMenus.contextMenuOCRRMyOrderReportTo = factory.createMenu(startControlID.intValue() + 2); contextMenus.contextMenuOCRRMyOrderReportToADDMOSItem = factory.createMenuItem(startControlID.intValue() + 3, "Add Member of Staff", true, false, new Integer(103141), true, false); contextMenus.contextMenuOCRRMyOrderReportTo.add(contextMenus.contextMenuOCRRMyOrderReportToADDMOSItem); contextMenus.contextMenuOCRRMyOrderReportToADDGPItem = factory.createMenuItem(startControlID.intValue() + 4, "Add GP", true, false, new Integer(103139), true, false); contextMenus.contextMenuOCRRMyOrderReportTo.add(contextMenus.contextMenuOCRRMyOrderReportToADDGPItem); contextMenus.contextMenuOCRRMyOrderReportToAddItem = factory.createMenuItem(startControlID.intValue() + 5, "Add Other", true, false, new Integer(102149), true, false); contextMenus.contextMenuOCRRMyOrderReportTo.add(contextMenus.contextMenuOCRRMyOrderReportToAddItem); contextMenus.contextMenuOCRRMyOrderReportToRemoveItem = factory.createMenuItem(startControlID.intValue() + 6, "Remove", true, false, new Integer(102148), true, false); contextMenus.contextMenuOCRRMyOrderReportTo.add(contextMenus.contextMenuOCRRMyOrderReportToRemoveItem); contextMenus.contextMenuOCRRMyOrderReportToADDWARDItem = factory.createMenuItem(startControlID.intValue() + 7, "Add Ward", true, false, new Integer(103111), true, false); contextMenus.contextMenuOCRRMyOrderReportTo.add(contextMenus.contextMenuOCRRMyOrderReportToADDWARDItem); contextMenus.contextMenuOCRRMyOrderReportToADDOUTPATItem = factory.createMenuItem(startControlID.intValue() + 8, "Add Outpatient Dept", true, false, new Integer(102182), true, false); contextMenus.contextMenuOCRRMyOrderReportTo.add(contextMenus.contextMenuOCRRMyOrderReportToADDOUTPATItem); form.registerMenu(contextMenus.contextMenuOCRRMyOrderReportTo); contextMenus.contextMenuSelectItems = factory.createMenu(startControlID.intValue() + 3); contextMenus.contextMenuSelectItemsSELECTItem = factory.createMenuItem(startControlID.intValue() + 9, "Site Selection", true, false, new Integer(103108), true, false); contextMenus.contextMenuSelectItems.add(contextMenus.contextMenuSelectItemsSELECTItem); contextMenus.contextMenuSelectItemsLINKItem = factory.createMenuItem(startControlID.intValue() + 10, "Link Add Ons", true, false, new Integer(101128), true, false); contextMenus.contextMenuSelectItems.add(contextMenus.contextMenuSelectItemsLINKItem); form.registerMenu(contextMenus.contextMenuSelectItems); // Layer Clasess lyrDetailsLayer m_lyrDetailsLayer = (lyrDetailsLayer)LayerFlyweightFactory.getInstance().createLayer(lyrDetailsLayer.class, this, factory); super.addLayer(m_lyrDetailsLayer); m_lyrDetailsLayer.setContext(form, appForm, control, loader, this.getImages(), contextMenus, startControlID, designSize, runtimeSize, startTabIndex, skipContextValidation); // Button Controls RuntimeAnchoring anchoringHelper91 = new RuntimeAnchoring(designSize, runtimeSize, 192, 600, 528, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1087), new Integer(anchoringHelper91.getX()), new Integer(anchoringHelper91.getY()), new Integer(anchoringHelper91.getWidth()), new Integer(anchoringHelper91.getHeight()), new Integer(startTabIndex.intValue() + 77), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Order", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper92 = new RuntimeAnchoring(designSize, runtimeSize, 728, 600, 104, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1088), new Integer(anchoringHelper92.getX()), new Integer(anchoringHelper92.getY()), new Integer(anchoringHelper92.getWidth()), new Integer(anchoringHelper92.getHeight()), new Integer(startTabIndex.intValue() + 78), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // Tree Controls RuntimeAnchoring anchoringHelper93 = new RuntimeAnchoring(designSize, runtimeSize, 16, 16, 168, 576, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT); super.addControl(factory.getControl(TreeView.class, new Object[] { control, new Integer(startControlID.intValue() + 1089), new Integer(anchoringHelper93.getX()), new Integer(anchoringHelper93.getY()), new Integer(anchoringHelper93.getWidth()), new Integer(anchoringHelper93.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.ENABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMLEFT,Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, contextMenus.contextMenuOCRRMyOrderAddInvestigation, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE})); } public Forms getForms() { return (Forms)super.getFormReferences(); } public Images getImages() { return (Images)super.getImageReferences(); } public lyrDetailsLayer lyrDetails() { return (lyrDetailsLayer)super.getLayer(0); } public Button btnOrder() { return (Button)super.getControl(5); } public Button btnCancel() { return (Button)super.getControl(6); } public TreeView treeComponents() { return (TreeView)super.getControl(7); } public static class Forms implements java.io.Serializable { private static final long serialVersionUID = 1L; protected final class LocalFormName extends FormName { private static final long serialVersionUID = 1L; private LocalFormName(int name) { super(name); } } private Forms() { OCRR = new OCRRForms(); Core = new CoreForms(); Clinical = new ClinicalForms(); } public final class OCRRForms implements java.io.Serializable { private static final long serialVersionUID = 1L; private OCRRForms() { OrderPriorityDialog = new LocalFormName(116124); SelectandOrder = new LocalFormName(116112); SelectAndOrderDialog = new LocalFormName(116131); OrdersRequiringAuthorisation = new LocalFormName(116140); OrderSummaryDialog = new LocalFormName(116132); PrintOrder = new LocalFormName(116102); ChooseAlternativeContainersDialog = new LocalFormName(116159); MyOrderDialog = new LocalFormName(116137); } public final FormName OrderPriorityDialog; public final FormName SelectandOrder; public final FormName SelectAndOrderDialog; public final FormName OrdersRequiringAuthorisation; public final FormName OrderSummaryDialog; public final FormName PrintOrder; public final FormName ChooseAlternativeContainersDialog; public final FormName MyOrderDialog; } public final class CoreForms implements java.io.Serializable { private static final long serialVersionUID = 1L; private CoreForms() { SelectItems = new LocalFormName(102229); Demographics = new LocalFormName(102101); OutpatientList = new LocalFormName(102230); } public final FormName SelectItems; public final FormName Demographics; public final FormName OutpatientList; } public final class ClinicalForms implements java.io.Serializable { private static final long serialVersionUID = 1L; private ClinicalForms() { ClinicListWithICPActions = new LocalFormName(123155); } public final FormName ClinicListWithICPActions; } public OCRRForms OCRR; public CoreForms Core; public ClinicalForms Clinical; } public static class Images implements java.io.Serializable { private static final long serialVersionUID = 1L; private final class ImageHelper extends ims.framework.utils.ImagePath { private static final long serialVersionUID = 1L; private ImageHelper(int id, String path, Integer width, Integer height) { super(id, path, width, height); } } private Images() { OCRR = new OCRRImages(); Core = new CoreImages(); } public final class OCRRImages implements java.io.Serializable { private static final long serialVersionUID = 1L; private OCRRImages() { Profile = new ImageHelper(116108, "Images/OCRR/Profile.gif", new Integer(16), new Integer(16)); Investigation = new ImageHelper(116105, "Images/OCRR/Investigation.gif", new Integer(16), new Integer(16)); Information = new ImageHelper(116101, "Images/OCRR/Information.gif", new Integer(16), new Integer(16)); Question = new ImageHelper(116100, "Images/OCRR/Question.gif", new Integer(16), new Integer(16)); QuestionCategory = new ImageHelper(116102, "Images/OCRR/QCategory.gif", new Integer(16), new Integer(16)); Label = new ImageHelper(116111, "Images/OCRR/Label.gif", new Integer(16), new Integer(16)); TestTube = new ImageHelper(116118, "Images/OCRR/itesttube.gif", new Integer(19), new Integer(19)); SpecimenDetails16 = new ImageHelper(116147, "Images/OCRR/SpecimenDetails.gif", new Integer(16), new Integer(16)); } public final ims.framework.utils.Image Profile; public final ims.framework.utils.Image Investigation; public final ims.framework.utils.Image Information; public final ims.framework.utils.Image Question; public final ims.framework.utils.Image QuestionCategory; public final ims.framework.utils.Image Label; public final ims.framework.utils.Image TestTube; public final ims.framework.utils.Image SpecimenDetails16; } public final class CoreImages implements java.io.Serializable { private static final long serialVersionUID = 1L; private CoreImages() { Form = new ImageHelper(102258, "Images/Core/Control_Form.gif", new Integer(16), new Integer(16)); MandatoryQuestion = new ImageHelper(102272, "Images/Core/Help4.gif", new Integer(16), new Integer(16)); } public final ims.framework.utils.Image Form; public final ims.framework.utils.Image MandatoryQuestion; } public final OCRRImages OCRR; public final CoreImages Core; } public GlobalContext getGlobalContext() { return this.globalContext; } public static class GlobalContextBridge extends ContextBridge { private static final long serialVersionUID = 1L; } public LocalContext getLocalContext() { return (LocalContext)super.getLocalCtx(); } public class LocalContext extends ContextBridge { private static final long serialVersionUID = 1L; public LocalContext(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { super.setContext(context); String prefix = formInfo.getLocalVariablesPrefix(); cxl_OcsOrder = new ims.framework.ContextVariable("OcsOrder", prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier + ""); cxl_OutpatientDurationLookupCollection = new ims.framework.ContextVariable("OutpatientDurationLookupCollection", prefix + "_lv_OCRR.MyOrder.__internal_x_context__OutpatientDurationLookupCollection_" + componentIdentifier + ""); cxl_SelectedComponents = new ims.framework.ContextVariable("SelectedComponents", prefix + "_lv_OCRR.MyOrder.__internal_x_context__SelectedComponents_" + componentIdentifier + ""); cxl_WorkListItems = new ims.framework.ContextVariable("WorkListItems", prefix + "_lv_OCRR.MyOrder.__internal_x_context__WorkListItems_" + componentIdentifier + ""); cxl_ClosedRounds = new ims.framework.ContextVariable("ClosedRounds", prefix + "_lv_OCRR.MyOrder.__internal_x_context__ClosedRounds_" + componentIdentifier + ""); cxl_UIValidationMessages = new ims.framework.ContextVariable("UIValidationMessages", prefix + "_lv_OCRR.MyOrder.__internal_x_context__UIValidationMessages_" + componentIdentifier + ""); cxl_ContextDummyForReports = new ims.framework.ContextVariable("ContextDummyForReports", prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier + ""); cxl_AddedOrderInvestigations = new ims.framework.ContextVariable("AddedOrderInvestigations", prefix + "_lv_OCRR.MyOrder.__internal_x_context__AddedOrderInvestigations_" + componentIdentifier + ""); cxl_ActiveHospitals = new ims.framework.ContextVariable("ActiveHospitals", prefix + "_lv_OCRR.MyOrder.__internal_x_context__ActiveHospitals_" + componentIdentifier + ""); cxl_PreviousForm = new ims.framework.ContextVariable("PreviousForm", prefix + "_lv_OCRR.MyOrder.__internal_x_context__PreviousForm_" + componentIdentifier + ""); cxl_TestRowBeingModified = new ims.framework.ContextVariable("TestRowBeingModified", prefix + "_lv_OCRR.MyOrder.__internal_x_context__TestRowBeingModified_" + componentIdentifier + ""); cxl_OriginalOrderInvestigationCollection = new ims.framework.ContextVariable("OriginalOrderInvestigationCollection", prefix + "_lv_OCRR.MyOrder.__internal_x_context__OriginalOrderInvestigationCollection_" + componentIdentifier + ""); cxl_InvestigationToAmend = new ims.framework.ContextVariable("InvestigationToAmend", prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier + ""); cxl_DFTCollectionType = new ims.framework.ContextVariable("DFTCollectionType", prefix + "_lv_OCRR.MyOrder.__internal_x_context__DFTCollectionType_" + componentIdentifier + ""); cxl_OrderComponentsRestorePoint = new ims.framework.ContextVariable("OrderComponentsRestorePoint", prefix + "_lv_OCRR.MyOrder.__internal_x_context__OrderComponentsRestorePoint_" + componentIdentifier + ""); } public boolean getOcsOrderIsNotNull() { return !cxl_OcsOrder.getValueIsNull(context); } public ims.ocrr.vo.OcsOrderVo getOcsOrder() { return (ims.ocrr.vo.OcsOrderVo)cxl_OcsOrder.getValue(context); } public void setOcsOrder(ims.ocrr.vo.OcsOrderVo value) { cxl_OcsOrder.setValue(context, value); } private ims.framework.ContextVariable cxl_OcsOrder = null; public boolean getOutpatientDurationLookupCollectionIsNotNull() { return !cxl_OutpatientDurationLookupCollection.getValueIsNull(context); } public ims.ocrr.vo.lookups.OutPatientDurationCollection getOutpatientDurationLookupCollection() { return (ims.ocrr.vo.lookups.OutPatientDurationCollection)cxl_OutpatientDurationLookupCollection.getValue(context); } public void setOutpatientDurationLookupCollection(ims.ocrr.vo.lookups.OutPatientDurationCollection value) { cxl_OutpatientDurationLookupCollection.setValue(context, value); } private ims.framework.ContextVariable cxl_OutpatientDurationLookupCollection = null; public boolean getSelectedComponentsIsNotNull() { return !cxl_SelectedComponents.getValueIsNull(context); } public ims.ocrr.vo.MyOrderComponentVoCollection getSelectedComponents() { return (ims.ocrr.vo.MyOrderComponentVoCollection)cxl_SelectedComponents.getValue(context); } public void setSelectedComponents(ims.ocrr.vo.MyOrderComponentVoCollection value) { cxl_SelectedComponents.setValue(context, value); } private ims.framework.ContextVariable cxl_SelectedComponents = null; public boolean getWorkListItemsIsNotNull() { return !cxl_WorkListItems.getValueIsNull(context); } public ims.ocrr.vo.SpecimenWorkListItemVoCollection getWorkListItems() { return (ims.ocrr.vo.SpecimenWorkListItemVoCollection)cxl_WorkListItems.getValue(context); } public void setWorkListItems(ims.ocrr.vo.SpecimenWorkListItemVoCollection value) { cxl_WorkListItems.setValue(context, value); } private ims.framework.ContextVariable cxl_WorkListItems = null; public boolean getClosedRoundsIsNotNull() { return !cxl_ClosedRounds.getValueIsNull(context); } public ims.ocrr.vo.PhlebotomyRoundShortVoCollection getClosedRounds() { return (ims.ocrr.vo.PhlebotomyRoundShortVoCollection)cxl_ClosedRounds.getValue(context); } public void setClosedRounds(ims.ocrr.vo.PhlebotomyRoundShortVoCollection value) { cxl_ClosedRounds.setValue(context, value); } private ims.framework.ContextVariable cxl_ClosedRounds = null; public boolean getUIValidationMessagesIsNotNull() { return !cxl_UIValidationMessages.getValueIsNull(context); } public java.util.ArrayList<String> getUIValidationMessages() { return (java.util.ArrayList<String>)cxl_UIValidationMessages.getValue(context); } public void setUIValidationMessages(java.util.ArrayList<String> value) { cxl_UIValidationMessages.setValue(context, value); } private ims.framework.ContextVariable cxl_UIValidationMessages = null; public boolean getContextDummyForReportsIsNotNull() { return !cxl_ContextDummyForReports.getValueIsNull(context); } public ims.ocrr.vo.OrderSpecimenVo getContextDummyForReports() { return (ims.ocrr.vo.OrderSpecimenVo)cxl_ContextDummyForReports.getValue(context); } public void setContextDummyForReports(ims.ocrr.vo.OrderSpecimenVo value) { cxl_ContextDummyForReports.setValue(context, value); } private ims.framework.ContextVariable cxl_ContextDummyForReports = null; public boolean getAddedOrderInvestigationsIsNotNull() { return !cxl_AddedOrderInvestigations.getValueIsNull(context); } public ims.ocrr.vo.OrderInvestigationVoCollection getAddedOrderInvestigations() { return (ims.ocrr.vo.OrderInvestigationVoCollection)cxl_AddedOrderInvestigations.getValue(context); } public void setAddedOrderInvestigations(ims.ocrr.vo.OrderInvestigationVoCollection value) { cxl_AddedOrderInvestigations.setValue(context, value); } private ims.framework.ContextVariable cxl_AddedOrderInvestigations = null; public boolean getActiveHospitalsIsNotNull() { return !cxl_ActiveHospitals.getValueIsNull(context); } public ims.core.vo.LocShortMappingsVoCollection getActiveHospitals() { return (ims.core.vo.LocShortMappingsVoCollection)cxl_ActiveHospitals.getValue(context); } public void setActiveHospitals(ims.core.vo.LocShortMappingsVoCollection value) { cxl_ActiveHospitals.setValue(context, value); } private ims.framework.ContextVariable cxl_ActiveHospitals = null; public boolean getPreviousFormIsNotNull() { return !cxl_PreviousForm.getValueIsNull(context); } public ims.framework.FormName getPreviousForm() { return (ims.framework.FormName)cxl_PreviousForm.getValue(context); } public void setPreviousForm(ims.framework.FormName value) { cxl_PreviousForm.setValue(context, value); } private ims.framework.ContextVariable cxl_PreviousForm = null; public boolean getTestRowBeingModifiedIsNotNull() { return !cxl_TestRowBeingModified.getValueIsNull(context); } public GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow getTestRowBeingModified() { return (GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow)cxl_TestRowBeingModified.getValue(context); } public void setTestRowBeingModified(GenForm.lyrDetailsLayer.tabPathDetailsContainer.lyrPathologyLayer.tabRequestedTestsContainer.grdTestRow value) { cxl_TestRowBeingModified.setValue(context, value); } private ims.framework.ContextVariable cxl_TestRowBeingModified = null; public boolean getOriginalOrderInvestigationCollectionIsNotNull() { return !cxl_OriginalOrderInvestigationCollection.getValueIsNull(context); } public ims.ocrr.vo.OrderInvestigationVoCollection getOriginalOrderInvestigationCollection() { return (ims.ocrr.vo.OrderInvestigationVoCollection)cxl_OriginalOrderInvestigationCollection.getValue(context); } public void setOriginalOrderInvestigationCollection(ims.ocrr.vo.OrderInvestigationVoCollection value) { cxl_OriginalOrderInvestigationCollection.setValue(context, value); } private ims.framework.ContextVariable cxl_OriginalOrderInvestigationCollection = null; public boolean getInvestigationToAmendIsNotNull() { return !cxl_InvestigationToAmend.getValueIsNull(context); } public ims.ocrr.vo.OcsOrderVo getInvestigationToAmend() { return (ims.ocrr.vo.OcsOrderVo)cxl_InvestigationToAmend.getValue(context); } public void setInvestigationToAmend(ims.ocrr.vo.OcsOrderVo value) { cxl_InvestigationToAmend.setValue(context, value); } private ims.framework.ContextVariable cxl_InvestigationToAmend = null; public boolean getDFTCollectionTypeIsNotNull() { return !cxl_DFTCollectionType.getValueIsNull(context); } public ims.ocrr.vo.DFTCollectionTypesConfigVo getDFTCollectionType() { return (ims.ocrr.vo.DFTCollectionTypesConfigVo)cxl_DFTCollectionType.getValue(context); } public void setDFTCollectionType(ims.ocrr.vo.DFTCollectionTypesConfigVo value) { cxl_DFTCollectionType.setValue(context, value); } private ims.framework.ContextVariable cxl_DFTCollectionType = null; public boolean getOrderComponentsRestorePointIsNotNull() { return !cxl_OrderComponentsRestorePoint.getValueIsNull(context); } public ims.ocrr.vo.MyOrderComponentVoCollection getOrderComponentsRestorePoint() { return (ims.ocrr.vo.MyOrderComponentVoCollection)cxl_OrderComponentsRestorePoint.getValue(context); } public void setOrderComponentsRestorePoint(ims.ocrr.vo.MyOrderComponentVoCollection value) { cxl_OrderComponentsRestorePoint.setValue(context, value); } private ims.framework.ContextVariable cxl_OrderComponentsRestorePoint = null; } public final class ContextMenus implements java.io.Serializable { private static final long serialVersionUID = 1L; public final class OCRRMyOrderAddInvestigation implements java.io.Serializable { private static final long serialVersionUID = 1L; public static final int ADDINVESTIGATION = 1; public static final int REMOVEINVESTIGATION = 2; } public void disableAllOCRRMyOrderAddInvestigationMenuItems() { this.contextMenuOCRRMyOrderAddInvestigationADDINVESTIGATIONItem.setEnabled(false); this.contextMenuOCRRMyOrderAddInvestigationREMOVEINVESTIGATIONItem.setEnabled(false); } public void hideAllOCRRMyOrderAddInvestigationMenuItems() { this.contextMenuOCRRMyOrderAddInvestigationADDINVESTIGATIONItem.setVisible(false); this.contextMenuOCRRMyOrderAddInvestigationREMOVEINVESTIGATIONItem.setVisible(false); } private Menu contextMenuOCRRMyOrderAddInvestigation; public MenuItem getOCRRMyOrderAddInvestigationADDINVESTIGATIONItem() { return this.contextMenuOCRRMyOrderAddInvestigationADDINVESTIGATIONItem; } private MenuItem contextMenuOCRRMyOrderAddInvestigationADDINVESTIGATIONItem; public MenuItem getOCRRMyOrderAddInvestigationREMOVEINVESTIGATIONItem() { return this.contextMenuOCRRMyOrderAddInvestigationREMOVEINVESTIGATIONItem; } private MenuItem contextMenuOCRRMyOrderAddInvestigationREMOVEINVESTIGATIONItem; public final class OCRRMyOrderReportTo implements java.io.Serializable { private static final long serialVersionUID = 1L; public static final int ADDMOS = 3; public static final int ADDGP = 4; public static final int Add = 5; public static final int Remove = 6; public static final int ADDWARD = 7; public static final int ADDOUTPAT = 8; } public void disableAllOCRRMyOrderReportToMenuItems() { this.contextMenuOCRRMyOrderReportToADDMOSItem.setEnabled(false); this.contextMenuOCRRMyOrderReportToADDGPItem.setEnabled(false); this.contextMenuOCRRMyOrderReportToAddItem.setEnabled(false); this.contextMenuOCRRMyOrderReportToRemoveItem.setEnabled(false); this.contextMenuOCRRMyOrderReportToADDWARDItem.setEnabled(false); this.contextMenuOCRRMyOrderReportToADDOUTPATItem.setEnabled(false); } public void hideAllOCRRMyOrderReportToMenuItems() { this.contextMenuOCRRMyOrderReportToADDMOSItem.setVisible(false); this.contextMenuOCRRMyOrderReportToADDGPItem.setVisible(false); this.contextMenuOCRRMyOrderReportToAddItem.setVisible(false); this.contextMenuOCRRMyOrderReportToRemoveItem.setVisible(false); this.contextMenuOCRRMyOrderReportToADDWARDItem.setVisible(false); this.contextMenuOCRRMyOrderReportToADDOUTPATItem.setVisible(false); } private Menu contextMenuOCRRMyOrderReportTo; public MenuItem getOCRRMyOrderReportToADDMOSItem() { return this.contextMenuOCRRMyOrderReportToADDMOSItem; } private MenuItem contextMenuOCRRMyOrderReportToADDMOSItem; public MenuItem getOCRRMyOrderReportToADDGPItem() { return this.contextMenuOCRRMyOrderReportToADDGPItem; } private MenuItem contextMenuOCRRMyOrderReportToADDGPItem; public MenuItem getOCRRMyOrderReportToAddItem() { return this.contextMenuOCRRMyOrderReportToAddItem; } private MenuItem contextMenuOCRRMyOrderReportToAddItem; public MenuItem getOCRRMyOrderReportToRemoveItem() { return this.contextMenuOCRRMyOrderReportToRemoveItem; } private MenuItem contextMenuOCRRMyOrderReportToRemoveItem; public MenuItem getOCRRMyOrderReportToADDWARDItem() { return this.contextMenuOCRRMyOrderReportToADDWARDItem; } private MenuItem contextMenuOCRRMyOrderReportToADDWARDItem; public MenuItem getOCRRMyOrderReportToADDOUTPATItem() { return this.contextMenuOCRRMyOrderReportToADDOUTPATItem; } private MenuItem contextMenuOCRRMyOrderReportToADDOUTPATItem; public final class SelectItems implements java.io.Serializable { private static final long serialVersionUID = 1L; public static final int SELECT = 9; public static final int LINK = 10; } public void disableAllSelectItemsMenuItems() { this.contextMenuSelectItemsSELECTItem.setEnabled(false); this.contextMenuSelectItemsLINKItem.setEnabled(false); } public void hideAllSelectItemsMenuItems() { this.contextMenuSelectItemsSELECTItem.setVisible(false); this.contextMenuSelectItemsLINKItem.setVisible(false); } private Menu contextMenuSelectItems; public MenuItem getSelectItemsSELECTItem() { return this.contextMenuSelectItemsSELECTItem; } private MenuItem contextMenuSelectItemsSELECTItem; public MenuItem getSelectItemsLINKItem() { return this.contextMenuSelectItemsLINKItem; } private MenuItem contextMenuSelectItemsLINKItem; } private ContextMenus contextMenus; public ContextMenus getContextMenus() { return this.contextMenus; } private IReportField[] getFormReportFields() { if(this.context == null) return null; if(this.reportFields == null) this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields(); return this.reportFields; } private class ReportFields { public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { this.context = context; this.formInfo = formInfo; this.componentIdentifier = componentIdentifier; } public IReportField[] getReportFields() { String prefix = formInfo.getLocalVariablesPrefix(); IReportField[] fields = new IReportField[137]; fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient"); fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex"); fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob"); fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod"); fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion"); fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive"); fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin"); fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus"); fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN"); fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation"); fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath"); fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient"); fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant"); fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient"); fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex"); fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob"); fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact"); fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty"); fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType"); fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime"); fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime"); fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext"); fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated"); fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp"); fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType"); fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive"); fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP"); fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician"); fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext"); fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context"); fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital"); fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate"); fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime"); fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime"); fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType"); fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP"); fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare"); fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell"); fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty"); fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship"); fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate"); fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate"); fields[42] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[43] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote"); fields[44] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType"); fields[45] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline"); fields[46] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact"); fields[47] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote"); fields[48] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview"); fields[49] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime"); fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected"); fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed"); fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote"); fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime"); fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport"); fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext"); fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[58] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState"); fields[59] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission"); fields[60] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus"); fields[61] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode"); fields[62] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate"); fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview"); fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[66] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[67] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext"); fields[68] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent"); fields[69] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails"); fields[70] = new ims.framework.ReportField(this.context, "_cvp_RefMan.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral"); fields[71] = new ims.framework.ReportField(this.context, "_cv_OCRR.MyOrderQuestions", "BO-1070100016-ID", "ID_OcsQASession"); fields[72] = new ims.framework.ReportField(this.context, "_cv_Core.GPDetails", "BO-1006100001-ID", "ID_Gp"); fields[73] = new ims.framework.ReportField(this.context, "_cv_Core.GPDetails", "BO-1006100001-STATUS", "Status"); fields[74] = new ims.framework.ReportField(this.context, "_cv_Core.CareContextSelectDialog.ChosenCareContext", "BO-1004100019-ID", "ID_CareContext"); fields[75] = new ims.framework.ReportField(this.context, "_cv_Core.CareContextSelectDialog.ChosenCareContext", "BO-1004100019-CONTEXT", "Context"); fields[76] = new ims.framework.ReportField(this.context, "_cv_Core.CareContextSelectDialog.ChosenCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital"); fields[77] = new ims.framework.ReportField(this.context, "_cv_OCRR.OrderInvestigationToAmend", "BO-1070100002-ID", "ID_OrderInvestigation"); fields[78] = new ims.framework.ReportField(this.context, "_cv_OCRR.OrderInvestigationToAmend", "BO-1070100002-REPDATETIME", "RepDateTime"); fields[79] = new ims.framework.ReportField(this.context, "_cv_OCRR.OrderInvestigationToAmend", "BO-1070100002-DISPLAYDATETIME", "DisplayDateTime"); fields[80] = new ims.framework.ReportField(this.context, "_cv_OCRR.OrderInvestigationToAmend", "BO-1070100002-RESULTSTATUS", "ResultStatus"); fields[81] = new ims.framework.ReportField(this.context, "_cv_OCRR.OrderInvestigationToAmend", "BO-1070100002-DISPLAYFLAG", "DisplayFlag"); fields[82] = new ims.framework.ReportField(this.context, "_cv_OCRR.OrderInvestigationToAmend", "BO-1070100002-APPOINTMENTDATE", "AppointmentDate"); fields[83] = new ims.framework.ReportField(this.context, "_cv_RefMan.OrderingHCP", "BO-1006100006-ID", "ID_MemberOfStaff"); fields[84] = new ims.framework.ReportField(this.context, "_cv_RefMan.OrderingHCP", "BO-1006100006-INITIALS", "Initials"); fields[85] = new ims.framework.ReportField(this.context, "_cv_RefMan.OrderingHCP", "BO-1006100006-SIGNATUREBLOCK", "SignatureBlock"); fields[86] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-ID", "ID_Location"); fields[87] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-NAME", "Name"); fields[88] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-ISACTIVE", "IsActive"); fields[89] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-ISVIRTUAL", "IsVirtual"); fields[90] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-TYPE", "Type"); fields[91] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-DISPLAYINEDTRACKING", "DisplayInEDTracking"); fields[92] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-SECUREACCOMMODATION", "SecureAccommodation"); fields[93] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-TREATINGHOSP", "TreatingHosp"); fields[94] = new ims.framework.ReportField(this.context, "_cv_Core.SelectedLocationForOrdering", "BO-1007100007-REFERRINGHOSPITAL", "ReferringHospital"); fields[95] = new ims.framework.ReportField(this.context, "_cv_Core.OutpatientAttendanceForOrder", "BO-1014100001-ID", "ID_OutpatientAttendance"); fields[96] = new ims.framework.ReportField(this.context, "_cv_Core.OutpatientAttendanceForOrder", "BO-1014100001-APPOINTMENTDATETIME", "AppointmentDateTime"); fields[97] = new ims.framework.ReportField(this.context, "_cv_OCRR.PathologyResults.Order", "BO-1070100000-ID", "ID_OcsOrderSession"); fields[98] = new ims.framework.ReportField(this.context, "_cv_Rotherham.AppointmentToLink", "BO-1055100007-ID", "ID_Booking_Appointment"); fields[99] = new ims.framework.ReportField(this.context, "_cv_OCRR.OrderAwaitingAuthorisation", "BO-1070100000-ID", "ID_OcsOrderSession"); fields[100] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-ID", "ID_OcsOrderSession"); fields[101] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-CLINICALCONTACT", "ClinicalContact"); fields[102] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-ADDITCLINNOTES", "AdditClinNotes"); fields[103] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-ORDERINGHOSPITAL", "OrderingHospital"); fields[104] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-AUTHORISATIONORDERSTATUS", "AuthorisationOrderStatus"); fields[105] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-CLINICALTRIAL", "ClinicalTrial"); fields[106] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-CLINICALTRIALTXT", "ClinicalTrialTxt"); fields[107] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-PATMOBILITY", "PatMobility"); fields[108] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-ORDERCATEGORY", "OrderCategory"); fields[109] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-WASPROCESSED", "WasProcessed"); fields[110] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-SUMMARYCLINICALINFORMATION", "SummaryClinicalInformation"); fields[111] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__OcsOrder_" + componentIdentifier, "BO-1070100000-BLEEPEXTNUMBER", "BleepExtNumber"); fields[112] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-ID", "ID_OrderSpecimen"); fields[113] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-COLLDATETIMEPLACER", "CollDateTimePlacer"); fields[114] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-COLLECTINGMOS", "CollectingMos"); fields[115] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-ISPATIENTCOLLECT", "IsPatientCollect"); fields[116] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-ISAWAITINGCOLLECTION", "IsAwaitingCollection"); fields[117] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-SPECIMENSOURCE", "SpecimenSource"); fields[118] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-DISCIPLINE", "Discipline"); fields[119] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-ORDER", "Order"); fields[120] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-INSTRUCTIONSTOCOLLECTOR", "InstructionsToCollector"); fields[121] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-COLLECTORCOMMENT", "CollectorComment"); fields[122] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-SITECD", "SiteCd"); fields[123] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__ContextDummyForReports_" + componentIdentifier, "BO-1070100010-REQUESTEDTYPE", "RequestedType"); fields[124] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-ID", "ID_OcsOrderSession"); fields[125] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-CLINICALCONTACT", "ClinicalContact"); fields[126] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-ADDITCLINNOTES", "AdditClinNotes"); fields[127] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-ORDERINGHOSPITAL", "OrderingHospital"); fields[128] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-AUTHORISATIONORDERSTATUS", "AuthorisationOrderStatus"); fields[129] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-CLINICALTRIAL", "ClinicalTrial"); fields[130] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-CLINICALTRIALTXT", "ClinicalTrialTxt"); fields[131] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-PATMOBILITY", "PatMobility"); fields[132] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-ORDERCATEGORY", "OrderCategory"); fields[133] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-WASPROCESSED", "WasProcessed"); fields[134] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-SUMMARYCLINICALINFORMATION", "SummaryClinicalInformation"); fields[135] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__InvestigationToAmend_" + componentIdentifier, "BO-1070100000-BLEEPEXTNUMBER", "BleepExtNumber"); fields[136] = new ims.framework.ReportField(this.context, prefix + "_lv_OCRR.MyOrder.__internal_x_context__DFTCollectionType_" + componentIdentifier, "BO-1061100027-ID", "ID_DFTCollectionTypesConfig"); return fields; } protected Context context = null; protected ims.framework.FormInfo formInfo; protected String componentIdentifier; } public String getUniqueIdentifier() { return null; } private Context context = null; private ims.framework.FormInfo formInfo = null; private String componentIdentifier; private GlobalContext globalContext = null; private IReportField[] reportFields = null; }
agpl-3.0
hbrunn/server-tools
__unported__/base_optional_quick_create/model.py
2434
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 Agile Business Group sagl (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import orm, fields from openerp import SUPERUSER_ID from openerp.tools.translate import _ class ir_model(orm.Model): _inherit = 'ir.model' _columns = { 'avoid_quick_create': fields.boolean('Avoid quick create'), } def _wrap_name_create(self, old_create, model): def wrapper(cr, uid, name, context=None): raise orm.except_orm(_('Error'), _("Can't create quickly. Opening create form")) return wrapper def _register_hook(self, cr, ids=None): if ids is None: ids = self.search(cr, SUPERUSER_ID, []) for model in self.browse(cr, SUPERUSER_ID, ids): if model.avoid_quick_create: model_name = model.model model_obj = self.pool.get(model_name) if not hasattr(model_obj, 'check_quick_create'): model_obj.name_create = self._wrap_name_create(model_obj.name_create, model_name) model_obj.check_quick_create = True return True def create(self, cr, uid, vals, context=None): res_id = super(ir_model, self).create(cr, uid, vals, context=context) self._register_hook(cr, [res_id]) return res_id def write(self, cr, uid, ids, vals, context=None): if isinstance(ids, (int, long)): ids = [ids] super(ir_model, self).write(cr, uid, ids, vals, context=context) self._register_hook(cr, ids) return True
agpl-3.0
ioanpocol/superdesk-client-core
scripts/apps/desks/directives/MarkDesksDropdown.ts
1038
import {DesksReactDropdown} from './DesksReactDropdown'; import ReactDOM from 'react-dom'; import {gettext} from 'core/utils'; /** * @ngdoc directive * @module superdesk.apps.desks * @name MarkDesksDropdown * * @requires desks * @requires $timeout * * * @description Creates dropdown react element with list of available desks */ MarkDesksDropdown.$inject = ['desks', '$timeout', '$injector']; export function MarkDesksDropdown(desks, $timeout, $injector) { return { link: function(scope, elem) { desks.fetchDesks().then(() => { var deskList = $injector.invoke(DesksReactDropdown, null, { item: scope.item, className: '', noHighlightsLabel: gettext('No available highlights'), noDesksLabel: gettext('No available desks'), noLanguagesLabel: gettext('No available translations'), }); ReactDOM.render(deskList, elem[0]); }); }, }; }
agpl-3.0
oopcell/openApotti
Source Library/openmaxims_workspace/Correspondence/src/ims/correspondence/forms/batchupdatepatientlists/Logic.java
12578
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Peter Martin using IMS Development Environment (version 1.62 build 3100.30141) // Copyright (C) 1995-2008 IMS MAXIMS plc. All rights reserved. package ims.correspondence.forms.batchupdatepatientlists; import ims.configuration.gen.ConfigFlag; import ims.core.vo.DischargedEpisodeVo; import ims.core.vo.DischargedEpisodeVoCollection; import ims.core.vo.InpatientEpisodeVo; import ims.core.vo.InpatientEpisodeVoCollection; import ims.core.vo.MedicWithMappingsLiteVo; import ims.core.vo.MemberOfStaffShortVo; import ims.core.vo.OutPatientAttendanceVo; import ims.core.vo.OutPatientAttendanceVoCollection; import ims.core.vo.OutPatientListSearchCriteriaVo; import ims.core.vo.PasEventVo; import ims.core.vo.PatientListsFilterVo; import ims.core.vo.lookups.DocumentStatus; import ims.correspondence.vo.CorrespondencePatientListsVoCollection; import ims.domain.exceptions.DomainInterfaceException; import ims.domain.exceptions.StaleObjectException; import ims.framework.enumerations.DialogResult; import ims.framework.exceptions.PresentationLogicException; public class Logic extends BaseLogic { private static final long serialVersionUID = 1L; @Override protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException { initialise(); } private void initialise() { PatientListsFilterVo voPatientListsFilter = form.getGlobalContext().Correspondence.getPatientListSearchCriteria(); OutPatientListSearchCriteriaVo voOutPatientList = form.getGlobalContext().Core.getOutPatientSearchCriteria(); DocumentStatus newDocumentStatus = form.getGlobalContext().Correspondence.getPatientListsBatchUpdateType(); if(newDocumentStatus == DocumentStatus.DICTATED) form.pnlBatchUpdate().setValue("Batch Update Of Status To 'Dictated'"); else if(newDocumentStatus == DocumentStatus.NOLETTERREQUIRED) form.pnlBatchUpdate().setValue("Batch Update Of Status To 'No Letter Required'"); else if(newDocumentStatus == DocumentStatus.SIGNED) form.pnlBatchUpdate().setValue("Batch Update Of Status To 'Signed'"); if(voPatientListsFilter!=null) populateListControl(domain.listInPatients(voPatientListsFilter,(newDocumentStatus==DocumentStatus.DICTATED))); else if(voOutPatientList!=null) populateListControl(domain.listOutpatients(voOutPatientList, (newDocumentStatus==DocumentStatus.DICTATED))); } private void populateListControl(CorrespondencePatientListsVoCollection voCorrespondencePatientListsEpisColl) { if (voCorrespondencePatientListsEpisColl != null) { if (voCorrespondencePatientListsEpisColl.size() == 0) { engine.showMessage("No matching patients found."); return; } GenForm.grdPatientListRow row = null; for (int i = 0; i < voCorrespondencePatientListsEpisColl.size(); i++) { InpatientEpisodeVo voInpatient = voCorrespondencePatientListsEpisColl.get(i).getInpatientEpisodeVo(); DischargedEpisodeVo voDischargedEpisode = voCorrespondencePatientListsEpisColl.get(i).getDischargeEpisodeVo(); OutPatientAttendanceVo voOutpatientAttendance = voCorrespondencePatientListsEpisColl.get(i).getOutpatientAttendanceVo(); PasEventVo voPasEvent = null; if(voInpatient != null && voInpatient.getPasEventIsNotNull()) voPasEvent = voInpatient.getPasEvent(); else if(voDischargedEpisode != null && voDischargedEpisode.getPasEventIsNotNull()) voPasEvent = voDischargedEpisode.getPasEvent(); else if(voOutpatientAttendance != null && voOutpatientAttendance.getPasEventIsNotNull()) voPasEvent = voOutpatientAttendance.getPasEvent(); /*if(form.grdPatientList().getValue()==null && form.getLocalContext().getUserAccessVoIsNotNull()){ boolean bIsUserAccessConsultant = false; UserAccessVo voUserAccess = form.getLocalContext().getUserAccessVo(); ConsultantAccessVoCollection collConsultantAccessVo = voUserAccess.getConsultantAccess(); MedicLiteVo med = null; if (collConsultantAccessVo != null) { for (int j = 0; j < collConsultantAccessVo.size(); j++) { med = collConsultantAccessVo.get(j).getConsultant(); if(med.getID_Hcp().equals(voInpatient.getPasEvent().getConsultant().getID_Hcp())) bIsUserAccessConsultant=true; } } if(!bIsUserAccessConsultant) continue; }*/ if (voPasEvent.getPatientIsNotNull()) { row = form.grdPatientList().getRows().newRow(); if(voInpatient != null && voInpatient.getIsOnLeaveIsNotNull() && voInpatient.getIsOnLeave().equals(Boolean.TRUE)) { row.setcolLeave(form.getImages().Core.Home); row.setTooltipForcolLeave("Patient is currently on Leave"); } if (voPasEvent.getPatient().getNameIsNotNull()) { if (voPasEvent.getPatient().getName().getForenameIsNotNull()) row.setcolForename(voPasEvent.getPatient().getName().getForename()); if (voPasEvent.getPatient().getName().getSurnameIsNotNull()) row.setcolSurname(voPasEvent.getPatient().getName().getSurname()); } voPasEvent.getPatient().calculateAge(); if (voPasEvent.getPatient().getAgeIsNotNull()) row.setColAge(voPasEvent.getPatient().getAge().toString()); ims.core.vo.PatientId voPatId = voPasEvent.getPatient().getDisplayId(); if (voPatId != null) row.setcolHospnum(voPatId.getValue()); if (voPasEvent.getPatient().getDobIsNotNull()) row.setcolDob(voPasEvent.getPatient().getDob().toString()); if (voPasEvent.getPatient().getAgeIsNotNull()) row.setColAge(voPasEvent.getPatient().getAge().toString()); if (voPasEvent.getPatient().getSexIsNotNull()) row.setcolSex(voPasEvent.getPatient().getSex().getText()); if (voPasEvent.getLocationIsNotNull()) row.setcolWard(voPasEvent.getLocation().getName()); if (voPasEvent.getPatient().getIsDead() != null && voPasEvent.getPatient().getIsDead().booleanValue()) row.setBackColor(ConfigFlag.UI.RIP_COLOUR.getValue()); if (voPasEvent.getEventDateTime() != null) row.setcolAdmissionDate(voPasEvent.getEventDateTime().getDate().toString()); if (voPasEvent.getConsultant() != null) row.setcolConsultant(voPasEvent.getConsultant().getName().toString()); if(voPasEvent.getCspDocumentStatusIsNotNull()){ row.setcolDocStatus(voPasEvent.getCspDocumentStatus().getImage()); row.setTooltipForcolDocStatus(voPasEvent.getCspDocumentStatus().getText()); } if(voInpatient != null) row.setValue(voInpatient); else if(voDischargedEpisode != null){ row.setcolDischarged(form.getImages().NTPF.Discharge); row.setTooltipForcolDischarged("Discharged"); row.setValue(voDischargedEpisode); } else if(voOutpatientAttendance != null) row.setValue(voOutpatientAttendance); } } } } @Override protected void onBtnCancel() throws PresentationLogicException { engine.close(DialogResult.CANCEL); } @Override protected void onBtnSaveClick() throws PresentationLogicException { InpatientEpisodeVoCollection collInpatientEpisodeVo = new InpatientEpisodeVoCollection (); DischargedEpisodeVoCollection collDischargedEpisodeVo = new DischargedEpisodeVoCollection (); OutPatientAttendanceVoCollection collOutPatientAttendanceVo = new OutPatientAttendanceVoCollection (); InpatientEpisodeVo voInpatientListRow = null; DischargedEpisodeVo voDischargedEpisode = null; OutPatientAttendanceVo voOutPatientAttendance = null; PasEventVo voPasEvent = null; for(int i=0; i< form.grdPatientList().getRows().size(); i++){ if(form.grdPatientList().getRows().get(i).getcolSelect()){ if(form.grdPatientList().getRows().get(i).getValue() instanceof InpatientEpisodeVo){ voInpatientListRow = (InpatientEpisodeVo) form.grdPatientList().getRows().get(i).getValue(); voPasEvent = voInpatientListRow.getPasEvent(); DocumentStatus documentStatus = form.getGlobalContext().Correspondence.getPatientListsBatchUpdateType(); voPasEvent.setCspDocumentStatus(documentStatus); voInpatientListRow.setPasEvent(voPasEvent); String[] errors = voInpatientListRow.validate(); if (errors != null) { engine.showErrors(errors); return; } collInpatientEpisodeVo.add(voInpatientListRow); } else if(form.grdPatientList().getRows().get(i).getValue() instanceof DischargedEpisodeVo){ voDischargedEpisode = (DischargedEpisodeVo) form.grdPatientList().getRows().get(i).getValue(); voPasEvent = voDischargedEpisode.getPasEvent(); DocumentStatus documentStatus = form.getGlobalContext().Correspondence.getPatientListsBatchUpdateType(); voPasEvent.setCspDocumentStatus(documentStatus); voDischargedEpisode.setPasEvent(voPasEvent); String[] errors = voDischargedEpisode.validate(); if (errors != null) { engine.showErrors(errors); return; } collDischargedEpisodeVo.add(voDischargedEpisode); } else if(form.grdPatientList().getRows().get(i).getValue() instanceof OutPatientAttendanceVo){ voOutPatientAttendance = (OutPatientAttendanceVo) form.grdPatientList().getRows().get(i).getValue(); voPasEvent = voOutPatientAttendance.getPasEvent(); DocumentStatus documentStatus = form.getGlobalContext().Correspondence.getPatientListsBatchUpdateType(); voPasEvent.setCspDocumentStatus(documentStatus); voOutPatientAttendance.setPasEvent(voPasEvent); String[] errors = voOutPatientAttendance.validate(); if (errors != null) { engine.showErrors(errors); return; } collOutPatientAttendanceVo.add(voOutPatientAttendance); } } } if(collInpatientEpisodeVo.size()==0 && collDischargedEpisodeVo.size()==0 && collOutPatientAttendanceVo.size()==0){ engine.showMessage("Select at least 1 Episode to be updated."); return; } if(collInpatientEpisodeVo.size()>0){ try { domain.saveInpatientEpisodes(collInpatientEpisodeVo, (MemberOfStaffShortVo) domain.getMosUser()); } catch (DomainInterfaceException e) { engine.showMessage(e.getMessage()); return; } catch (StaleObjectException e) { engine.showMessage(e.getMessage()); return; } } if(collDischargedEpisodeVo.size()>0){ try { domain.saveDischargeEpisodes(collDischargedEpisodeVo, (MemberOfStaffShortVo) domain.getMosUser()); } catch (DomainInterfaceException e) { engine.showMessage(e.getMessage()); return; } catch (StaleObjectException e) { engine.showMessage(e.getMessage()); return; } } if(collOutPatientAttendanceVo.size()>0){ try { domain.saveOutPatientEpisodes(collOutPatientAttendanceVo, (MemberOfStaffShortVo) domain.getMosUser()); } catch (DomainInterfaceException e) { engine.showMessage(e.getMessage()); return; } catch (StaleObjectException e) { engine.showMessage(e.getMessage()); return; } } engine.close(DialogResult.OK); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace-archive/Core/src/ims/core/forms/localsettingsdialog/Handlers.java
3100
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.localsettingsdialog; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnOkClick() throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { onFormOpen(args); } }); this.form.btnCancel().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnCancelClick(); } }); this.form.btnOk().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnOkClick(); } }); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIEngine engine; protected GenForm form; }
agpl-3.0
laborautonomo/jitsi
src/net/java/sip/communicator/service/protocol/OperationSetFileTransfer.java
3401
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.service.protocol; import java.io.*; import net.java.sip.communicator.service.protocol.event.*; /** * The File Transfer Operation Set provides an interface towards those functions * of a given protocol, that allow transferring files among users. * * @author Emil Ivov * @author Yana Stamcheva */ public interface OperationSetFileTransfer extends OperationSet { /** * Sends a file transfer request to the given <tt>toContact</tt> by * specifying the local and remote file path and the <tt>fromContact</tt>, * sending the file. * * @param toContact the contact that should receive the file * @param file the file to send * * @return the transfer object * * @throws IllegalStateException if the protocol provider is not registered * or connected * @throws IllegalArgumentException if some of the arguments doesn't fit the * protocol requirements * @throws OperationNotSupportedException if the given contact client or * server does not support file transfers */ public FileTransfer sendFile( Contact toContact, File file) throws IllegalStateException, IllegalArgumentException, OperationNotSupportedException; /** * Sends a file transfer request to the given <tt>toContact</tt> by * specifying the local and remote file path and the <tt>fromContact</tt>, * sending the file. * * @param toContact the contact that should receive the file * @param fromContact the contact sending the file * @param remotePath the remote file path * @param localPath the local file path * * @return the transfer object * * @throws IllegalStateException if the protocol provider is not registered * or connected * @throws IllegalArgumentException if some of the arguments doesn't fit the * protocol requirements * @throws OperationNotSupportedException if the given contact client or * server does not support file transfers. */ public FileTransfer sendFile( Contact toContact, Contact fromContact, String remotePath, String localPath) throws IllegalStateException, IllegalArgumentException, OperationNotSupportedException; /** * Adds the given <tt>FileTransferListener</tt> that would listen for * file transfer requests and created file transfers. * * @param listener the <tt>FileTransferListener</tt> to add */ public void addFileTransferListener( FileTransferListener listener); /** * Removes the given <tt>FileTransferListener</tt> that listens for * file transfer requests and created file transfers. * * @param listener the <tt>FileTransferListener</tt> to remove */ public void removeFileTransferListener( FileTransferListener listener); /** * Returns the maximum file length supported by the protocol in bytes. * @return the file length that is supported. */ public long getMaximumFileLength(); }
lgpl-2.1
xph906/SootNew
src/soot/coffi/Instruction_Lstore_3.java
2485
/* Soot - a J*va Optimization Framework * Copyright (C) 1997 Clark Verbrugge * * 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. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ package soot.coffi; /** Instruction subclasses are used to represent parsed bytecode; each * bytecode operation has a corresponding subclass of Instruction. * <p> * Each subclass is derived from one of * <ul><li>Instruction</li> * <li>Instruction_noargs (an Instruction with no embedded arguments)</li> * <li>Instruction_byte (an Instruction with a single byte data argument)</li> * <li>Instruction_bytevar (a byte argument specifying a local variable)</li> * <li>Instruction_byteindex (a byte argument specifying a constant pool index)</li> * <li>Instruction_int (an Instruction with a single short data argument)</li> * <li>Instruction_intvar (a short argument specifying a local variable)</li> * <li>Instruction_intindex (a short argument specifying a constant pool index)</li> * <li>Instruction_intbranch (a short argument specifying a code offset)</li> * <li>Instruction_longbranch (an int argument specifying a code offset)</li> * </ul> * @author Clark Verbrugge * @see Instruction * @see Instruction_noargs * @see Instruction_byte * @see Instruction_bytevar * @see Instruction_byteindex * @see Instruction_int * @see Instruction_intvar * @see Instruction_intindex * @see Instruction_intbranch * @see Instruction_longbranch * @see Instruction_Unknown */ class Instruction_Lstore_3 extends Instruction_noargs { public Instruction_Lstore_3() { super((byte)ByteCode.LSTORE_3); name = "lstore_3"; } }
lgpl-2.1
MichaelMcDonnell/vrjuggler
modules/gadgeteer/test/FlockAdaptor.cpp
5402
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2011 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <FlockAdaptor.h> #include <string> // Constructor //spinner() was here also namespace gadget_test { FlockAdaptor::FlockAdaptor(const std::string& devName = "Flock of Birds") { mName=devName; //MUST KEEP HERE ALWAYS //mFlock = new FlockStandalone(); //const char* port = "/dev/ttyd3"; const char* port = "/dev/ttyS0"; const int baud = 38400; const int numBirds = 2; const char* calfile = "/home/users/allenb/Source/juggler/Data/calibration.table"; const BIRD_HEMI hemi = LOWER_HEM; const BIRD_FILT filt = AC_NARROW; const int sync = 1; const int blocking = 0; const char report = 'R'; const int transmitter = 3; mFlock = new FlockStandalone( port, baud, sync, blocking, numBirds, transmitter, hemi, filt, report, calfile ); } FlockAdaptor::~FlockAdaptor() { if ( mFlock != NULL ) { delete mFlock; mFlock = NULL; } } bool FlockAdaptor::Start( const std::string& ttyPort, int mBaudRate ) { if(mFlock->start() == vpr::ReturnStatus::Fail) { return(false); } else { return(true); } } bool FlockAdaptor::Start() { std::string ttyPort; int mBaudRate; std::cout<<" ====================================================\n"<<std::flush; std::cout<<" What serial port do you want to use? \n"<<std::flush; std::cout<<" ====================================================\n"<<std::flush; std::cin >> ttyPort; std::cout<<" ====================================================\n"<<std::flush; std::cout<<" What baud rate do you want to use? \n"<<std::flush; std::cout<<" ====================================================\n"<<std::flush; std::cin >> mBaudRate; return(Start(ttyPort,mBaudRate)); } bool FlockAdaptor::Stop() { if ( mFlock != NULL ) { mFlock->stop(); delete mFlock; mFlock = NULL; } return(true); } bool FlockAdaptor::Sample( int numSamples ) { for(int z = 0; z < 10; z++) { int i; mFlock->sample(); system("clear"); std::cout << "vjFlock------------------------------------------------------------" << std::endl; std::cout<< "Data: x:" << std::setw(10); for(i=1; i <= mFlock->getNumBirds(); ++i) { std::cout<< std::setw(10) <<mFlock->xPos(i); std::cout<<std::endl; std::cout<< " y:" << std::setw(10); } for( i=1; i <= mFlock->getNumBirds(); ++i) { std::cout<< std::setw(10) <<mFlock->yPos(i); std::cout<<std::endl; std::cout<< " z:" << std::setw(10); } for( i=1; i <= mFlock->getNumBirds(); ++i) { std::cout<< std::setw(10) <<mFlock->zPos(i); std::cout<<std::endl; std::cout<< " azi:" << std::setw(10); } for( i=1; i <= mFlock->getNumBirds(); ++i) { std::cout<< std::setw(10) <<mFlock->zRot(i); std::cout<<std::endl; std::cout<< " elev:" << std::setw(10); } for( i=1; i <= mFlock->getNumBirds(); ++i) { std::cout<< std::setw(10) <<mFlock->yRot(i); std::cout<<std::endl; std::cout<< " roll:" ; } for( i=1; i <= mFlock->getNumBirds(); ++i) { std::cout<< std::setw(10) <<mFlock->xRot(i); std::cout<<std::endl<<std::endl; } sleep(2); } return(true); } bool FlockAdaptor::Sample() { int numSamples; std::cout<<" ====================================================\n"<<std::flush; std::cout<<" How many samples of data do you want? \n"<<std::flush; std::cout<<" ====================================================\n"<<std::flush; std::cin >> numSamples; return(Sample(numSamples)); } bool FlockAdaptor::Dump() { return(true); } void FlockAdaptor::printCommands() { std::cout << " ==================================\n" << std::flush; std::cout << " Flock Interactive Test\n" << std::flush; std::cout << " ==================================\n" << std::flush; std::cout << " S = Start\n" << std::flush; std::cout << " X = Stop\n" << std::flush; std::cout << " N = Sample\n" << std::flush; std::cout << " Q = Quit\n" << std::flush; std::cout << " ==================================\n" << std::flush; } void FlockAdaptor::Command(const char ch) { if(ch=='S') { Start(); } else if(ch=='X') { Stop(); } else if(ch=='N') { Sample(); } } }
lgpl-2.1
danielru/moose
modules/solid_mechanics/src/bcs/DashpotBC.C
2258
/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "DashpotBC.h" template<> InputParameters validParams<DashpotBC>() { InputParameters params = validParams<IntegratedBC>(); params.addRequiredParam<unsigned int>("component", "The displacement component corresponding the variable this BC acts on."); params.addRequiredCoupledVar("disp_x", "Displacement in the x direction"); params.addCoupledVar("disp_y", "Displacement in the y direction"); params.addCoupledVar("disp_z", "Displacement in the z direction"); params.addParam<Real>("coefficient", 1.0, "The viscosity coefficient"); return params; } DashpotBC::DashpotBC(const std::string & name, InputParameters parameters) : IntegratedBC(name, parameters), _component(getParam<unsigned int>("component")), _coefficient(getParam<Real>("coefficient")), _disp_x_var(coupled("disp_x")), _disp_y_var(isCoupled("disp_y") ? coupled("disp_y") : 0), _disp_z_var(isCoupled("disp_z") ? coupled("disp_z") : 0), _disp_x_dot(coupledDot("disp_x")), _disp_y_dot(isCoupled("disp_y") ? coupledDot("disp_y") : _zero), _disp_z_dot(isCoupled("disp_z") ? coupledDot("disp_z") : _zero) {} Real DashpotBC::computeQpResidual() { RealVectorValue velocity(_disp_x_dot[_qp], _disp_y_dot[_qp], _disp_z_dot[_qp]); return _test[_i][_qp]*_coefficient*_normals[_qp]*velocity; } Real DashpotBC::computeQpJacobian() { RealVectorValue velocity; velocity(_component) = _phi[_j][_qp]/_dt; return _test[_i][_qp]*_coefficient*_normals[_qp]*velocity; } Real DashpotBC::computeQpOffDiagJacobian(unsigned int jvar) { RealVectorValue velocity; unsigned int component = 0; if (jvar == _disp_x_var) component = 0; else if (jvar == _disp_y_var) component = 1; else if (jvar == _disp_z_var) component = 2; velocity(component) = _phi[_j][_qp]/_dt; return -_test[_i][_qp]*_normals[_qp]*velocity; }
lgpl-2.1
dizzzz/exist
exist-core/src/main/java/org/exist/xmldb/AbstractLocalService.java
1874
/* * eXist-db Open Source Native XML Database * Copyright (C) 2001 The eXist-db Authors * * info@exist-db.org * http://www.exist-db.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.xmldb; import org.exist.security.Subject; import org.exist.storage.BrokerPool; import org.xmldb.api.base.Collection; import org.xmldb.api.base.ErrorCodes; import org.xmldb.api.base.Service; import org.xmldb.api.base.XMLDBException; /** * Base class for Local XMLDB Services * * @author <a href="mailto:adam.retter@googlemail.com">Adam Retter</a> */ public abstract class AbstractLocalService extends AbstractLocal implements Service { AbstractLocalService(final Subject user, final BrokerPool brokerPool, final LocalCollection collection) { super(user, brokerPool, collection); } @Override public void setCollection(final Collection collection) throws XMLDBException { if(!(collection instanceof LocalCollection)) { throw new XMLDBException(ErrorCodes.INVALID_COLLECTION, "incompatible collection type: " + collection.getClass().getName()); } this.collection = (LocalCollection) collection; } }
lgpl-2.1
LLNL/spack
var/spack/repos/builtin/packages/util-linux/package.py
2969
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os from spack import * class UtilLinux(AutotoolsPackage): """Util-linux is a suite of essential utilities for any Linux system.""" homepage = "https://github.com/karelzak/util-linux" url = "https://www.kernel.org/pub/linux/utils/util-linux/v2.29/util-linux-2.29.2.tar.gz" list_url = "https://www.kernel.org/pub/linux/utils/util-linux" list_depth = 1 version('2.37.2', sha256='15db966474e459b33fa390a6b892190a92079a73ca45384cde4c86e6ed265a86') version('2.37.1', sha256='0fe9ee8ee7f157be8abcfc2902ec8de9fe30b39173b84e4c458675cef4709b35') version('2.37', sha256='faa8b46d080faa6f32c57da81eda871e38e1e27ba4e9b61cb2589334671aba50') version('2.36.2', sha256='f5dbe79057e7d68e1a46fc04083fc558b26a49499b1b3f50e4f4893150970463') version('2.36', sha256='82942cd877a989f6d12d4ce2c757fb67ec53d8c5cd9af0537141ec5f84a2eea3') version('2.35.1', sha256='37ac05d82c6410d89bc05d43cee101fefc8fe6cf6090b3ce7a1409a6f35db606') version('2.35', sha256='98acab129a8490265052e6c1e033ca96d68758a13bb7fcd232c06bf16cc96238') version('2.34', sha256='b62c92e5e1629642113cd41cec1ee86d1ee7e36b8ffe8ec3ac89c11797e9ac25') version('2.33.1', sha256='e15bd3142b3a0c97fffecaed9adfdef8ab1d29211215d7ae614c177ef826e73a') version('2.33', sha256='952fb0d3498e81bd67b3c48e283c80cb12c719bc2357ec5801e7d420991ad319') version('2.29.2', sha256='29ccdf91d2c3245dc705f0ad3bf729ac41d8adcdbeff914e797c552ecb04a4c7') version('2.29.1', sha256='a6a7adba65a368e6dad9582d9fbedee43126d990df51266eaee089a73c893653') version('2.25', sha256='7e43273a9e2ab99b5a54ac914fddf5d08ba7ab9b114c550e9f03474672bd23a1') depends_on('python@2.7:', type='build') depends_on('pkgconfig', type='build') depends_on('ncurses', type='link') variant('bash', default=False, description='Install bash completion scripts') depends_on('bash', when="+bash", type='run') def url_for_version(self, version): url = "https://www.kernel.org/pub/linux/utils/util-linux/v{0}/util-linux-{1}.tar.gz" return url.format(version.up_to(2), version) def configure_args(self): config_args = [ '--disable-use-tty-group', '--disable-makeinstall-chown', '--without-systemd', '--disable-libuuid', ] if "+bash" in self.spec: config_args.extend( ['--enable-bash-completion', '--with-bashcompletiondir=' + os.path.join( self.spec['bash'].prefix, "share", "bash-completion", "completions")]) else: config_args.append('--disable-bash-completion') return config_args def install(self, spec, prefix): make('install', parallel=False)
lgpl-2.1
dfoteinakis/MateCat
test/unit/DAO/TestJobDAO/DestroyCacheJobTest.php
5596
<?php /** * @group regression * @covers Jobs_JobDao::destroyCache * User: dinies * Date: 27/05/16 * Time: 11.48 */ class DestroyCacheJobTest extends AbstractTest { /** * @var Jobs_JobDao */ protected $job_Dao; /** * @var Jobs_JobStruct */ protected $job_struct; /** * @var Database */ protected $database_instance; protected $id; protected $str_password; protected $str_id_project; protected $str_owner; /** * @var \Predis\Client */ protected $cache; public function setUp() { parent::setUp(); /** * job initialization */ $this->id= "808080"; $this->str_id_project = "888888"; $this->str_password = "7barandfoo71"; $this->str_owner="barandfoo@translated.net"; $this->job_struct = new Jobs_JobStruct( array('id' => $this->id, //SET NULL FOR AUTOINCREMENT -> in this case is only stored in cache so i will chose a casual value 'password' => $this->str_password, 'id_project' => $this->str_id_project, 'job_first_segment' => "182655137", 'job_last_segment' => "182655236", 'source' => "nl-NL", 'target' => "de-DE", 'tm_keys' => '[{"tm":true,"glos":true,"owner":true,"uid_transl":null,"uid_rev":null,"name":"","key":"e1f9153f48c4c7e9328d","r":true,"w":true,"r_transl":null,"w_transl":null,"r_rev":null,"w_rev":null,"source":null,"target":null}]', 'id_translator' => "", 'job_type' => null, 'total_time_to_edit' => "156255", 'avg_post_editing_effort' => "0", 'id_job_to_revise' => null, 'last_opened_segment' => "182655204", 'id_tms' => "1", 'id_mt_engine' => "1", 'create_date' => "2016-03-30 13:18:09", 'last_update' => "2016-03-30 13:21:02", 'disabled' => "0", 'owner' => $this->str_owner, 'status_owner' => "active", 'status' => "active", 'status_translator' => null, 'completed' => false, 'new_words' => "-12.60", 'draft_words' => "0.00", 'translated_words' => "728.15", 'approved_words' => "0.00", 'rejected_words' => "0.00", 'subject' => "general", 'payable_rates' => '{"NO_MATCH":100,"50%-74%":100,"75%-84%":60,"85%-94%":60,"95%-99%":60,"100%":30,"100%_PUBLIC":30,"REPETITIONS":30,"INTERNAL":60,"MT":85}', 'revision_stats_typing_min' => "0", 'revision_stats_translations_min' => "0", 'revision_stats_terminology_min' => "0", 'revision_stats_language_quality_min' => "0", 'revision_stats_style_min' => "0", 'revision_stats_typing_maj' => "0", 'revision_stats_translations_maj' => "0", 'revision_stats_terminology_maj' => "0", 'revision_stats_language_quality_maj' => "0", 'revision_stats_style_maj' => "0", 'dqf_key' => "", 'total_raw_wc' => "1", 'validator' => "xxxx" ) ); $this->database_instance = Database::obtain(INIT::$DB_SERVER, INIT::$DB_USER, INIT::$DB_PASS, INIT::$DB_DATABASE); $this->job_Dao = new Jobs_JobDao($this->database_instance); $this->cache= new Predis\Client(INIT::$REDIS_SERVERS); } public function tearDown() { $this->cache->flushdb(); parent::tearDown(); } /** * @group regression * @covers Jobs_JobDao::destroyCache */ public function test_DestroyCache_with_ID_and_Password() { $cache_key = "SELECT * FROM ".INIT::$DB_DATABASE.".`jobs` WHERE id ='". $this->id ."' AND password = '". $this->str_password ." '"; $key = md5($cache_key); $value = serialize($this->job_struct); $this->cache->setex($key,20, $value); $output_before_destruction=$this->cache->get($key); $this->assertEquals($value,$output_before_destruction); $this->assertTrue(unserialize($output_before_destruction) instanceof Jobs_JobStruct); $this->job_Dao->destroyCache($this->job_struct); $output_after_destruction=$this->cache->get($cache_key); $this->assertNull($output_after_destruction); $this->assertFalse(unserialize($output_after_destruction) instanceof Jobs_JobStruct); } /** * @group regression * @covers Jobs_JobDao::destroyCache */ public function test_DestroyCache_with_ID_Project() { $cache_key = "SELECT * FROM ( SELECT * FROM ".INIT::$DB_DATABASE.".`jobs` WHERE id ='". $this->str_id_project ."' ORDER BY id DESC) t GROUP BY id ; "; $key = md5($cache_key); $value = serialize($this->job_struct); $this->cache->setex($key,20, $value); $output_before_destruction=$this->cache->get($key); $this->assertEquals($value,$output_before_destruction); $this->assertTrue(unserialize($output_before_destruction) instanceof Jobs_JobStruct); $this->job_Dao->destroyCache($this->job_struct); $output_after_destruction=$this->cache->get($cache_key); $this->assertNull($output_after_destruction); $this->assertFalse(unserialize($output_after_destruction) instanceof Jobs_JobStruct); } }
lgpl-3.0
udayakiran/video-js-3
dev/require.js
88951
/** vim: et:ts=4:sw=4:sts=4 * @license RequireJS 1.0.4 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /*jslint strict: false, plusplus: false, sub: true */ /*global window: false, navigator: false, document: false, importScripts: false, jQuery: false, clearInterval: false, setInterval: false, self: false, setTimeout: false, opera: false */ var requirejs, require, define; (function () { //Change this version number for each release. var version = "1.0.4", commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /require\(\s*["']([^'"\s]+)["']\s*\)/g, currDirRegExp = /^\.\//, jsSuffixRegExp = /\.js$/, ostring = Object.prototype.toString, ap = Array.prototype, aps = ap.slice, apsp = ap.splice, isBrowser = !!(typeof window !== "undefined" && navigator && document), isWebWorker = !isBrowser && typeof importScripts !== "undefined", //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is "loading", "loaded", execution, // then "complete". The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = "_", //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== "undefined" && opera.toString() === "[object Opera]", empty = {}, contexts = {}, globalDefQueue = [], interactiveScript = null, checkLoadedDepth = 0, useInteractive = false, req, cfg = {}, currentlyAddingScript, s, head, baseElement, scripts, script, src, subPath, mainScript, dataMain, i, ctx, jQueryCheck, checkLoadedTimeoutId; function isFunction(it) { return ostring.call(it) === "[object Function]"; } function isArray(it) { return ostring.call(it) === "[object Array]"; } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. * This is not robust in IE for transferring methods that match * Object.prototype names, but the uses of mixin here seem unlikely to * trigger a problem related to that. */ function mixin(target, source, force) { for (var prop in source) { if (!(prop in empty) && (!(prop in target) || force)) { target[prop] = source[prop]; } } return req; } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); if (err) { e.originalError = err; } return e; } /** * Used to set up package paths from a packagePaths or packages config object. * @param {Object} pkgs the object to store the new package config * @param {Array} currentPackages an array of packages to configure * @param {String} [dir] a prefix dir to use. */ function configurePackageDir(pkgs, currentPackages, dir) { var i, location, pkgObj; for (i = 0; (pkgObj = currentPackages[i]); i++) { pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj; location = pkgObj.location; //Add dir to the path, but avoid paths that start with a slash //or have a colon (indicates a protocol) if (dir && (!location || (location.indexOf("/") !== 0 && location.indexOf(":") === -1))) { location = dir + "/" + (location || pkgObj.name); } //Create a brand new object on pkgs, since currentPackages can //be passed in again, and config.pkgs is the internal transformed //state for all package configs. pkgs[pkgObj.name] = { name: pkgObj.name, location: location || pkgObj.name, //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. main: (pkgObj.main || "main") .replace(currDirRegExp, '') .replace(jsSuffixRegExp, '') }; } } /** * jQuery 1.4.3-1.5.x use a readyWait/ready() pairing to hold DOM * ready callbacks, but jQuery 1.6 supports a holdReady() API instead. * At some point remove the readyWait/ready() support and just stick * with using holdReady. */ function jQueryHoldReady($, shouldHold) { if ($.holdReady) { $.holdReady(shouldHold); } else if (shouldHold) { $.readyWait += 1; } else { $.ready(true); } } if (typeof define !== "undefined") { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== "undefined") { if (isFunction(requirejs)) { //Do not overwrite and existing requirejs instance. return; } else { cfg = requirejs; requirejs = undefined; } } //Allow for a require config object if (typeof require !== "undefined" && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } /** * Creates a new context for use in require and define calls. * Handle most of the heavy lifting. Do not want to use an object * with prototype here to avoid using "this" in require, in case it * needs to be used in more super secure envs that do not want this. * Also there should not be that many contexts in the page. Usually just * one for the default context, but could be extra for multiversion cases * or if a package needs a special context for a dependency that conflicts * with the standard context. */ function newContext(contextName) { var context, resume, config = { waitSeconds: 7, baseUrl: "./", paths: {}, pkgs: {}, catchError: {} }, defQueue = [], specified = { "require": true, "exports": true, "module": true }, urlMap = {}, defined = {}, loaded = {}, waiting = {}, waitAry = [], urlFetched = {}, managerCounter = 0, managerCallbacks = {}, plugins = {}, //Used to indicate which modules in a build scenario //need to be full executed. needFullExec = {}, fullExec = {}, resumeDepth = 0; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; (part = ary[i]); i++) { if (part === ".") { ary.splice(i, 1); i -= 1; } else if (part === "..") { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var pkgName, pkgConfig; //Adjust any relative paths. if (name && name.charAt(0) === ".") { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { if (config.pkgs[baseName]) { //If the baseName is a package name, then just treat it as one //name to concat the name with. baseName = [baseName]; } else { //Convert baseName to array, and lop off the last part, //so that . matches that "directory" and not name of the baseName's //module. For instance, baseName of "one/two/three", maps to //"one/two/three.js", but we want the directory, "one/two" for //this normalization. baseName = baseName.split("/"); baseName = baseName.slice(0, baseName.length - 1); } name = baseName.concat(name.split("/")); trimDots(name); //Some use of packages may use a . path to reference the //"main" module name, so normalize for that. pkgConfig = config.pkgs[(pkgName = name[0])]; name = name.join("/"); if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { name = pkgName; } } else if (name.indexOf("./") === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } return name; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap) { var index = name ? name.indexOf("!") : -1, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, normalizedName, url, pluginModule; if (index !== -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } if (prefix) { prefix = normalize(prefix, parentName); } //Account for relative paths if there is a base name. if (name) { if (prefix) { pluginModule = defined[prefix]; if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName); }); } else { normalizedName = normalize(name, parentName); } } else { //A regular module. normalizedName = normalize(name, parentName); url = urlMap[normalizedName]; if (!url) { //Calculate url for the module, if it has a name. //Use name here since nameToUrl also calls normalize, //and for relative names that are outside the baseUrl //this causes havoc. Was thinking of just removing //parentModuleMap to avoid extra normalization, but //normalize() still does a dot removal because of //issue #142, so just pass in name here and redo //the normalization. Paths outside baseUrl are just //messy to support. url = context.nameToUrl(name, null, parentModuleMap); //Store the URL mapping for later. urlMap[normalizedName] = url; } } } return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, url: url, originalName: originalName, fullName: prefix ? prefix + "!" + (normalizedName || '') : normalizedName }; } /** * Determine if priority loading is done. If so clear the priorityWait */ function isPriorityDone() { var priorityDone = true, priorityWait = config.priorityWait, priorityName, i; if (priorityWait) { for (i = 0; (priorityName = priorityWait[i]); i++) { if (!loaded[priorityName]) { priorityDone = false; break; } } if (priorityDone) { delete config.priorityWait; } } return priorityDone; } function makeContextModuleFunc(func, relModuleMap, enableBuildCallback) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName var args = aps.call(arguments, 0), lastArg; if (enableBuildCallback && isFunction((lastArg = args[args.length - 1]))) { lastArg.__requireJsBuild = true; } args.push(relModuleMap); return func.apply(null, args); }; } /** * Helper function that creates a require function object to give to * modules that ask for it as a dependency. It needs to be specific * per module because of the implication of path mappings that may * need to be relative to the module name. */ function makeRequire(relModuleMap, enableBuildCallback) { var modRequire = makeContextModuleFunc(context.require, relModuleMap, enableBuildCallback); mixin(modRequire, { nameToUrl: makeContextModuleFunc(context.nameToUrl, relModuleMap), toUrl: makeContextModuleFunc(context.toUrl, relModuleMap), defined: makeContextModuleFunc(context.requireDefined, relModuleMap), specified: makeContextModuleFunc(context.requireSpecified, relModuleMap), isBrowser: req.isBrowser }); return modRequire; } /* * Queues a dependency for checking after the loader is out of a * "paused" state, for example while a script file is being loaded * in the browser, where it may have many modules defined in it. */ function queueDependency(manager) { context.paused.push(manager); } function execManager(manager) { var i, ret, err, errFile, errModuleTree, cb = manager.callback, map = manager.map, fullName = map.fullName, args = manager.deps, listeners = manager.listeners, cjsModule; //Call the callback to define the module, if necessary. if (cb && isFunction(cb)) { if (config.catchError.define) { try { ret = req.execCb(fullName, manager.callback, args, defined[fullName]); } catch (e) { err = e; } } else { ret = req.execCb(fullName, manager.callback, args, defined[fullName]); } if (fullName) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. cjsModule = manager.cjsModule; if (cjsModule && cjsModule.exports !== undefined && //Make sure it is not already the exports value cjsModule.exports !== defined[fullName]) { ret = defined[fullName] = manager.cjsModule.exports; } else if (ret === undefined && manager.usingExports) { //exports already set the defined value. ret = defined[fullName]; } else { //Use the return value from the function. defined[fullName] = ret; //If this module needed full execution in a build //environment, mark that now. if (needFullExec[fullName]) { fullExec[fullName] = true; } } } } else if (fullName) { //May just be an object definition for the module. Only //worry about defining if have a module name. ret = defined[fullName] = cb; //If this module needed full execution in a build //environment, mark that now. if (needFullExec[fullName]) { fullExec[fullName] = true; } } //Clean up waiting. Do this before error calls, and before //calling back listeners, so that bookkeeping is correct //in the event of an error and error is reported in correct order, //since the listeners will likely have errors if the //onError function does not throw. if (waiting[manager.id]) { delete waiting[manager.id]; manager.isDone = true; context.waitCount -= 1; if (context.waitCount === 0) { //Clear the wait array used for cycles. waitAry = []; } } //Do not need to track manager callback now that it is defined. delete managerCallbacks[fullName]; //Allow instrumentation like the optimizer to know the order //of modules executed and their dependencies. if (req.onResourceLoad && !manager.placeholder) { req.onResourceLoad(context, map, manager.depArray); } if (err) { errFile = (fullName ? makeModuleMap(fullName).url : '') || err.fileName || err.sourceURL; errModuleTree = err.moduleTree; err = makeError('defineerror', 'Error evaluating ' + 'module "' + fullName + '" at location "' + errFile + '":\n' + err + '\nfileName:' + errFile + '\nlineNumber: ' + (err.lineNumber || err.line), err); err.moduleName = fullName; err.moduleTree = errModuleTree; return req.onError(err); } //Let listeners know of this manager's value. for (i = 0; (cb = listeners[i]); i++) { cb(ret); } return undefined; } /** * Helper that creates a callack function that is called when a dependency * is ready, and sets the i-th dependency for the manager as the * value passed to the callback generated by this function. */ function makeArgCallback(manager, i) { return function (value) { //Only do the work if it has not been done //already for a dependency. Cycle breaking //logic in forceExec could mean this function //is called more than once for a given dependency. if (!manager.depDone[i]) { manager.depDone[i] = true; manager.deps[i] = value; manager.depCount -= 1; if (!manager.depCount) { //All done, execute! execManager(manager); } } }; } function callPlugin(pluginName, depManager) { var map = depManager.map, fullName = map.fullName, name = map.name, plugin = plugins[pluginName] || (plugins[pluginName] = defined[pluginName]), load; //No need to continue if the manager is already //in the process of loading. if (depManager.loading) { return; } depManager.loading = true; load = function (ret) { depManager.callback = function () { return ret; }; execManager(depManager); loaded[depManager.id] = true; //The loading of this plugin //might have placed other things //in the paused queue. In particular, //a loader plugin that depends on //a different plugin loaded resource. resume(); }; //Allow plugins to load other code without having to know the //context or how to "complete" the load. load.fromText = function (moduleName, text) { /*jslint evil: true */ var hasInteractive = useInteractive; //Indicate a the module is in process of loading. loaded[moduleName] = false; context.scriptCount += 1; //Indicate this is not a "real" module, so do not track it //for builds, it does not map to a real file. context.fake[moduleName] = true; //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } req.exec(text); if (hasInteractive) { useInteractive = true; } //Support anonymous modules. context.completeLoad(moduleName); }; //No need to continue if the plugin value has already been //defined by a build. if (fullName in defined) { load(defined[fullName]); } else { //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(name, makeRequire(map.parentMap, true), load, config); } } /** * Adds the manager to the waiting queue. Only fully * resolved items should be in the waiting queue. */ function addWait(manager) { if (!waiting[manager.id]) { waiting[manager.id] = manager; waitAry.push(manager); context.waitCount += 1; } } /** * Function added to every manager object. Created out here * to avoid new function creation for each manager instance. */ function managerAdd(cb) { this.listeners.push(cb); } function getManager(map, shouldQueue) { var fullName = map.fullName, prefix = map.prefix, plugin = prefix ? plugins[prefix] || (plugins[prefix] = defined[prefix]) : null, manager, created, pluginManager, prefixMap; if (fullName) { manager = managerCallbacks[fullName]; } if (!manager) { created = true; manager = { //ID is just the full name, but if it is a plugin resource //for a plugin that has not been loaded, //then add an ID counter to it. id: (prefix && !plugin ? (managerCounter++) + '__p@:' : '') + (fullName || '__r@' + (managerCounter++)), map: map, depCount: 0, depDone: [], depCallbacks: [], deps: [], listeners: [], add: managerAdd }; specified[manager.id] = true; //Only track the manager/reuse it if this is a non-plugin //resource. Also only track plugin resources once //the plugin has been loaded, and so the fullName is the //true normalized value. if (fullName && (!prefix || plugins[prefix])) { managerCallbacks[fullName] = manager; } } //If there is a plugin needed, but it is not loaded, //first load the plugin, then continue on. if (prefix && !plugin) { prefixMap = makeModuleMap(prefix); //Clear out defined and urlFetched if the plugin was previously //loaded/defined, but not as full module (as in a build //situation). However, only do this work if the plugin is in //defined but does not have a module export value. if (prefix in defined && !defined[prefix]) { delete defined[prefix]; delete urlFetched[prefixMap.url]; } pluginManager = getManager(prefixMap, true); pluginManager.add(function (plugin) { //Create a new manager for the normalized //resource ID and have it call this manager when //done. var newMap = makeModuleMap(map.originalName, map.parentMap), normalizedManager = getManager(newMap, true); //Indicate this manager is a placeholder for the real, //normalized thing. Important for when trying to map //modules and dependencies, for instance, in a build. manager.placeholder = true; normalizedManager.add(function (resource) { manager.callback = function () { return resource; }; execManager(manager); }); }); } else if (created && shouldQueue) { //Indicate the resource is not loaded yet if it is to be //queued. loaded[manager.id] = false; queueDependency(manager); addWait(manager); } return manager; } function main(inName, depArray, callback, relModuleMap) { var moduleMap = makeModuleMap(inName, relModuleMap), name = moduleMap.name, fullName = moduleMap.fullName, manager = getManager(moduleMap), id = manager.id, deps = manager.deps, i, depArg, depName, depPrefix, cjsMod; if (fullName) { //If module already defined for context, or already loaded, //then leave. Also leave if jQuery is registering but it does //not match the desired version number in the config. if (fullName in defined || loaded[id] === true || (fullName === "jquery" && config.jQuery && config.jQuery !== callback().fn.jquery)) { return; } //Set specified/loaded here for modules that are also loaded //as part of a layer, where onScriptLoad is not fired //for those cases. Do this after the inline define and //dependency tracing is done. specified[id] = true; loaded[id] = true; //If module is jQuery set up delaying its dom ready listeners. if (fullName === "jquery" && callback) { jQueryCheck(callback()); } } //Attach real depArray and callback to the manager. Do this //only if the module has not been defined already, so do this after //the fullName checks above. IE can call main() more than once //for a module. manager.depArray = depArray; manager.callback = callback; //Add the dependencies to the deps field, and register for callbacks //on the dependencies. for (i = 0; i < depArray.length; i++) { depArg = depArray[i]; //There could be cases like in IE, where a trailing comma will //introduce a null dependency, so only treat a real dependency //value as a dependency. if (depArg) { //Split the dependency name into plugin and name parts depArg = makeModuleMap(depArg, (name ? moduleMap : relModuleMap)); depName = depArg.fullName; depPrefix = depArg.prefix; //Fix the name in depArray to be just the name, since //that is how it will be called back later. depArray[i] = depName; //Fast path CommonJS standard dependencies. if (depName === "require") { deps[i] = makeRequire(moduleMap); } else if (depName === "exports") { //CommonJS module spec 1.1 deps[i] = defined[fullName] = {}; manager.usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 manager.cjsModule = cjsMod = deps[i] = { id: name, uri: name ? context.nameToUrl(name, null, relModuleMap) : undefined, exports: defined[fullName] }; } else if (depName in defined && !(depName in waiting) && (!(fullName in needFullExec) || (fullName in needFullExec && fullExec[depName]))) { //Module already defined, and not in a build situation //where the module is a something that needs full //execution and this dependency has not been fully //executed. See r.js's requirePatch.js for more info //on fullExec. deps[i] = defined[depName]; } else { //Mark this dependency as needing full exec if //the current module needs full exec. if (fullName in needFullExec) { needFullExec[depName] = true; //Reset state so fully executed code will get //picked up correctly. delete defined[depName]; urlFetched[depArg.url] = false; } //Either a resource that is not loaded yet, or a plugin //resource for either a plugin that has not //loaded yet. manager.depCount += 1; manager.depCallbacks[i] = makeArgCallback(manager, i); getManager(depArg, true).add(manager.depCallbacks[i]); } } } //Do not bother tracking the manager if it is all done. if (!manager.depCount) { //All done, execute! execManager(manager); } else { addWait(manager); } } /** * Convenience method to call main for a define call that was put on * hold in the defQueue. */ function callDefMain(args) { main.apply(null, args); } /** * jQuery 1.4.3+ supports ways to hold off calling * calling jQuery ready callbacks until all scripts are loaded. Be sure * to track it if the capability exists.. Also, since jQuery 1.4.3 does * not register as a module, need to do some global inference checking. * Even if it does register as a module, not guaranteed to be the precise * name of the global. If a jQuery is tracked for this context, then go * ahead and register it as a module too, if not already in process. */ jQueryCheck = function (jqCandidate) { if (!context.jQuery) { var $ = jqCandidate || (typeof jQuery !== "undefined" ? jQuery : null); if ($) { //If a specific version of jQuery is wanted, make sure to only //use this jQuery if it matches. if (config.jQuery && $.fn.jquery !== config.jQuery) { return; } if ("holdReady" in $ || "readyWait" in $) { context.jQuery = $; //Manually create a "jquery" module entry if not one already //or in process. Note this could trigger an attempt at //a second jQuery registration, but does no harm since //the first one wins, and it is the same value anyway. callDefMain(["jquery", [], function () { return jQuery; }]); //Ask jQuery to hold DOM ready callbacks. if (context.scriptCount) { jQueryHoldReady($, true); context.jQueryIncremented = true; } } } } }; function forceExec(manager, traced) { if (manager.isDone) { return undefined; } var fullName = manager.map.fullName, depArray = manager.depArray, i, depName, depManager, prefix, prefixManager, value; if (fullName) { if (traced[fullName]) { return defined[fullName]; } traced[fullName] = true; } //Trace through the dependencies. if (depArray) { for (i = 0; i < depArray.length; i++) { //Some array members may be null, like if a trailing comma //IE, so do the explicit [i] access and check if it has a value. depName = depArray[i]; if (depName) { //First, make sure if it is a plugin resource that the //plugin is not blocked. prefix = makeModuleMap(depName).prefix; if (prefix && (prefixManager = waiting[prefix])) { forceExec(prefixManager, traced); } depManager = waiting[depName]; if (depManager && !depManager.isDone && loaded[depName]) { value = forceExec(depManager, traced); manager.depCallbacks[i](value); } } } } return fullName ? defined[fullName] : undefined; } /** * Checks if all modules for a context are loaded, and if so, evaluates the * new ones in right dependency order. * * @private */ function checkLoaded() { var waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = "", hasLoadedProp = false, stillLoading = false, prop, err, manager; //If there are items still in the paused queue processing wait. //This is particularly important in the sync case where each paused //item is processed right away but there may be more waiting. if (context.pausedCount > 0) { return undefined; } //Determine if priority loading is done. If so clear the priority. If //not, then do not check if (config.priorityWait) { if (isPriorityDone()) { //Call resume, since it could have //some waiting dependencies to trace. resume(); } else { return undefined; } } //See if anything is still in flight. for (prop in loaded) { if (!(prop in empty)) { hasLoadedProp = true; if (!loaded[prop]) { if (expired) { noLoads += prop + " "; } else { stillLoading = true; break; } } } } //Check for exit conditions. if (!hasLoadedProp && !context.waitCount) { //If the loaded object had no items, then the rest of //the work below does not need to be done. return undefined; } if (expired && noLoads) { //If wait time expired, throw error of unloaded modules. err = makeError("timeout", "Load timeout for modules: " + noLoads); err.requireType = "timeout"; err.requireModules = noLoads; return req.onError(err); } if (stillLoading || context.scriptCount) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } return undefined; } //If still have items in the waiting cue, but all modules have //been loaded, then it means there are some circular dependencies //that need to be broken. //However, as a waiting thing is fired, then it can add items to //the waiting cue, and those items should not be fired yet, so //make sure to redo the checkLoaded call after breaking a single //cycle, if nothing else loaded then this logic will pick it up //again. if (context.waitCount) { //Cycle through the waitAry, and call items in sequence. for (i = 0; (manager = waitAry[i]); i++) { forceExec(manager, {}); } //If anything got placed in the paused queue, run it down. if (context.paused.length) { resume(); } //Only allow this recursion to a certain depth. Only //triggered by errors in calling a module in which its //modules waiting on it cannot finish loading, or some circular //dependencies that then may add more dependencies. //The value of 5 is a bit arbitrary. Hopefully just one extra //pass, or two for the case of circular dependencies generating //more work that gets resolved in the sync node case. if (checkLoadedDepth < 5) { checkLoadedDepth += 1; checkLoaded(); } } checkLoadedDepth = 0; //Check for DOM ready, and nothing is waiting across contexts. req.checkReadyState(); return undefined; } /** * Resumes tracing of dependencies and then checks if everything is loaded. */ resume = function () { var manager, map, url, i, p, args, fullName; resumeDepth += 1; if (context.scriptCount <= 0) { //Synchronous envs will push the number below zero with the //decrement above, be sure to set it back to zero for good measure. //require() calls that also do not end up loading scripts could //push the number negative too. context.scriptCount = 0; } //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return req.onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { callDefMain(args); } } //Skip the resume of paused dependencies //if current context is in priority wait. if (!config.priorityWait || isPriorityDone()) { while (context.paused.length) { p = context.paused; context.pausedCount += p.length; //Reset paused list context.paused = []; for (i = 0; (manager = p[i]); i++) { map = manager.map; url = map.url; fullName = map.fullName; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (map.prefix) { callPlugin(map.prefix, manager); } else { //Regular dependency. if (!urlFetched[url] && !loaded[fullName]) { req.load(context, fullName, url); //Mark the URL as fetched, but only if it is //not an empty: URL, used by the optimizer. //In that case we need to be sure to call //load() for each module that is mapped to //empty: so that dependencies are satisfied //correctly. if (url.indexOf('empty:') !== 0) { urlFetched[url] = true; } } } } //Move the start time for timeout forward. context.startTime = (new Date()).getTime(); context.pausedCount -= p.length; } } //Only check if loaded when resume depth is 1. It is likely that //it is only greater than 1 in sync environments where a factory //function also then calls the callback-style require. In those //cases, the checkLoaded should not occur until the resume //depth is back at the top level. if (resumeDepth === 1) { checkLoaded(); } resumeDepth -= 1; return undefined; }; //Define the context object. Many of these fields are on here //just to make debugging easier. context = { contextName: contextName, config: config, defQueue: defQueue, waiting: waiting, waitCount: 0, specified: specified, loaded: loaded, urlMap: urlMap, urlFetched: urlFetched, scriptCount: 0, defined: defined, paused: [], pausedCount: 0, plugins: plugins, needFullExec: needFullExec, fake: {}, fullExec: fullExec, managerCallbacks: managerCallbacks, makeModuleMap: makeModuleMap, normalize: normalize, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { var paths, prop, packages, pkgs, packagePaths, requireWait; //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== "/") { cfg.baseUrl += "/"; } } //Save off the paths and packages since they require special processing, //they are additive. paths = config.paths; packages = config.packages; pkgs = config.pkgs; //Mix in the config values, favoring the new values over //existing ones in context.config. mixin(config, cfg, true); //Adjust paths if necessary. if (cfg.paths) { for (prop in cfg.paths) { if (!(prop in empty)) { paths[prop] = cfg.paths[prop]; } } config.paths = paths; } packagePaths = cfg.packagePaths; if (packagePaths || cfg.packages) { //Convert packagePaths into a packages config. if (packagePaths) { for (prop in packagePaths) { if (!(prop in empty)) { configurePackageDir(pkgs, packagePaths[prop], prop); } } } //Adjust packages if necessary. if (cfg.packages) { configurePackageDir(pkgs, cfg.packages); } //Done with modifications, assing packages back to context config config.pkgs = pkgs; } //If priority loading is in effect, trigger the loads now if (cfg.priority) { //Hold on to requireWait value, and reset it after done requireWait = context.requireWait; //Allow tracing some require calls to allow the fetching //of the priority config. context.requireWait = false; //But first, call resume to register any defined modules that may //be in a data-main built file before the priority config //call. Also grab any waiting define calls for this context. context.takeGlobalQueue(); resume(); context.require(cfg.priority); //Trigger a resume right away, for the case when //the script with the priority load is done as part //of a data-main call. In that case the normal resume //call will not happen because the scriptCount will be //at 1, since the script for data-main is being processed. resume(); //Restore previous state. context.requireWait = requireWait; config.priorityWait = cfg.priority; } //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, requireDefined: function (moduleName, relModuleMap) { return makeModuleMap(moduleName, relModuleMap).fullName in defined; }, requireSpecified: function (moduleName, relModuleMap) { return makeModuleMap(moduleName, relModuleMap).fullName in specified; }, require: function (deps, callback, relModuleMap) { var moduleName, fullName, moduleMap; if (typeof deps === "string") { if (isFunction(callback)) { //Invalid call return req.onError(makeError("requireargs", "Invalid require call")); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. //In this case deps is the moduleName and callback is //the relModuleMap if (req.get) { return req.get(context, deps, callback); } //Just return the module wanted. In this scenario, the //second arg (if passed) is just the relModuleMap. moduleName = deps; relModuleMap = callback; //Normalize module name, if it contains . or .. moduleMap = makeModuleMap(moduleName, relModuleMap); fullName = moduleMap.fullName; if (!(fullName in defined)) { return req.onError(makeError("notloaded", "Module name '" + moduleMap.fullName + "' has not been loaded yet for context: " + contextName)); } return defined[fullName]; } //Call main but only if there are dependencies or //a callback to call. if (deps && deps.length || callback) { main(null, deps, callback, relModuleMap); } //If the require call does not trigger anything new to load, //then resume the dependency processing. if (!context.requireWait) { while (!context.scriptCount && context.paused.length) { //For built layers, there can be some defined //modules waiting for intake into the context, //in particular module plugins. Take them. context.takeGlobalQueue(); resume(); } } return context.require; }, /** * Internal method to transfer globalQueue items to this context's * defQueue. */ takeGlobalQueue: function () { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(context.defQueue, [context.defQueue.length - 1, 0].concat(globalDefQueue)); globalDefQueue = []; } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var args; context.takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; break; } else if (args[0] === moduleName) { //Found matching define call for this script! break; } else { //Some other named define call, most likely the result //of a build layer that included many define calls. callDefMain(args); args = null; } } if (args) { callDefMain(args); } else { //A script that does not call define(), so just simulate //the call for it. Special exception for jQuery dynamic load. callDefMain([moduleName, [], moduleName === "jquery" && typeof jQuery !== "undefined" ? function () { return jQuery; } : null]); } //Doing this scriptCount decrement branching because sync envs //need to decrement after resume, otherwise it looks like //loading is complete after the first dependency is fetched. //For browsers, it works fine to decrement after, but it means //the checkLoaded setTimeout 50 ms cost is taken. To avoid //that cost, decrement beforehand. if (req.isAsync) { context.scriptCount -= 1; } resume(); if (!req.isAsync) { context.scriptCount -= 1; } }, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt, relModuleMap) { var index = moduleNamePlusExt.lastIndexOf("."), ext = null; if (index !== -1) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(moduleNamePlusExt, ext, relModuleMap); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. */ nameToUrl: function (moduleName, ext, relModuleMap) { var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, config = context.config; //Normalize module name if have a base relative module name to work from. moduleName = normalize(moduleName, relModuleMap && relModuleMap.fullName); //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash or ends with .js, it is just a plain file. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext ? ext : ""); } else { //A module that needs to be converted to a path. paths = config.paths; pkgs = config.pkgs; syms = moduleName.split("/"); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i--) { parentModule = syms.slice(0, i).join("/"); if (paths[parentModule]) { syms.splice(0, i, paths[parentModule]); break; } else if ((pkg = pkgs[parentModule])) { //If module name is just the package name, then looking //for the main module. if (moduleName === pkg.name) { pkgPath = pkg.location + '/' + pkg.main; } else { pkgPath = pkg.location; } syms.splice(0, i, pkgPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join("/") + (ext || ".js"); url = (url.charAt(0) === '/' || url.match(/^\w+:/) ? "" : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; } }; //Make these visible on the context so can be called at the very //end of the file to bootstrap context.jQueryCheck = jQueryCheck; context.resume = resume; return context; } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback) { //Find the right context, use default var contextName = defContextName, context, config; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== "string") { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = arguments[2]; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = contexts[contextName] || (contexts[contextName] = newContext(contextName)); if (config) { context.configure(config); } return context.require(deps, callback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } /** * Global require.toUrl(), to match global require, mostly useful * for debugging/work in the global space. */ req.toUrl = function (moduleNamePlusExt) { return contexts[defContextName].toUrl(moduleNamePlusExt); }; req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; s = req.s = { contexts: contexts, //Stores a list of URLs that should not get async script tag treatment. skipAsync: {} }; req.isAsync = req.isBrowser = isBrowser; if (isBrowser) { head = s.head = document.getElementsByTagName("head")[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: //http://dev.jquery.com/ticket/2709 baseElement = document.getElementsByTagName("base")[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = function (err) { throw err; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { req.resourcesReady(false); context.scriptCount += 1; req.attach(url, context, moduleName); //If tracking a jQuery, then make sure its ready callbacks //are put on hold to prevent its ready callbacks from //triggering too soon. if (context.jQuery && !context.jQueryIncremented) { jQueryHoldReady(context.jQuery, true); context.jQueryIncremented = true; } }; function getInteractiveScript() { var scripts, i, script; if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } scripts = document.getElementsByTagName('script'); for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) { if (script.readyState === 'interactive') { return (interactiveScript = script); } } return null; } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous functions if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = []; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps.length && isFunction(callback)) { //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, "") .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ["require"] : ["require", "exports", "module"]).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = currentlyAddingScript || getInteractiveScript(); if (node) { if (!name) { name = node.getAttribute("data-requiremodule"); } context = contexts[node.getAttribute("data-requirecontext")]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); return undefined; }; define.amd = { multiversion: true, plugins: true, jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a more environment specific call. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { return eval(text); }; /** * Executes a module callack function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ req.execCb = function (name, callback, args, exports) { return callback.apply(exports, args); }; /** * Adds a node to the DOM. Public function since used by the order plugin. * This method should not normally be called by outside code. */ req.addScriptToDom = function (node) { //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. currentlyAddingScript = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } currentlyAddingScript = null; }; /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. * * @private */ req.onScriptLoad = function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement, contextName, moduleName, context; if (evt.type === "load" || (node && readyRegExp.test(node.readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. contextName = node.getAttribute("data-requirecontext"); moduleName = node.getAttribute("data-requiremodule"); context = contexts[contextName]; contexts[contextName].completeLoad(moduleName); //Clean up script binding. Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. node.detachEvent("onreadystatechange", req.onScriptLoad); } else { node.removeEventListener("load", req.onScriptLoad, false); } } }; /** * Attaches the script represented by the URL to the current * environment. Right now only supports browser loading, * but can be redefined in other environments to do the right thing. * @param {String} url the url of the script to attach. * @param {Object} context the context that wants the script. * @param {moduleName} the name of the module that is associated with the script. * @param {Function} [callback] optional callback, defaults to require.onScriptLoad * @param {String} [type] optional type, defaults to text/javascript * @param {Function} [fetchOnlyFunction] optional function to indicate the script node * should be set up to fetch the script but do not attach it to the DOM * so that it can later be attached to execute it. This is a way for the * order plugin to support ordered loading in IE. Once the script is fetched, * but not executed, the fetchOnlyFunction will be called. */ req.attach = function (url, context, moduleName, callback, type, fetchOnlyFunction) { var node; if (isBrowser) { //In the browser so use a script tag callback = callback || req.onScriptLoad; node = context && context.config && context.config.xhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "html:script") : document.createElement("script"); node.type = type || (context && context.config.scriptType) || "text/javascript"; node.charset = "utf-8"; //Use async so Gecko does not block on executing the script if something //like a long-polling comet tag is being run first. Gecko likes //to evaluate scripts in DOM order, even for dynamic scripts. //It will fetch them async, but only evaluate the contents in DOM //order, so a long-polling script tag can delay execution of scripts //after it. But telling Gecko we expect async gets us the behavior //we want -- execute it whenever it is finished downloading. Only //Helps Firefox 3.6+ //Allow some URLs to not be fetched async. Mostly helps the order! //plugin node.async = !s.skipAsync[url]; if (context) { node.setAttribute("data-requirecontext", context.contextName); } node.setAttribute("data-requiremodule", moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in "interactive" //readyState at the time of the define call. useInteractive = true; if (fetchOnlyFunction) { //Need to use old school onreadystate here since //when the event fires and the node is not attached //to the DOM, the evt.srcElement is null, so use //a closure to remember the node. node.onreadystatechange = function (evt) { //Script loaded but not executed. //Clear loaded handler, set the real one that //waits for script execution. if (node.readyState === 'loaded') { node.onreadystatechange = null; node.attachEvent("onreadystatechange", callback); fetchOnlyFunction(node); } }; } else { node.attachEvent("onreadystatechange", callback); } } else { node.addEventListener("load", callback, false); } node.src = url; //Fetch only means waiting to attach to DOM after loaded. if (!fetchOnlyFunction) { req.addScriptToDom(node); } return node; } else if (isWebWorker) { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation that a build has been done so that //only one script needs to be loaded anyway. This may need to be //reevaluated if other use cases become common. importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } return null; }; //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser) { //Figure out baseUrl. Get it from the script tag with require.js in it. scripts = document.getElementsByTagName("script"); for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) { //Set the "head" where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. if ((dataMain = script.getAttribute('data-main'))) { if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. src = dataMain.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; //Set final config. cfg.baseUrl = subPath; //Strip off any trailing .js since dataMain is now //like a module name. dataMain = mainScript.replace(jsSuffixRegExp, ''); } //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain]; break; } } } //See if there is nothing waiting across contexts, and if not, trigger //resourcesReady. req.checkReadyState = function () { var contexts = s.contexts, prop; for (prop in contexts) { if (!(prop in empty)) { if (contexts[prop].waitCount) { return; } } } req.resourcesReady(true); }; /** * Internal function that is triggered whenever all scripts/resources * have been loaded by the loader. Can be overridden by other, for * instance the domReady plugin, which wants to know when all resources * are loaded. */ req.resourcesReady = function (isReady) { var contexts, context, prop; //First, set the public variable indicating that resources are loading. req.resourcesDone = isReady; if (req.resourcesDone) { //If jQuery with DOM ready delayed, release it now. contexts = s.contexts; for (prop in contexts) { if (!(prop in empty)) { context = contexts[prop]; if (context.jQueryIncremented) { jQueryHoldReady(context.jQuery, false); context.jQueryIncremented = false; } } } } }; //FF < 3.6 readyState fix. Needed so that domReady plugin //works well in that environment, since require.js is normally //loaded via an HTML script tag so it will be there before window load, //where the domReady plugin is more likely to be loaded after window load. req.pageLoaded = function () { if (document.readyState !== "complete") { document.readyState = "complete"; } }; if (isBrowser) { if (document.addEventListener) { if (!document.readyState) { document.readyState = "loading"; window.addEventListener("load", req.pageLoaded, false); } } } //Set up default context. If require was a configuration object, use that as base config. req(cfg); //If modules are built into require.js, then need to make sure dependencies are //traced. Use a setTimeout in the browser world, to allow all the modules to register //themselves. In a non-browser env, assume that modules are not built into require.js, //which seems odd to do on the server. if (req.isAsync && typeof setTimeout !== "undefined") { ctx = s.contexts[(cfg.context || defContextName)]; //Indicate that the script that includes require() is still loading, //so that require()'d dependencies are not traced until the end of the //file is parsed (approximated via the setTimeout call). ctx.requireWait = true; setTimeout(function () { ctx.requireWait = false; //Any modules included with the require.js file will be in the //global queue, assign them to this context. ctx.takeGlobalQueue(); if (!ctx.scriptCount) { ctx.resume(); } req.checkReadyState(); }, 0); } }()); /** * @license RequireJS order 1.0.0 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /*jslint nomen: false, plusplus: false, strict: false */ /*global require: false, define: false, window: false, document: false, setTimeout: false */ //Specify that requirejs optimizer should wrap this code in a closure that //maps the namespaced requirejs API to non-namespaced local variables. /*requirejs namespace: true */ (function () { //Sadly necessary browser inference due to differences in the way //that browsers load and execute dynamically inserted javascript //and whether the script/cache method works when ordered execution is //desired. Currently, Gecko and Opera do not load/fire onload for scripts with //type="script/cache" but they execute injected scripts in order //unless the 'async' flag is present. //However, this is all changing in latest browsers implementing HTML5 //spec. With compliant browsers .async true by default, and //if false, then it will execute in order. Favor that test first for forward //compatibility. var testScript = typeof document !== "undefined" && typeof window !== "undefined" && document.createElement("script"), supportsInOrderExecution = testScript && (testScript.async || ((window.opera && Object.prototype.toString.call(window.opera) === "[object Opera]") || //If Firefox 2 does not have to be supported, then //a better check may be: //('mozIsLocallyAvailable' in window.navigator) ("MozAppearance" in document.documentElement.style))), //This test is true for IE browsers, which will load scripts but only //execute them once the script is added to the DOM. supportsLoadSeparateFromExecute = testScript && testScript.readyState === 'uninitialized', readyRegExp = /^(complete|loaded)$/, cacheWaiting = [], cached = {}, scriptNodes = {}, scriptWaiting = []; //Done with the test script. testScript = null; //Callback used by the type="script/cache" callback that indicates a script //has finished downloading. function scriptCacheCallback(evt) { var node = evt.currentTarget || evt.srcElement, i, moduleName, resource; if (evt.type === "load" || readyRegExp.test(node.readyState)) { //Pull out the name of the module and the context. moduleName = node.getAttribute("data-requiremodule"); //Mark this cache request as loaded cached[moduleName] = true; //Find out how many ordered modules have loaded for (i = 0; (resource = cacheWaiting[i]); i++) { if (cached[resource.name]) { resource.req([resource.name], resource.onLoad); } else { //Something in the ordered list is not loaded, //so wait. break; } } //If just loaded some items, remove them from cacheWaiting. if (i > 0) { cacheWaiting.splice(0, i); } //Remove this script tag from the DOM //Use a setTimeout for cleanup because some older IE versions vomit //if removing a script node while it is being evaluated. setTimeout(function () { node.parentNode.removeChild(node); }, 15); } } /** * Used for the IE case, where fetching is done by creating script element * but not attaching it to the DOM. This function will be called when that * happens so it can be determined when the node can be attached to the * DOM to trigger its execution. */ function onFetchOnly(node) { var i, loadedNode, resourceName; //Mark this script as loaded. node.setAttribute('data-orderloaded', 'loaded'); //Cycle through waiting scripts. If the matching node for them //is loaded, and is in the right order, add it to the DOM //to execute the script. for (i = 0; (resourceName = scriptWaiting[i]); i++) { loadedNode = scriptNodes[resourceName]; if (loadedNode && loadedNode.getAttribute('data-orderloaded') === 'loaded') { delete scriptNodes[resourceName]; require.addScriptToDom(loadedNode); } else { break; } } //If just loaded some items, remove them from waiting. if (i > 0) { scriptWaiting.splice(0, i); } } define({ version: '1.0.0', load: function (name, req, onLoad, config) { var url = req.nameToUrl(name, null), node, context; //Make sure the async attribute is not set for any pathway involving //this script. require.s.skipAsync[url] = true; if (supportsInOrderExecution || config.isBuild) { //Just a normal script tag append, but without async attribute //on the script. req([name], onLoad); } else if (supportsLoadSeparateFromExecute) { //Just fetch the URL, but do not execute it yet. The //non-standards IE case. Really not so nice because it is //assuming and touching requrejs internals. OK though since //ordered execution should go away after a long while. context = require.s.contexts._; if (!context.urlFetched[url] && !context.loaded[name]) { //Indicate the script is being fetched. context.urlFetched[url] = true; //Stuff from require.load require.resourcesReady(false); context.scriptCount += 1; //Fetch the script now, remember it. node = require.attach(url, context, name, null, null, onFetchOnly); scriptNodes[name] = node; scriptWaiting.push(name); } //Do a normal require for it, once it loads, use it as return //value. req([name], onLoad); } else { //Credit to LABjs author Kyle Simpson for finding that scripts //with type="script/cache" allow scripts to be downloaded into //browser cache but not executed. Use that //so that subsequent addition of a real type="text/javascript" //tag will cause the scripts to be executed immediately in the //correct order. if (req.specified(name)) { req([name], onLoad); } else { cacheWaiting.push({ name: name, req: req, onLoad: onLoad }); require.attach(url, null, name, scriptCacheCallback, "script/cache"); } } } }); }());
lgpl-3.0
ocefpaf/iris
lib/iris/tests/unit/experimental/representation/__init__.py
267
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Unit tests for the :mod:`iris.experimental.representation` package."""
lgpl-3.0
mshvartsman/cddm
external/armadillo/include/armadillo_bits/spop_max_bones.hpp
1853
// Copyright (C) 2012-2015 Conrad Sanderson // Copyright (C) 2012-2014 Ryan Curtin // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! \addtogroup spop_max //! @{ class spop_max { public: template<typename T1> inline static void apply(SpMat<typename T1::elem_type>& out, const SpOp<T1, spop_max>& in); // template<typename T1> inline static void apply_proxy(SpMat<typename T1::elem_type>& out, const SpProxy<T1>& p, const uword dim, const typename arma_not_cx<typename T1::elem_type>::result* junk = 0); template<typename T1> inline static typename T1::elem_type vector_max(const T1& X, const typename arma_not_cx<typename T1::elem_type>::result* junk = 0); template<typename T1> inline static typename arma_not_cx<typename T1::elem_type>::result max(const SpBase<typename T1::elem_type, T1>& X); template<typename T1> inline static typename arma_not_cx<typename T1::elem_type>::result max_with_index(const SpProxy<T1>& P, uword& index_of_max_val); // template<typename T1> inline static void apply_proxy(SpMat<typename T1::elem_type>& out, const SpProxy<T1>& p, const uword dim, const typename arma_cx_only<typename T1::elem_type>::result* junk = 0); template<typename T1> inline static typename T1::elem_type vector_max(const T1& X, const typename arma_cx_only<typename T1::elem_type>::result* junk = 0); template<typename T1> inline static typename arma_cx_only<typename T1::elem_type>::result max(const SpBase<typename T1::elem_type, T1>& X); template<typename T1> inline static typename arma_cx_only<typename T1::elem_type>::result max_with_index(const SpProxy<T1>& P, uword& index_of_max_val); }; //! @}
lgpl-3.0
Tybion/community-edition
projects/repository/source/java/org/alfresco/repo/management/subsystems/SubsystemProxyFactory.java
9195
/* * Copyright (C) 2005-2012 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.management.subsystems; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * A factory bean, normally used in conjunction with {@link ChildApplicationContextFactory} allowing selected * interfaces in a child application context to be proxied by a bean in the parent application context. This allows * 'hot-swapping' and reconfiguration of entire subsystems. */ public class SubsystemProxyFactory extends ProxyFactoryBean implements ApplicationContextAware { private static final long serialVersionUID = -4186421942840611218L; /** The source application context factory. */ private ApplicationContextFactory sourceApplicationContextFactory; private String sourceApplicationContextFactoryName; private ApplicationContext applicationContext; /** An optional bean name to look up in the source application context **/ private String sourceBeanName; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private ApplicationContext context; private Object sourceBean; private Object defaultBean; private Map <Class<?>, Object> typedBeans = new HashMap<Class<?>, Object>(7); /** * Instantiates a new managed subsystem proxy factory. */ public SubsystemProxyFactory() { addAdvisor(new DefaultPointcutAdvisor(new MethodInterceptor() { public Object invoke(MethodInvocation mi) throws Throwable { Method method = mi.getMethod(); try { return method.invoke(locateBean(mi), mi.getArguments()); } catch (InvocationTargetException e) { // Unwrap invocation target exceptions throw e.getTargetException(); } } })); } @SuppressWarnings("unchecked") @Override public void setInterfaces(Class[] interfaces) { super.setInterfaces(interfaces); // Make it possible to export the object via JMX setTargetClass(getObjectType()); } /** * Sets the source application context factory by name. * * @param sourceApplicationContextFactoryName * the name of the sourceApplicationContextFactory to set */ public void setSourceApplicationContextFactoryName(String sourceApplicationContextFactoryName) { this.sourceApplicationContextFactoryName = sourceApplicationContextFactoryName; } /** * Sets the source application context factory by reference * * @param sourceApplicationContextFactory * the sourceApplicationContextFactory to set */ public void setSourceApplicationContextFactory(ApplicationContextFactory sourceApplicationContextFactory) { this.sourceApplicationContextFactory = sourceApplicationContextFactory; } private ApplicationContextFactory getSourceApplicationContextFactory() { if (sourceApplicationContextFactory != null) { return sourceApplicationContextFactory; } else { try { return applicationContext.getBean(sourceApplicationContextFactoryName, ApplicationContextFactory.class); } catch (NoSuchBeanDefinitionException e) { return null; } } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * Sets an optional bean name to target all calls to in the source application context. If not set, an appropriate * bean is looked up based on method class. * * @param sourceBeanName * the sourceBeanName to set */ public void setSourceBeanName(String sourceBeanName) { this.sourceBeanName = sourceBeanName; } /** * Sets an optional default bean to be used if the target bean is not found. Generally used when a subsystem does not * exist. * * @param defaultBean * the defaultBean to set */ public void setDefaultBean(Object defaultBean) { this.defaultBean = defaultBean; } // Bring our cached copies of the source beans in line with the application context factory, using a RW lock to // ensure consistency protected Object locateBean(MethodInvocation mi) { boolean haveWriteLock = false; this.lock.readLock().lock(); try { ApplicationContextFactory sourceApplicationContextFactory = getSourceApplicationContextFactory(); if (sourceApplicationContextFactory != null) { ApplicationContext newContext = sourceApplicationContextFactory.getApplicationContext(); if (this.context != newContext) { // Upgrade the lock this.lock.readLock().unlock(); this.lock.writeLock().lock(); haveWriteLock = true; newContext = sourceApplicationContextFactory.getApplicationContext(); this.context = newContext; this.typedBeans.clear(); this.sourceBean = null; if (this.sourceBeanName != null) { this.sourceBean = newContext.getBean(this.sourceBeanName); } } if (this.sourceBean == null) { Method method = mi.getMethod(); Class<?> type = method.getDeclaringClass(); Object bean = this.typedBeans.get(type); if (bean == null) { // Upgrade the lock if necessary if (!haveWriteLock) { this.lock.readLock().unlock(); this.lock.writeLock().lock(); haveWriteLock = true; } bean = this.typedBeans.get(type); if (bean == null) { Map<?, ?> beans = this.context.getBeansOfType(type); if (beans.size() == 0 && defaultBean != null) { bean = defaultBean; } else { if (beans.size() != 1) { throw new RuntimeException("Don't know where to route call to method " + method); } bean = beans.values().iterator().next(); this.typedBeans.put(type, bean); } } } return bean; } return this.sourceBean; } else { return defaultBean; } } finally { if (haveWriteLock) { this.lock.writeLock().unlock(); } else { this.lock.readLock().unlock(); } } } }
lgpl-3.0
huberflores/Energy-AwareOffloading-IoT
Tools/libraries/WiFlySerial/Examples/WFSv3/WFSEthernet.cpp
7592
/* * WFSEthernet.cpp * Arduino Ethernet class for wifi devices * Based on Arduino 1.0 Ethernet class * * Credits: * First to the Arduino Ethernet team for their model upon which this is based. * Modifications are * Copyright GPL 2.1 Tom Waldock 2012 Version 1.07 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <WiFlySerial.h> #include "WFSEthernet.h" #include <Time.h> //#include "Dhcp.h" // XXX: don't make assumptions about the value of MAX_SOCK_NUM. uint8_t WFSEthernetClass::_state[MAX_SOCK_NUM] = { 0, 0, 0, 0 }; uint16_t WFSEthernetClass::_server_port[MAX_SOCK_NUM] = { 0, 0, 0, 0 }; // Function for setSyncProvider time_t WFSGetSyncTime() { // wifly returns UTC time. time_t tCurrent = (time_t) wifi.getTime(); // DebugPrint( "RESYNC TIME FROM WIFLY *****" ); wifi.exitCommandMode(); return tCurrent; } //init //Allows device to prepare for operations. // // Parameters: none // Returns true on success, false on failure. boolean WFSEthernetClass::initDevice() { return wifi.begin(); } //configure // Sets up modes of operation. // //Parameters // AuthMode - authentication modes // JoinMode - Means of joining a network // DHCPMode - Options for DHCP // // Returns true on success, false on failure. boolean WFSEthernetClass::configure(uint8_t AuthMode, uint8_t JoinMode, uint8_t DHCPMode) { return wifi.setAuthMode(AuthMode) | wifi.setJoinMode(JoinMode) | wifi.setDHCPMode(DHCPMode) ; } // credentials // Sets wifi name and passphrase/key // // Parameters // pSSID SSID to join // pPassphrase WPA/2 Passphrase or WEP key // // Returns true on success, false on failure. boolean WFSEthernetClass::credentials( char* pSSID, char* pPassphrase) { boolean bReturn = ( wifi.setPassphrase(pPassphrase) & wifi.setSSID(pSSID) ); return bReturn; } // begin()s // call init(), then configure(), then credentials() /// BEFORE calling begin(). // fewer-parameter begins cascade to more-parameter methods. // work really happens at last method. int WFSEthernetClass::begin() { // Initialise the basic info WFSIPAddress ip_addr(0,0,0,0); return begin(ip_addr); } int WFSEthernetClass::begin( WFSIPAddress local_ip) { // Assume the DNS server will be the machine on the same network as the local IP // but with last octet being '1' WFSIPAddress dns_server = local_ip; dns_server[3] = 1; return begin( local_ip, dns_server); } int WFSEthernetClass::begin( WFSIPAddress local_ip, WFSIPAddress dns_server) { // Assume the gateway will be the machine on the same network as the local IP // but with last octet being '1' WFSIPAddress gateway = local_ip; gateway[3] = 1; return begin( local_ip, dns_server, gateway); } int WFSEthernetClass::begin( WFSIPAddress local_ip, WFSIPAddress dns_server, WFSIPAddress gateway) { WFSIPAddress subnet(255, 255, 255, 0); return begin( local_ip, dns_server, gateway, subnet); } int WFSEthernetClass::begin( WFSIPAddress local_ip, WFSIPAddress dns_server, WFSIPAddress gateway, WFSIPAddress subnet) { wifi.begin(); // Arduino-WiFly communication-stability settings char bufRequest[COMMAND_BUFFER_SIZE]; // Set echo off wifi.SendCommand("set u m 0x1",">",bufRequest, COMMAND_BUFFER_SIZE); // Auto-disconnect after 30 seconds of idle connection. wifi.SendCommand( "set comm idle 30",">" ,bufRequest, COMMAND_BUFFER_SIZE) ; // Auto-sends TCP packet if no additional bytes provided from Arduino (ms). wifi.SendCommand( "set comm time 1000",">",bufRequest, COMMAND_BUFFER_SIZE); // Auto-sends TCP packet once this number of bytes provided from Arduino. wifi.SendCommand("set comm size 256",">",bufRequest, COMMAND_BUFFER_SIZE); // if already joined then leave first wifi.getDeviceStatus(); if (wifi.isAssociated() ) { Serial << "leaving" << endl; wifi.leave(); } // Try to join network based on provided (?) settings. int iRetry = 0; boolean bJoined = false; while ( (!bJoined ) && (iRetry < COMMAND_RETRY_ATTEMPTS) ) { Serial << F("Trying to join...") << ( ( bJoined = wifi.join() ) ? F(" ok ") : F(" failed ") ) ; iRetry++; } if ( bJoined ) { Serial << "Joined - setting addresses."; char bufAddr[IP_ADDR_WIDTH]; if (local_ip != WFSIPAddress(0,0,0,0) ){ Serial << "Set local IP"; wifi.setIP(IP_ArrayToBuffer( local_ip._address, bufAddr, IP_ADDR_WIDTH)); } if (subnet != WFSIPAddress(0,0,0,0) ){ wifi.setNetMask(IP_ArrayToBuffer(subnet._address, bufAddr, IP_ADDR_WIDTH)); } if (gateway != WFSIPAddress(0,0,0,1) ){ wifi.setGateway(IP_ArrayToBuffer(gateway._address, bufAddr, IP_ADDR_WIDTH)); } if (dns_server != WFSIPAddress(0,0,0,1) ){ wifi.setDNS(IP_ArrayToBuffer(dns_server._address, bufAddr, IP_ADDR_WIDTH)); } return true; } else { // DebugPrint("Failed to join..."); return false; } } boolean WFSEthernetClass::setNTPServer( char* pNTPServer, float fTimeZoneOffsetHrs ) { char bufRequest[ SMALL_COMMAND_BUFFER_SIZE ]; // Set NTP server, update frequency, wifi.setNTP(pNTPServer); wifi.SendCommand((char*) F("set time enable 60 "), WiFlyFixedPrompts[WIFLY_MSG_PROMPT] ,bufRequest, SMALL_COMMAND_BUFFER_SIZE); // set WiFly's time sync frequency with NTP server. wifi.setNTP_Update_Frequency(WIFLY_NTP_SYNC_INTERVAL); // Forces update of time. wifi.SendCommand((char*) F("time"), WiFlyFixedPrompts[WIFLY_MSG_PROMPT] ,bufRequest, SMALL_COMMAND_BUFFER_SIZE); wifi.setNTP_UTC_Offset ( fTimeZoneOffsetHrs ); setTime( wifi.getTime() ); // Set timezone adjustment: PST is -8h. Adjust to your local timezone. delay(1000); setSyncProvider( WFSGetSyncTime ); // Set Arduino's time sync frequency with WiFly setSyncInterval( WIFLY_TIME_SYNC_INTERVAL ); return true; } WFSIPAddress WFSEthernetClass::localIP() { WFSIPAddress ret; char bufAddr[COMMAND_BUFFER_SIZE]; wifi.getIP( bufAddr, COMMAND_BUFFER_SIZE ); BufferToIP_Array(bufAddr, ret._address); return ret; } WFSIPAddress WFSEthernetClass::subnetMask() { WFSIPAddress ret; char bufAddr[SMALL_COMMAND_BUFFER_SIZE]; wifi.getNetMask( bufAddr, SMALL_COMMAND_BUFFER_SIZE ); BufferToIP_Array(bufAddr, ret._address); return ret; } WFSIPAddress WFSEthernetClass::gatewayIP() { WFSIPAddress ret; char bufAddr[SMALL_COMMAND_BUFFER_SIZE]; wifi.getGateway( bufAddr, SMALL_COMMAND_BUFFER_SIZE ); BufferToIP_Array(bufAddr, ret._address); return ret; } WFSIPAddress WFSEthernetClass::dnsServerIP() { WFSIPAddress ret; char bufAddr[SMALL_COMMAND_BUFFER_SIZE]; wifi.getDNS( bufAddr, SMALL_COMMAND_BUFFER_SIZE ); BufferToIP_Array(bufAddr, ret._address); return ret; } WFSEthernetClass WFSEthernet; WiFlySerial wifi(ARDUINO_RX_PIN,ARDUINO_TX_PIN);
lgpl-3.0
Nikoli/youtube-dl
youtube_dl/downloader/f4m.py
15107
from __future__ import division, unicode_literals import base64 import io import itertools import os import time import xml.etree.ElementTree as etree from .common import FileDownloader from .http import HttpFD from ..compat import ( compat_urlparse, compat_urllib_error, ) from ..utils import ( struct_pack, struct_unpack, encodeFilename, sanitize_open, xpath_text, ) class FlvReader(io.BytesIO): """ Reader for Flv files The file format is documented in https://www.adobe.com/devnet/f4v.html """ # Utility functions for reading numbers and strings def read_unsigned_long_long(self): return struct_unpack('!Q', self.read(8))[0] def read_unsigned_int(self): return struct_unpack('!I', self.read(4))[0] def read_unsigned_char(self): return struct_unpack('!B', self.read(1))[0] def read_string(self): res = b'' while True: char = self.read(1) if char == b'\x00': break res += char return res def read_box_info(self): """ Read a box and return the info as a tuple: (box_size, box_type, box_data) """ real_size = size = self.read_unsigned_int() box_type = self.read(4) header_end = 8 if size == 1: real_size = self.read_unsigned_long_long() header_end = 16 return real_size, box_type, self.read(real_size - header_end) def read_asrt(self): # version self.read_unsigned_char() # flags self.read(3) quality_entry_count = self.read_unsigned_char() # QualityEntryCount for i in range(quality_entry_count): self.read_string() segment_run_count = self.read_unsigned_int() segments = [] for i in range(segment_run_count): first_segment = self.read_unsigned_int() fragments_per_segment = self.read_unsigned_int() segments.append((first_segment, fragments_per_segment)) return { 'segment_run': segments, } def read_afrt(self): # version self.read_unsigned_char() # flags self.read(3) # time scale self.read_unsigned_int() quality_entry_count = self.read_unsigned_char() # QualitySegmentUrlModifiers for i in range(quality_entry_count): self.read_string() fragments_count = self.read_unsigned_int() fragments = [] for i in range(fragments_count): first = self.read_unsigned_int() first_ts = self.read_unsigned_long_long() duration = self.read_unsigned_int() if duration == 0: discontinuity_indicator = self.read_unsigned_char() else: discontinuity_indicator = None fragments.append({ 'first': first, 'ts': first_ts, 'duration': duration, 'discontinuity_indicator': discontinuity_indicator, }) return { 'fragments': fragments, } def read_abst(self): # version self.read_unsigned_char() # flags self.read(3) self.read_unsigned_int() # BootstrapinfoVersion # Profile,Live,Update,Reserved flags = self.read_unsigned_char() live = flags & 0x20 != 0 # time scale self.read_unsigned_int() # CurrentMediaTime self.read_unsigned_long_long() # SmpteTimeCodeOffset self.read_unsigned_long_long() self.read_string() # MovieIdentifier server_count = self.read_unsigned_char() # ServerEntryTable for i in range(server_count): self.read_string() quality_count = self.read_unsigned_char() # QualityEntryTable for i in range(quality_count): self.read_string() # DrmData self.read_string() # MetaData self.read_string() segments_count = self.read_unsigned_char() segments = [] for i in range(segments_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b'asrt' segment = FlvReader(box_data).read_asrt() segments.append(segment) fragments_run_count = self.read_unsigned_char() fragments = [] for i in range(fragments_run_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b'afrt' fragments.append(FlvReader(box_data).read_afrt()) return { 'segments': segments, 'fragments': fragments, 'live': live, } def read_bootstrap_info(self): total_size, box_type, box_data = self.read_box_info() assert box_type == b'abst' return FlvReader(box_data).read_abst() def read_bootstrap_info(bootstrap_bytes): return FlvReader(bootstrap_bytes).read_bootstrap_info() def build_fragments_list(boot_info): """ Return a list of (segment, fragment) for each fragment in the video """ res = [] segment_run_table = boot_info['segments'][0] fragment_run_entry_table = boot_info['fragments'][0]['fragments'] first_frag_number = fragment_run_entry_table[0]['first'] fragments_counter = itertools.count(first_frag_number) for segment, fragments_count in segment_run_table['segment_run']: for _ in range(fragments_count): res.append((segment, next(fragments_counter))) if boot_info['live']: res = res[-2:] return res def write_unsigned_int(stream, val): stream.write(struct_pack('!I', val)) def write_unsigned_int_24(stream, val): stream.write(struct_pack('!I', val)[1:]) def write_flv_header(stream): """Writes the FLV header to stream""" # FLV header stream.write(b'FLV\x01') stream.write(b'\x05') stream.write(b'\x00\x00\x00\x09') stream.write(b'\x00\x00\x00\x00') def write_metadata_tag(stream, metadata): """Writes optional metadata tag to stream""" SCRIPT_TAG = b'\x12' FLV_TAG_HEADER_LEN = 11 if metadata: stream.write(SCRIPT_TAG) write_unsigned_int_24(stream, len(metadata)) stream.write(b'\x00\x00\x00\x00\x00\x00\x00') stream.write(metadata) write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata)) def _add_ns(prop): return '{http://ns.adobe.com/f4m/1.0}%s' % prop class HttpQuietDownloader(HttpFD): def to_screen(self, *args, **kargs): pass class F4mFD(FileDownloader): """ A downloader for f4m manifests or AdobeHDS. """ def _get_unencrypted_media(self, doc): media = doc.findall(_add_ns('media')) if not media: self.report_error('No media found') for e in (doc.findall(_add_ns('drmAdditionalHeader')) + doc.findall(_add_ns('drmAdditionalHeaderSet'))): # If id attribute is missing it's valid for all media nodes # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute if 'id' not in e.attrib: self.report_error('Missing ID in f4m DRM') media = list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and 'drmAdditionalHeaderSetId' not in e.attrib, media)) if not media: self.report_error('Unsupported DRM') return media def _get_bootstrap_from_url(self, bootstrap_url): bootstrap = self.ydl.urlopen(bootstrap_url).read() return read_bootstrap_info(bootstrap) def _update_live_fragments(self, bootstrap_url, latest_fragment): fragments_list = [] retries = 30 while (not fragments_list) and (retries > 0): boot_info = self._get_bootstrap_from_url(bootstrap_url) fragments_list = build_fragments_list(boot_info) fragments_list = [f for f in fragments_list if f[1] > latest_fragment] if not fragments_list: # Retry after a while time.sleep(5.0) retries -= 1 if not fragments_list: self.report_error('Failed to update fragments') return fragments_list def _parse_bootstrap_node(self, node, base_url): if node.text is None: bootstrap_url = compat_urlparse.urljoin( base_url, node.attrib['url']) boot_info = self._get_bootstrap_from_url(bootstrap_url) else: bootstrap_url = None bootstrap = base64.b64decode(node.text.encode('ascii')) boot_info = read_bootstrap_info(bootstrap) return (boot_info, bootstrap_url) def real_download(self, filename, info_dict): man_url = info_dict['url'] requested_bitrate = info_dict.get('tbr') self.to_screen('[download] Downloading f4m manifest') manifest = self.ydl.urlopen(man_url).read() doc = etree.fromstring(manifest) formats = [(int(f.attrib.get('bitrate', -1)), f) for f in self._get_unencrypted_media(doc)] if requested_bitrate is None: # get the best format formats = sorted(formats, key=lambda f: f[0]) rate, media = formats[-1] else: rate, media = list(filter( lambda f: int(f[0]) == requested_bitrate, formats))[0] base_url = compat_urlparse.urljoin(man_url, media.attrib['url']) bootstrap_node = doc.find(_add_ns('bootstrapInfo')) boot_info, bootstrap_url = self._parse_bootstrap_node(bootstrap_node, base_url) live = boot_info['live'] metadata_node = media.find(_add_ns('metadata')) if metadata_node is not None: metadata = base64.b64decode(metadata_node.text.encode('ascii')) else: metadata = None fragments_list = build_fragments_list(boot_info) if self.params.get('test', False): # We only download the first fragment fragments_list = fragments_list[:1] total_frags = len(fragments_list) # For some akamai manifests we'll need to add a query to the fragment url akamai_pv = xpath_text(doc, _add_ns('pv-2.0')) self.report_destination(filename) http_dl = HttpQuietDownloader( self.ydl, { 'continuedl': True, 'quiet': True, 'noprogress': True, 'ratelimit': self.params.get('ratelimit', None), 'test': self.params.get('test', False), } ) tmpfilename = self.temp_name(filename) (dest_stream, tmpfilename) = sanitize_open(tmpfilename, 'wb') write_flv_header(dest_stream) if not live: write_metadata_tag(dest_stream, metadata) # This dict stores the download progress, it's updated by the progress # hook state = { 'status': 'downloading', 'downloaded_bytes': 0, 'frag_index': 0, 'frag_count': total_frags, 'filename': filename, 'tmpfilename': tmpfilename, } start = time.time() def frag_progress_hook(s): if s['status'] not in ('downloading', 'finished'): return frag_total_bytes = s.get('total_bytes', 0) if s['status'] == 'finished': state['downloaded_bytes'] += frag_total_bytes state['frag_index'] += 1 estimated_size = ( (state['downloaded_bytes'] + frag_total_bytes) / (state['frag_index'] + 1) * total_frags) time_now = time.time() state['total_bytes_estimate'] = estimated_size state['elapsed'] = time_now - start if s['status'] == 'finished': progress = self.calc_percent(state['frag_index'], total_frags) else: frag_downloaded_bytes = s['downloaded_bytes'] frag_progress = self.calc_percent(frag_downloaded_bytes, frag_total_bytes) progress = self.calc_percent(state['frag_index'], total_frags) progress += frag_progress / float(total_frags) state['eta'] = self.calc_eta( start, time_now, estimated_size, state['downloaded_bytes'] + frag_downloaded_bytes) state['speed'] = s.get('speed') self._hook_progress(state) http_dl.add_progress_hook(frag_progress_hook) frags_filenames = [] while fragments_list: seg_i, frag_i = fragments_list.pop(0) name = 'Seg%d-Frag%d' % (seg_i, frag_i) url = base_url + name if akamai_pv: url += '?' + akamai_pv.strip(';') frag_filename = '%s-%s' % (tmpfilename, name) try: success = http_dl.download(frag_filename, {'url': url}) if not success: return False with open(frag_filename, 'rb') as down: down_data = down.read() reader = FlvReader(down_data) while True: _, box_type, box_data = reader.read_box_info() if box_type == b'mdat': dest_stream.write(box_data) break if live: os.remove(frag_filename) else: frags_filenames.append(frag_filename) except (compat_urllib_error.HTTPError, ) as err: if live and (err.code == 404 or err.code == 410): # We didn't keep up with the live window. Continue # with the next available fragment. msg = 'Fragment %d unavailable' % frag_i self.report_warning(msg) fragments_list = [] else: raise if not fragments_list and live and bootstrap_url: fragments_list = self._update_live_fragments(bootstrap_url, frag_i) total_frags += len(fragments_list) if fragments_list and (fragments_list[0][1] > frag_i + 1): msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1)) self.report_warning(msg) dest_stream.close() elapsed = time.time() - start self.try_rename(tmpfilename, filename) for frag_file in frags_filenames: os.remove(frag_file) fsize = os.path.getsize(encodeFilename(filename)) self._hook_progress({ 'downloaded_bytes': fsize, 'total_bytes': fsize, 'filename': filename, 'status': 'finished', 'elapsed': elapsed, }) return True
unlicense
astachurski/Karabiner
src/core/kext/VirtualKey/VK_JIS_YEN.hpp
295
#ifndef VIRTUALKEY_VK_JIS_YEN_HPP #define VIRTUALKEY_VK_JIS_YEN_HPP namespace org_pqrs_Karabiner { namespace VirtualKey { class VK_JIS_YEN final { public: static bool handle(const Params_KeyboardEventCallBack& params, AutogenId autogenId, PhysicalEventType physicalEventType); }; } } #endif
unlicense
mmelvin0/EnderIO
src/main/java/crazypants/enderio/conduit/gas/GasUtil.java
2023
package crazypants.enderio.conduit.gas; import mekanism.api.gas.GasStack; import mekanism.api.gas.IGasHandler; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import com.enderio.core.common.util.BlockCoord; import cpw.mods.fml.common.ModAPIManager; import cpw.mods.fml.common.Optional.Method; import crazypants.enderio.conduit.IConduitBundle; import crazypants.enderio.config.Config; public final class GasUtil { private static boolean useCheckPerformed = false; private static boolean isGasConduitEnabled = false; public static final String API_NAME = "MekanismAPI|gas"; public static boolean isGasConduitEnabled() { if(!useCheckPerformed) { if(Config.isGasConduitEnabled) { isGasConduitEnabled = ModAPIManager.INSTANCE.hasAPI(API_NAME); } else { isGasConduitEnabled = false; } useCheckPerformed = true; } return isGasConduitEnabled; } @Method(modid = API_NAME) public static IGasHandler getExternalGasHandler(IBlockAccess world, BlockCoord bc) { IGasHandler con = getGasHandler(world, bc); return (con != null && !(con instanceof IConduitBundle)) ? con : null; } @Method(modid = API_NAME) public static IGasHandler getGasHandler(IBlockAccess world, BlockCoord bc) { return getGasHandler(world, bc.x, bc.y, bc.z); } @Method(modid = API_NAME) public static IGasHandler getGasHandler(IBlockAccess world, int x, int y, int z) { TileEntity te = world.getTileEntity(x, y, z); return getGasHandler(te); } @Method(modid = API_NAME) public static IGasHandler getGasHandler(TileEntity te) { if(te instanceof IGasHandler) { return (IGasHandler) te; } return null; } @Method(modid = API_NAME) public static boolean isGasValid(GasStack gas) { if(gas != null) { String name = gas.getGas().getLocalizedName(); if(name != null && !name.trim().isEmpty()) { return true; } } return false; } private GasUtil() { } }
unlicense
fathi-hindi/oneplace
vendor/magento/magento2-base/setup/src/Magento/Setup/Controller/SelectVersion.php
2099
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Setup\Controller; use Magento\Composer\InfoCommand; use Magento\Setup\Model\SystemPackage; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\JsonModel; use Zend\View\Model\ViewModel; /** * Controller for selecting version */ class SelectVersion extends AbstractActionController { /** * @var SystemPackage */ protected $systemPackage; /** * @param SystemPackage $systemPackage */ public function __construct( SystemPackage $systemPackage ) { $this->systemPackage = $systemPackage; } /** * @return ViewModel|\Zend\Http\Response */ public function indexAction() { $view = new ViewModel; $view->setTerminal(true); $view->setTemplate('/magento/setup/select-version.phtml'); return $view; } /** * Gets system package and versions * * @return JsonModel */ public function systemPackageAction() { $data = []; try { $data['packages'] = $this->systemPackage->getPackageVersions(); $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; } catch (\Exception $e) { $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; $data['error'] = $e->getMessage(); } $data['responseType'] = $responseType; return new JsonModel($data); } /** * Gets installed system package * * @return JsonModel */ public function installedSystemPackageAction() { $data = []; try { $data['packages'] = $this->systemPackage->getInstalledSystemPackages([]); $data['responseType'] = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; } catch (\Exception $e) { $data['error'] = $e->getMessage(); $data['responseType'] = ResponseTypeInterface::RESPONSE_TYPE_ERROR; } return new JsonModel($data); } }
unlicense
Sphearion/screeps-1
ScreepsAutocomplete/Structures/StructureNuker.js
2180
/** * Launches a nuke to another room dealing huge damage to the landing area. * Each launch has a cooldown and requires energy and ghodium resources. * Launching creates a Nuke object at the target room position which is visible to any player until it is landed. * Incoming nuke cannot be moved or cancelled. Nukes cannot be launched from or to novice rooms. * * @class * @extends {OwnedStructure} * * @see {@link http://support.screeps.com/hc/en-us/articles/208488255-StructureNuker} */ StructureNuker = function() { }; StructureNuker.prototype = { /** * The amount of energy containing in this structure. * * @see {@link http://support.screeps.com/hc/en-us/articles/208488255-StructureNuker#energy} * * @type {number} */ energy: 0, /** * The total amount of energy this structure can contain. * * @see {@link http://support.screeps.com/hc/en-us/articles/208488255-StructureNuker#energyCapacity} * * @type {number} */ energyCapacity: 0, /** * The amount of ghodium containing in this structure. * * @see {@link http://support.screeps.com/hc/en-us/articles/208488255-StructureNuker#ghodium} * * @type {number} */ ghodium: 0, /** * The total amount of ghodium this structure can contain. * * @see {@link http://support.screeps.com/hc/en-us/articles/208488255-StructureNuker#ghodiumCapacity} * * @type {number} */ ghodiumCapacity: 0, /** * The amount of game ticks until the next launch is possible. * * @see {@link http://support.screeps.com/hc/en-us/articles/208488255-StructureNuker#cooldown} * * @type {number} */ cooldown: 0, /** * Launch a nuke to the specified position. * * @see {@link http://support.screeps.com/hc/en-us/articles/208488255-StructureNuker#launchNuke} * * @type {function} * * @param {RoomPosition} pos The target room position. * * @return {number|OK|ERR_NOT_OWNER|ERR_NOT_ENOUGH_RESOURCES|ERR_INVALID_TARGET|ERR_NOT_IN_RANGE|ERR_TIRED|ERR_RCL_NOT_ENOUGH} */ launchNuke: function(pos) { } };
unlicense
stoksey69/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201506/cm/SharedCriterionServiceInterface.java
4462
package com.google.api.ads.adwords.jaxws.v201506.cm; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * * Manages which criteria are associated with shared sets. * * * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.1 * */ @WebService(name = "SharedCriterionServiceInterface", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506") @XmlSeeAlso({ ObjectFactory.class }) public interface SharedCriterionServiceInterface { /** * * Returns a list of SharedCriterion that meets the selector criteria. * * @param selector filters the criteria returned * @return The list of SharedCriterion * @throws ApiException * * * @param selector * @return * returns com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionPage * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506") @RequestWrapper(localName = "get", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506", className = "com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionServiceInterfaceget") @ResponseWrapper(localName = "getResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506", className = "com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionServiceInterfacegetResponse") public SharedCriterionPage get( @WebParam(name = "selector", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506") Selector selector) throws ApiException_Exception ; /** * * Adds, removes criteria in a shared set. * * @param operations A list of unique operations * @return The list of updated SharedCriterion, returned in the same order as the * {@code operations} array. * @throws ApiException * * * @param operations * @return * returns com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionReturnValue * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506") @RequestWrapper(localName = "mutate", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506", className = "com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionServiceInterfacemutate") @ResponseWrapper(localName = "mutateResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506", className = "com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionServiceInterfacemutateResponse") public SharedCriterionReturnValue mutate( @WebParam(name = "operations", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506") List<SharedCriterionOperation> operations) throws ApiException_Exception ; /** * * Returns the list of SharedCriterion that match the query. * * @param query The SQL-like AWQL query string. * @return A list of SharedCriterion. * @throws ApiException * * * @param query * @return * returns com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionPage * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506") @RequestWrapper(localName = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506", className = "com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionServiceInterfacequery") @ResponseWrapper(localName = "queryResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506", className = "com.google.api.ads.adwords.jaxws.v201506.cm.SharedCriterionServiceInterfacequeryResponse") public SharedCriterionPage query( @WebParam(name = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201506") String query) throws ApiException_Exception ; }
apache-2.0
sseago/origin
pkg/cmd/experimental/diagnostics/diagnostics.go
9928
package diagnostics import ( "fmt" "io" "os" "runtime/debug" "github.com/spf13/cobra" flag "github.com/spf13/pflag" kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/util" kutilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/sets" "github.com/openshift/origin/pkg/cmd/cli/config" "github.com/openshift/origin/pkg/cmd/experimental/diagnostics/options" "github.com/openshift/origin/pkg/cmd/flagtypes" osclientcmd "github.com/openshift/origin/pkg/cmd/util/clientcmd" "github.com/openshift/origin/pkg/diagnostics/log" "github.com/openshift/origin/pkg/diagnostics/types" ) // DiagnosticsOptions holds values received from command line flags as well as // other objects generated for the command to operate. type DiagnosticsOptions struct { // list of diagnostic names to limit what is run RequestedDiagnostics util.StringList // specify locations of host config files MasterConfigLocation string NodeConfigLocation string // specify context name to be used for cluster-admin access ClientClusterContext string // indicate this is an openshift host despite lack of other indicators IsHost bool // We need a factory for creating clients. Creating a factory // creates flags as a byproduct, most of which we don't want. // The command creates these and binds only the flags we want. ClientFlags *flag.FlagSet Factory *osclientcmd.Factory // LogOptions determine globally what the user wants to see and how. LogOptions *log.LoggerOptions // The Logger is built with the options and should be used for all diagnostic output. Logger *log.Logger } const longDescription = ` This utility helps troubleshoot and diagnose known problems. It runs diagnostics using a client and/or the state of a running master / node host. $ %[1]s If run without flags, it will check for standard config files for client, master, and node, and if found, use them for diagnostics. You may also specify config files explicitly with flags, in which case you will receive an error if they are not found. For example: $ %[1]s --master-config=/etc/openshift/master/master-config.yaml * If master/node config files are not found and the --host flag is not present, host diagnostics are skipped. * If the client has cluster-admin access, this access enables cluster diagnostics to run which regular users cannot. * If a client config file is not found, client and cluster diagnostics are skipped. NOTE: This is a beta version of diagnostics and may still evolve in a different direction. ` // NewCommandDiagnostics is the base command for running any diagnostics. func NewCommandDiagnostics(name string, fullName string, out io.Writer) *cobra.Command { o := &DiagnosticsOptions{ RequestedDiagnostics: util.StringList{}, LogOptions: &log.LoggerOptions{Out: out}, } cmd := &cobra.Command{ Use: name, Short: "This utility helps you troubleshoot and diagnose.", Long: fmt.Sprintf(longDescription, fullName), Run: func(c *cobra.Command, args []string) { kcmdutil.CheckErr(o.Complete()) failed, err, warnCount, errorCount := o.RunDiagnostics() o.Logger.Summary(warnCount, errorCount) kcmdutil.CheckErr(err) if failed { os.Exit(255) } }, } cmd.SetOutput(out) // for output re: usage / help o.ClientFlags = flag.NewFlagSet("client", flag.ContinueOnError) // hide the extensive set of client flags o.Factory = osclientcmd.New(o.ClientFlags) // that would otherwise be added to this command cmd.Flags().AddFlag(o.ClientFlags.Lookup(config.OpenShiftConfigFlagName)) cmd.Flags().AddFlag(o.ClientFlags.Lookup("context")) // TODO: find k8s constant cmd.Flags().StringVar(&o.ClientClusterContext, options.FlagClusterContextName, "", "client context to use for cluster administrator") cmd.Flags().StringVar(&o.MasterConfigLocation, options.FlagMasterConfigName, "", "path to master config file (implies --host)") cmd.Flags().StringVar(&o.NodeConfigLocation, options.FlagNodeConfigName, "", "path to node config file (implies --host)") cmd.Flags().BoolVar(&o.IsHost, options.FlagIsHostName, false, "look for systemd and journald units even without master/node config") flagtypes.GLog(cmd.Flags()) options.BindLoggerOptionFlags(cmd.Flags(), o.LogOptions, options.RecommendedLoggerOptionFlags()) options.BindDiagnosticFlag(cmd.Flags(), &o.RequestedDiagnostics, options.NewRecommendedDiagnosticFlag()) return cmd } // Complete fills in DiagnosticsOptions needed if the command is actually invoked. func (o *DiagnosticsOptions) Complete() error { var err error o.Logger, err = o.LogOptions.NewLogger() if err != nil { return err } return nil } // RunDiagnostics builds diagnostics based on the options and executes them, returning a summary. func (o DiagnosticsOptions) RunDiagnostics() (bool, error, int, int) { failed := false warnings := []error{} errors := []error{} diagnostics := []types.Diagnostic{} AvailableDiagnostics := sets.NewString() AvailableDiagnostics.Insert(availableClientDiagnostics.List()...) AvailableDiagnostics.Insert(availableClusterDiagnostics.List()...) AvailableDiagnostics.Insert(availableHostDiagnostics.List()...) if len(o.RequestedDiagnostics) == 0 { o.RequestedDiagnostics = AvailableDiagnostics.List() } else if common := intersection(sets.NewString(o.RequestedDiagnostics...), AvailableDiagnostics); len(common) == 0 { o.Logger.Error("CED3012", log.EvalTemplate("CED3012", "None of the requested diagnostics are available:\n {{.requested}}\nPlease try from the following:\n {{.available}}", log.Hash{"requested": o.RequestedDiagnostics, "available": AvailableDiagnostics.List()})) return false, fmt.Errorf("No requested diagnostics available"), 0, 1 } else if len(common) < len(o.RequestedDiagnostics) { errors = append(errors, fmt.Errorf("Not all requested diagnostics are available")) o.Logger.Error("CED3013", log.EvalTemplate("CED3013", ` Of the requested diagnostics: {{.requested}} only these are available: {{.common}} The list of all possible is: {{.available}} `, log.Hash{"requested": o.RequestedDiagnostics, "common": common.List(), "available": AvailableDiagnostics.List()})) } func() { // don't trust discovery/build of diagnostics; wrap panic nicely in case of developer error defer func() { if r := recover(); r != nil { failed = true stack := debug.Stack() errors = append(errors, fmt.Errorf("While building the diagnostics, a panic was encountered.\nThis is a bug in diagnostics. Error and stack trace follow: \n%v\n%s", r, stack)) } }() detected, detectWarnings, detectErrors := o.detectClientConfig() // may log and return problems for _, warn := range detectWarnings { warnings = append(warnings, warn) } for _, err := range detectErrors { errors = append(errors, err) } if !detected { // there just plain isn't any client config file available o.Logger.Notice("CED3014", "No client configuration specified; skipping client and cluster diagnostics.") } else if rawConfig, err := o.buildRawConfig(); err != nil { // client config is totally broken - won't parse etc (problems may have been detected and logged) o.Logger.Error("CED3015", fmt.Sprintf("Client configuration failed to load; skipping client and cluster diagnostics due to error: %s", err.Error())) errors = append(errors, err) } else { clientDiags, ok, err := o.buildClientDiagnostics(rawConfig) failed = failed || !ok if ok { diagnostics = append(diagnostics, clientDiags...) } if err != nil { errors = append(errors, err) } clusterDiags, ok, err := o.buildClusterDiagnostics(rawConfig) failed = failed || !ok if ok { diagnostics = append(diagnostics, clusterDiags...) } if err != nil { errors = append(errors, err) } } hostDiags, ok, err := o.buildHostDiagnostics() failed = failed || !ok if ok { diagnostics = append(diagnostics, hostDiags...) } if err != nil { errors = append(errors, err) } }() if failed { return failed, kutilerrors.NewAggregate(errors), len(warnings), len(errors) } failed, err, numWarnings, numErrors := o.Run(diagnostics) numWarnings += len(warnings) numErrors += len(errors) return failed, err, numWarnings, numErrors } // Run performs the actual execution of diagnostics once they're built. func (o DiagnosticsOptions) Run(diagnostics []types.Diagnostic) (bool, error, int, int) { warnCount := 0 errorCount := 0 for _, diagnostic := range diagnostics { func() { // wrap diagnostic panic nicely in case of developer error defer func() { if r := recover(); r != nil { errorCount += 1 stack := debug.Stack() o.Logger.Error("CED3017", fmt.Sprintf("While running the %s diagnostic, a panic was encountered.\nThis is a bug in diagnostics. Error and stack trace follow: \n%s\n%s", diagnostic.Name(), fmt.Sprintf("%v", r), stack)) } }() if canRun, reason := diagnostic.CanRun(); !canRun { if reason == nil { o.Logger.Notice("CED3018", fmt.Sprintf("Skipping diagnostic: %s\nDescription: %s", diagnostic.Name(), diagnostic.Description())) } else { o.Logger.Notice("CED3019", fmt.Sprintf("Skipping diagnostic: %s\nDescription: %s\nBecause: %s", diagnostic.Name(), diagnostic.Description(), reason.Error())) } return } o.Logger.Notice("CED3020", fmt.Sprintf("Running diagnostic: %s\nDescription: %s", diagnostic.Name(), diagnostic.Description())) r := diagnostic.Check() for _, entry := range r.Logs() { o.Logger.LogEntry(entry) } warnCount += len(r.Warnings()) errorCount += len(r.Errors()) }() } return errorCount > 0, nil, warnCount, errorCount } // TODO move upstream func intersection(s1 sets.String, s2 sets.String) sets.String { result := sets.NewString() for key := range s1 { if s2.Has(key) { result.Insert(key) } } return result }
apache-2.0