code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the PKIX-C library.
*
* The Initial Developer of the Original Code is
* Sun Microsystems, Inc.
* Portions created by the Initial Developer are
* Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
*
* Contributor(s):
* Sun Microsystems, Inc.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* test_basicconstraintschecker.c
*
* Test Basic Constraints Checking
*
*/
#include "testutil.h"
#include "testutil_nss.h"
#define PKIX_TEST_MAX_CERTS 10
static void *plContext = NULL;
static
void printUsage1(char *pName){
printf("\nUSAGE: %s test-name [ENE|EE] ", pName);
printf("cert [certs].\n");
}
static
void printUsageMax(PKIX_UInt32 numCerts){
printf("\nUSAGE ERROR: number of certs %d exceed maximum %d\n",
numCerts, PKIX_TEST_MAX_CERTS);
}
int test_basicconstraintschecker(int argc, char *argv[]){
PKIX_List *chain = NULL;
PKIX_ValidateParams *valParams = NULL;
PKIX_ValidateResult *valResult = NULL;
PKIX_UInt32 actualMinorVersion;
char *certNames[PKIX_TEST_MAX_CERTS];
PKIX_PL_Cert *certs[PKIX_TEST_MAX_CERTS];
PKIX_VerifyNode *verifyTree = NULL;
PKIX_PL_String *verifyString = NULL;
PKIX_UInt32 chainLength = 0;
PKIX_UInt32 i = 0;
PKIX_UInt32 j = 0;
PKIX_Boolean testValid = PKIX_FALSE;
char *dirName = NULL;
PKIX_TEST_STD_VARS();
if (argc < 4){
printUsage1(argv[0]);
return (0);
}
startTests("BasicConstraintsChecker");
PKIX_TEST_EXPECT_NO_ERROR(
PKIX_PL_NssContext_Create(0, PKIX_FALSE, NULL, &plContext));
/* ENE = expect no error; EE = expect error */
if (PORT_Strcmp(argv[2+j], "ENE") == 0) {
testValid = PKIX_TRUE;
} else if (PORT_Strcmp(argv[2+j], "EE") == 0) {
testValid = PKIX_FALSE;
} else {
printUsage1(argv[0]);
return (0);
}
dirName = argv[3+j];
chainLength = (argc - j) - 4;
if (chainLength > PKIX_TEST_MAX_CERTS) {
printUsageMax(chainLength);
}
for (i = 0; i < chainLength; i++) {
certNames[i] = argv[(4+j)+i];
certs[i] = NULL;
}
subTest(argv[1+j]);
subTest("Basic-Constraints - Create Cert Chain");
chain = createCertChainPlus
(dirName, certNames, certs, chainLength, plContext);
/*
* Error occurs when creating Cert, this is critical and test
* should not continue. Since we expect error, we assume this
* error is the one that is expected, so undo the error count.
*
* This work needs future enhancement. We will introduce another
* flag ESE, in addition to the existing EE(expect validation
* error) and ENE(expect no validation error). ESE stands for
* "expect setup error". When running with ESE, if any of the setup
* calls such creating Cert Chain fails, the test can end and
* considered to be successful.
*/
if (testValid == PKIX_FALSE && chain == NULL) {
testErrorUndo("Cert Error - Create failed");
goto cleanup;
}
subTest("Basic-Constraints - Create Params");
valParams = createValidateParams
(dirName,
argv[4+j],
NULL,
NULL,
NULL,
PKIX_FALSE,
PKIX_FALSE,
PKIX_FALSE,
PKIX_FALSE,
chain,
plContext);
subTest("Basic-Constraints - Validate Chain");
if (testValid == PKIX_TRUE) {
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ValidateChain
(valParams, &valResult, &verifyTree, plContext));
} else {
PKIX_TEST_EXPECT_ERROR(PKIX_ValidateChain
(valParams, &valResult, &verifyTree, plContext));
}
cleanup:
PKIX_TEST_DECREF_AC(verifyString);
PKIX_TEST_DECREF_AC(verifyTree);
PKIX_TEST_DECREF_AC(chain);
PKIX_TEST_DECREF_AC(valParams);
PKIX_TEST_DECREF_AC(valResult);
PKIX_Shutdown(plContext);
PKIX_TEST_RETURN();
endTests("BasicConstraintsChecker");
return (0);
}
|
tmhorne/celtx
|
security/nss/cmd/libpkix/pkix/top/test_basicconstraintschecker.c
|
C
|
mpl-2.0
| 5,822
|
# encoding: utf-8
#
#
# 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/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division, unicode_literals
import argparse as _argparse
import os
import sys
import tempfile
from mo_dots import coalesce, listwrap, unwrap, to_data
from mo_logs import Log
# PARAMETERS MATCH argparse.ArgumentParser.add_argument()
# https://docs.python.org/dev/library/argparse.html#the-add-argument-method
#
# name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
# action - The basic type of action to be taken when this argument is encountered at the command line.
# nargs - The number of command-line arguments that should be consumed.
# const - A constant value required by some action and nargs selections.
# default - The value produced if the argument is absent from the command line.
# type - The type to which the command-line argument should be converted.
# choices - A container of the allowable values for the argument.
# required - Whether or not the command-line option may be omitted (optionals only).
# help - A brief description of what the argument does.
# metavar - A name for the argument in usage messages.
# dest - The name of the attribute to be added to the object returned by parse_args().
class _ArgParser(_argparse.ArgumentParser):
def error(self, message):
Log.error("argparse error: {{error}}", error=message)
def argparse(defs, complain=True):
parser = _ArgParser()
for d in listwrap(defs):
args = d.copy()
name = args.name
args.name = None
parser.add_argument(*unwrap(listwrap(name)), **args)
namespace, unknown = parser.parse_known_args()
if unknown and complain:
Log.warning("Ignoring arguments: {{unknown|json}}", unknown=unknown)
output = {k: getattr(namespace, k) for k in vars(namespace)}
return to_data(output)
def read_settings(defs=None, filename=None, default_filename=None, complain=True):
"""
:param filename: Force load a file
:param defs: more arguments you want to accept (see https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument)
:param default_filename: A config file from an environment variable (a fallback config file, if no other provided)
:parma complain: Complain about args mismatch
"""
from mo_files import File
import mo_json_config
# READ SETTINGS
defs = listwrap(defs)
defs.append({
"name": ["--config", "--settings", "--settings-file", "--settings_file"],
"help": "path to JSON file with settings",
"type": str,
"dest": "filename",
"default": None,
"required": False,
})
args = argparse(defs, complain)
args.filename = coalesce(
filename,
args.filename if args.filename.endswith(".json") else None,
default_filename,
"./config.json",
)
settings_file = File(args.filename)
if settings_file.exists:
Log.note("Using {{filename}} for configuration", filename=settings_file.abspath)
else:
Log.error(
"Can not read configuration file {{filename}}",
filename=settings_file.abspath,
)
settings = mo_json_config.get_file(settings_file)
settings.args = args
return settings
# snagged from https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py (under licence PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2)
class SingleInstance:
"""
ONLY ONE INSTANCE OF PROGRAM ALLOWED
If you want to prevent your script from running in parallel just instantiate SingleInstance() class.
If is there another instance already running it will exist the application with the message
"Another instance is already running, quitting.", returning -1 error code.
with SingleInstance():
<your code here>
settings = startup.read_settings()
with SingleInstance(settings.args.filename):
<your code here>
This option is very useful if you have scripts executed by crontab at small intervals, causing multiple instances
Remember that this works by creating a lock file with a filename based on the full path to the script file.
"""
def __init__(self, flavor_id=""):
self.initialized = False
appname = os.path.splitext(os.path.abspath(sys.argv[0]))[0]
basename = ((appname + "-%s") % flavor_id).replace("/", "-").replace(
":", ""
).replace("\\", "-").replace("-.-", "-") + ".lock"
self.lockfile = os.path.normpath(tempfile.gettempdir() + "/" + basename)
def __enter__(self):
Log.note("SingleInstance.lockfile = " + self.lockfile)
if sys.platform == "win32":
try:
# file already exists, we try to remove (in case previous execution was interrupted)
if os.path.exists(self.lockfile):
os.unlink(self.lockfile)
self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
except Exception as e:
Log.alarm("Another instance is already running, quitting.")
sys.exit(-1)
else: # non Windows
import fcntl
self.fp = open(self.lockfile, "w")
try:
fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
Log.alarm("Another instance is already running, quitting.")
sys.exit(-1)
self.initialized = True
def __exit__(self, type, value, traceback):
self.__del__()
def __del__(self):
temp, self.initialized = self.initialized, False
if not temp:
return
try:
if sys.platform == "win32":
if hasattr(self, "fd"):
os.close(self.fd)
os.unlink(self.lockfile)
else:
import fcntl
fcntl.lockf(self.fp, fcntl.LOCK_UN)
if os.path.isfile(self.lockfile):
os.unlink(self.lockfile)
except Exception as e:
Log.warning("Problem with SingleInstance __del__()", e)
sys.exit(-1)
|
klahnakoski/ActiveData
|
vendor/mo_logs/startup.py
|
Python
|
mpl-2.0
| 6,384
|
<!DOCTYPE html>
<html class="reftest-wait">
<script>
var context = new window.AudioContext();
var source = context.createBufferSource();
source.connect(context.destination);
source.playbackRate.value = 0.01;
source.buffer = context.createBuffer(2, 32, context.sampleRate);
source.start(0);
setTimeout(
function() {
source.buffer = context.createBuffer(1, 10, context.sampleRate);
source.playbackRate.value = 1;
source.onended =
function() {
document.documentElement.removeAttribute("class");
};
}, 0);
</script>
</html>
|
Yukarumya/Yukarum-Redfoxes
|
dom/media/test/crashtests/1020205.html
|
HTML
|
mpl-2.0
| 594
|
{% extends "wiki/base.html" %}
{% from "includes/error_list.html" import errorlist %}
{% from 'wiki/includes/page_buttons.html' import page_buttons with context %}
{% from "includes/common_macros.html" import content_editor %}
{% if is_template %}
{% set title = _('Create a New Template') %}
{% else %}
{% set title = _('Create a New Article') %}
{% endif %}
{% block title %}{{ page_title(title) }}{% endblock %}
{% set classes = 'new' %}
{% block bodyclass %}new{% if is_template %} is-template{% endif %}{% endblock %}
{% block site_css %}
{{ super() }}
{% stylesheet 'wiki-edit' %}
{% stylesheet 'jquery-ui' %}
{% endblock %}
{% block content %}
<article id="new-document">
{{ errorlist(document_form) }}
{{ errorlist(revision_form) }}
<form id="wiki-page-edit" class="editing" method="post" action="">
{{ csrf() }}
<fieldset>
<header id="article-head">
{{ page_buttons(wiki, document, discard_href, 'top') }}
{{ document_form.category|safe }}
<div class="doc-title">
<h1><span class="title-prefix">{{ _('Create a') }} </span><em>{{ _('New Document') }}</em></h1>
<p class="save-state" id="draft-status">
{{ _('Draft') }} <span id="draft-action"></span> <time id="draft-time" class="timeago" title=""></time>
</p>
</div>
<ul class="metadata">
<li class="clear">
<label for="id_title">{{ _('Title:') }}</label>
{{ document_form.title | safe }}
</li>
<li class="clear">
<label for="id_slug"><dfn title="{{ _('URL segment that identifies the page') }}">{{ _('Slug:') }}</dfn></label>
{{ document_form.slug | safe }}
</li>
{% if parent_slug and not is_template %}
<li class="clear"><label>{{ _('Parent:') }}</label>
<a href="{{ parent_path }}" class="metadataDisplay" target="_blank">{{ parent_slug }}</a></li>
{% endif %}
{% if is_template %}
<input type="hidden" name="toc_depth" value="0" />
{% else %}
{% include 'wiki/includes/document_toc_field.html' %}
{% endif %}
</ul>
<input type="hidden" name="parent_topic" value="{{ parent_id|safe }}" />
</header>
{% include 'wiki/includes/guide_links.html' %}
{% if is_template %}
{{ revision_form.content|safe }}
<div id="ace_content" class="editor-container"></div>
{% else %}
<div class="ckeditor-container editor-container">
{{ revision_form.content|safe }}
</div>
{% endif %}
{% include 'wiki/includes/revision_comment.html' %}
{% include 'wiki/includes/review_tags.html' %}
<section id="page-tags" class="page-tags wiki-block">
<h3><i aria-hidden="true" class="icon-tags"></i>{{ _('Tags') }}</h3>
<input id="tagit_tags" type="text" name="tags" value="{% for tag in initial_tags %}{{ tag.name }},{% endfor %}" maxlength="255" />
</section>
</fieldset>
<section class="wiki-block">
{{ page_buttons(wiki, document, discard_href, 'bottom') }}
</section>
</form>
{% include 'attachments/includes/attachment_list.html' %}
</article>
{% endblock %}
{% block site_js %}
{{ super() }}
{% javascript 'jquery-ui' %}
{% include 'wiki/includes/tag_suggestions.html' %}
{% if is_template %}
{% include 'wiki/includes/ace_scripts.html' %}
{% else %}
{% include 'wiki/includes/ckeditor_scripts.html' %}
{% endif %}
{% javascript 'wiki-edit' %}
{% endblock %}
|
anaran/kuma
|
kuma/wiki/templates/wiki/create.html
|
HTML
|
mpl-2.0
| 3,681
|
/* 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/. */
//! Borders, padding, and margins.
#![deny(unsafe_code)]
use fragment::Fragment;
use geom::{Matrix4, SideOffsets2D, Size2D};
use std::cmp::{max, min};
use std::fmt;
use style::computed_values::transform::ComputedMatrix;
use style::properties::ComputedValues;
use style::values::computed::{LengthAndPercentage, LengthOrPercentageOrAuto};
use style::values::computed::{LengthOrPercentageOrNone, LengthOrPercentage};
use util::geometry::Au;
use util::logical_geometry::LogicalMargin;
/// A collapsible margin. See CSS 2.1 § 8.3.1.
#[derive(Copy, Clone)]
pub struct AdjoiningMargins {
/// The value of the greatest positive margin.
pub most_positive: Au,
/// The actual value (not the absolute value) of the negative margin with the largest absolute
/// value. Since this is not the absolute value, this is always zero or negative.
pub most_negative: Au,
}
impl AdjoiningMargins {
pub fn new() -> AdjoiningMargins {
AdjoiningMargins {
most_positive: Au(0),
most_negative: Au(0),
}
}
pub fn from_margin(margin_value: Au) -> AdjoiningMargins {
if margin_value >= Au(0) {
AdjoiningMargins {
most_positive: margin_value,
most_negative: Au(0),
}
} else {
AdjoiningMargins {
most_positive: Au(0),
most_negative: margin_value,
}
}
}
pub fn union(&mut self, other: AdjoiningMargins) {
self.most_positive = max(self.most_positive, other.most_positive);
self.most_negative = min(self.most_negative, other.most_negative)
}
pub fn collapse(&self) -> Au {
self.most_positive + self.most_negative
}
}
/// Represents the block-start and block-end margins of a flow with collapsible margins. See CSS 2.1 § 8.3.1.
#[derive(Copy, Clone)]
pub enum CollapsibleMargins {
/// Margins may not collapse with this flow.
None(Au, Au),
/// Both the block-start and block-end margins (specified here in that order) may collapse, but the
/// margins do not collapse through this flow.
Collapse(AdjoiningMargins, AdjoiningMargins),
/// Margins collapse *through* this flow. This means, essentially, that the flow doesn’t
/// have any border, padding, or out-of-flow (floating or positioned) content
CollapseThrough(AdjoiningMargins),
}
impl CollapsibleMargins {
pub fn new() -> CollapsibleMargins {
CollapsibleMargins::None(Au(0), Au(0))
}
/// Returns the amount of margin that should be applied in a noncollapsible context. This is
/// currently used to apply block-start margin for hypothetical boxes, since we do not collapse
/// margins of hypothetical boxes.
pub fn block_start_margin_for_noncollapsible_context(&self) -> Au {
match *self {
CollapsibleMargins::None(block_start, _) => block_start,
CollapsibleMargins::Collapse(ref block_start, _) |
CollapsibleMargins::CollapseThrough(ref block_start) => block_start.collapse(),
}
}
}
enum FinalMarginState {
MarginsCollapseThrough,
BottomMarginCollapses,
}
pub struct MarginCollapseInfo {
pub state: MarginCollapseState,
pub block_start_margin: AdjoiningMargins,
pub margin_in: AdjoiningMargins,
}
impl MarginCollapseInfo {
/// TODO(#2012, pcwalton): Remove this method once `fragment` is not an `Option`.
pub fn new() -> MarginCollapseInfo {
MarginCollapseInfo {
state: MarginCollapseState::AccumulatingCollapsibleTopMargin,
block_start_margin: AdjoiningMargins::new(),
margin_in: AdjoiningMargins::new(),
}
}
pub fn initialize_block_start_margin(&mut self,
fragment: &Fragment,
can_collapse_block_start_margin_with_kids: bool) {
if !can_collapse_block_start_margin_with_kids {
self.state = MarginCollapseState::AccumulatingMarginIn
}
self.block_start_margin = AdjoiningMargins::from_margin(fragment.margin.block_start)
}
pub fn finish_and_compute_collapsible_margins(mut self,
fragment: &Fragment,
can_collapse_block_end_margin_with_kids: bool)
-> (CollapsibleMargins, Au) {
let state = match self.state {
MarginCollapseState::AccumulatingCollapsibleTopMargin => {
match fragment.style().content_block_size() {
LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Length(Au(0)) |
LengthOrPercentageOrAuto::Percentage(0.) => {
match fragment.style().min_block_size() {
LengthOrPercentage::Length(Au(0)) | LengthOrPercentage::Percentage(0.) => {
FinalMarginState::MarginsCollapseThrough
},
_ => {
// If the fragment has non-zero min-block-size, margins may not
// collapse through it.
FinalMarginState::BottomMarginCollapses
}
}
},
_ => {
// If the fragment has an explicitly specified block-size, margins may not
// collapse through it.
FinalMarginState::BottomMarginCollapses
}
}
}
MarginCollapseState::AccumulatingMarginIn => FinalMarginState::BottomMarginCollapses,
};
// Different logic is needed here depending on whether this flow can collapse its block-end
// margin with its children.
let block_end_margin = fragment.margin.block_end;
if !can_collapse_block_end_margin_with_kids {
match state {
FinalMarginState::MarginsCollapseThrough => {
let advance = self.block_start_margin.collapse();
self.margin_in.union(AdjoiningMargins::from_margin(block_end_margin));
(CollapsibleMargins::Collapse(self.block_start_margin, self.margin_in), advance)
}
FinalMarginState::BottomMarginCollapses => {
let advance = self.margin_in.collapse();
self.margin_in.union(AdjoiningMargins::from_margin(block_end_margin));
(CollapsibleMargins::Collapse(self.block_start_margin, self.margin_in), advance)
}
}
} else {
match state {
FinalMarginState::MarginsCollapseThrough => {
self.block_start_margin.union(AdjoiningMargins::from_margin(block_end_margin));
(CollapsibleMargins::CollapseThrough(self.block_start_margin), Au(0))
}
FinalMarginState::BottomMarginCollapses => {
self.margin_in.union(AdjoiningMargins::from_margin(block_end_margin));
(CollapsibleMargins::Collapse(self.block_start_margin, self.margin_in), Au(0))
}
}
}
}
pub fn current_float_ceiling(&mut self) -> Au {
match self.state {
MarginCollapseState::AccumulatingCollapsibleTopMargin => {
// We do not include the top margin in the float ceiling, because the float flow
// needs to be positioned relative to our *border box*, not our margin box. See
// `tests/ref/float_under_top_margin_a.html`.
Au(0)
}
MarginCollapseState::AccumulatingMarginIn => self.margin_in.collapse(),
}
}
/// Adds the child's potentially collapsible block-start margin to the current margin state and
/// advances the Y offset by the appropriate amount to handle that margin. Returns the amount
/// that should be added to the Y offset during block layout.
pub fn advance_block_start_margin(&mut self, child_collapsible_margins: &CollapsibleMargins)
-> Au {
match (self.state, *child_collapsible_margins) {
(MarginCollapseState::AccumulatingCollapsibleTopMargin,
CollapsibleMargins::None(block_start, _)) => {
self.state = MarginCollapseState::AccumulatingMarginIn;
block_start
}
(MarginCollapseState::AccumulatingCollapsibleTopMargin,
CollapsibleMargins::Collapse(block_start, _)) => {
self.block_start_margin.union(block_start);
self.state = MarginCollapseState::AccumulatingMarginIn;
Au(0)
}
(MarginCollapseState::AccumulatingMarginIn,
CollapsibleMargins::None(block_start, _)) => {
let previous_margin_value = self.margin_in.collapse();
self.margin_in = AdjoiningMargins::new();
previous_margin_value + block_start
}
(MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::Collapse(block_start, _)) => {
self.margin_in.union(block_start);
let margin_value = self.margin_in.collapse();
self.margin_in = AdjoiningMargins::new();
margin_value
}
(_, CollapsibleMargins::CollapseThrough(_)) => {
// For now, we ignore this; this will be handled by `advance_block-end_margin` below.
Au(0)
}
}
}
/// Adds the child's potentially collapsible block-end margin to the current margin state and
/// advances the Y offset by the appropriate amount to handle that margin. Returns the amount
/// that should be added to the Y offset during block layout.
pub fn advance_block_end_margin(&mut self, child_collapsible_margins: &CollapsibleMargins) -> Au {
match (self.state, *child_collapsible_margins) {
(MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::None(..)) |
(MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::Collapse(..)) => {
// Can't happen because the state will have been replaced with
// `MarginCollapseState::AccumulatingMarginIn` above.
panic!("should not be accumulating collapsible block_start margins anymore!")
}
(MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::CollapseThrough(margin)) => {
self.block_start_margin.union(margin);
Au(0)
}
(MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::None(_, block_end)) => {
assert_eq!(self.margin_in.most_positive, Au(0));
assert_eq!(self.margin_in.most_negative, Au(0));
block_end
}
(MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::Collapse(_, block_end)) |
(MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::CollapseThrough(block_end)) => {
self.margin_in.union(block_end);
Au(0)
}
}
}
}
#[derive(Copy, Clone)]
pub enum MarginCollapseState {
AccumulatingCollapsibleTopMargin,
AccumulatingMarginIn,
}
/// Intrinsic inline-sizes, which consist of minimum and preferred.
#[derive(RustcEncodable)]
pub struct IntrinsicISizes {
/// The *minimum inline-size* of the content.
pub minimum_inline_size: Au,
/// The *preferred inline-size* of the content.
pub preferred_inline_size: Au,
}
impl fmt::Debug for IntrinsicISizes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "min={:?}, pref={:?}", self.minimum_inline_size, self.preferred_inline_size)
}
}
impl IntrinsicISizes {
pub fn new() -> IntrinsicISizes {
IntrinsicISizes {
minimum_inline_size: Au(0),
preferred_inline_size: Au(0),
}
}
}
/// The temporary result of the computation of intrinsic inline-sizes.
pub struct IntrinsicISizesContribution {
/// Intrinsic sizes for the content only (not counting borders, padding, or margins).
pub content_intrinsic_sizes: IntrinsicISizes,
/// The inline size of borders and padding, as well as margins if appropriate.
pub surrounding_size: Au,
}
impl IntrinsicISizesContribution {
/// Creates and initializes an inline size computation with all sizes set to zero.
pub fn new() -> IntrinsicISizesContribution {
IntrinsicISizesContribution {
content_intrinsic_sizes: IntrinsicISizes::new(),
surrounding_size: Au(0),
}
}
/// Adds the content intrinsic sizes and the surrounding size together to yield the final
/// intrinsic size computation.
pub fn finish(self) -> IntrinsicISizes {
IntrinsicISizes {
minimum_inline_size: self.content_intrinsic_sizes.minimum_inline_size +
self.surrounding_size,
preferred_inline_size: self.content_intrinsic_sizes.preferred_inline_size +
self.surrounding_size,
}
}
/// Updates the computation so that the minimum is the maximum of the current minimum and the
/// given minimum and the preferred is the sum of the current preferred and the given
/// preferred. This is used when laying out fragments in the inline direction.
///
/// FIXME(pcwalton): This is incorrect when the inline fragment contains forced line breaks
/// (e.g. `<br>` or `white-space: pre`).
pub fn union_inline(&mut self, sizes: &IntrinsicISizes) {
self.content_intrinsic_sizes.minimum_inline_size =
max(self.content_intrinsic_sizes.minimum_inline_size, sizes.minimum_inline_size);
self.content_intrinsic_sizes.preferred_inline_size =
self.content_intrinsic_sizes.preferred_inline_size + sizes.preferred_inline_size
}
/// Updates the computation so that the minimum is the sum of the current minimum and the
/// given minimum and the preferred is the sum of the current preferred and the given
/// preferred. This is used when laying out fragments in the inline direction when
/// `white-space` is `pre` or `nowrap`.
pub fn union_nonbreaking_inline(&mut self, sizes: &IntrinsicISizes) {
self.content_intrinsic_sizes.minimum_inline_size =
self.content_intrinsic_sizes.minimum_inline_size + sizes.minimum_inline_size;
self.content_intrinsic_sizes.preferred_inline_size =
self.content_intrinsic_sizes.preferred_inline_size + sizes.preferred_inline_size
}
/// Updates the computation so that the minimum is the maximum of the current minimum and the
/// given minimum and the preferred is the maximum of the current preferred and the given
/// preferred. This can be useful when laying out fragments in the block direction (but note
/// that it does not take floats into account, so `BlockFlow` does not use it).
///
/// This is used when contributing the intrinsic sizes for individual fragments.
pub fn union_block(&mut self, sizes: &IntrinsicISizes) {
self.content_intrinsic_sizes.minimum_inline_size =
max(self.content_intrinsic_sizes.minimum_inline_size, sizes.minimum_inline_size);
self.content_intrinsic_sizes.preferred_inline_size =
max(self.content_intrinsic_sizes.preferred_inline_size, sizes.preferred_inline_size)
}
}
/// Useful helper data type when computing values for blocks and positioned elements.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MaybeAuto {
Auto,
Specified(Au),
}
impl MaybeAuto {
#[inline]
pub fn from_style(length: LengthOrPercentageOrAuto, containing_length: Au)
-> MaybeAuto {
match length {
LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto,
LengthOrPercentageOrAuto::Percentage(percent) => {
MaybeAuto::Specified(containing_length.scale_by(percent))
}
LengthOrPercentageOrAuto::Length(length) => MaybeAuto::Specified(length)
}
}
#[inline]
pub fn specified_or_default(&self, default: Au) -> Au {
match *self {
MaybeAuto::Auto => default,
MaybeAuto::Specified(value) => value,
}
}
#[inline]
pub fn specified_or_zero(&self) -> Au {
self.specified_or_default(Au::new(0))
}
#[inline]
pub fn map<F>(&self, mapper: F) -> MaybeAuto where F: FnOnce(Au) -> Au {
match *self {
MaybeAuto::Auto => MaybeAuto::Auto,
MaybeAuto::Specified(value) => MaybeAuto::Specified(mapper(value)),
}
}
}
pub fn specified_or_none(length: LengthOrPercentageOrNone, containing_length: Au) -> Option<Au> {
match length {
LengthOrPercentageOrNone::None => None,
LengthOrPercentageOrNone::Percentage(percent) => Some(containing_length.scale_by(percent)),
LengthOrPercentageOrNone::Length(length) => Some(length),
}
}
pub fn specified(length: LengthOrPercentage, containing_length: Au) -> Au {
match length {
LengthOrPercentage::Length(length) => length,
LengthOrPercentage::Percentage(p) => containing_length.scale_by(p)
}
}
#[inline]
pub fn padding_from_style(style: &ComputedValues, containing_block_inline_size: Au)
-> LogicalMargin<Au> {
let padding_style = style.get_padding();
LogicalMargin::from_physical(style.writing_mode, SideOffsets2D::new(
specified(padding_style.padding_top, containing_block_inline_size),
specified(padding_style.padding_right, containing_block_inline_size),
specified(padding_style.padding_bottom, containing_block_inline_size),
specified(padding_style.padding_left, containing_block_inline_size)))
}
pub trait ToGfxMatrix {
fn to_gfx_matrix(&self, containing_size: &Size2D<Au>) -> Matrix4<f32>;
}
impl ToGfxMatrix for ComputedMatrix {
fn to_gfx_matrix(&self, containing_size: &Size2D<Au>) -> Matrix4<f32> {
Matrix4 {
m11: self.m11 as f32, m12: self.m12 as f32, m13: self.m13 as f32, m14: self.m14 as f32,
m21: self.m21 as f32, m22: self.m22 as f32, m23: self.m23 as f32, m24: self.m24 as f32,
m31: self.m31 as f32, m32: self.m32 as f32, m33: self.m33 as f32, m34: self.m34 as f32,
m41: self.m41.to_au(containing_size.width).to_f32_px(),
m42: self.m42.to_au(containing_size.height).to_f32_px(),
m43: self.m43 as f32,
m44: self.m44 as f32
}
}
}
pub trait ToAu {
fn to_au(&self, containing_size: Au) -> Au;
}
impl ToAu for LengthAndPercentage {
#[inline]
fn to_au(&self, containing_size: Au) -> Au {
self.length + Au::from_f32_px(self.percentage * containing_size.to_f32_px())
}
}
|
zhangjunlei26/servo
|
components/layout/model.rs
|
Rust
|
mpl-2.0
| 19,406
|
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ActSpecObsInterferenceCode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ActSpecObsInterferenceCode">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="INTFR"/>
* <enumeration value="FIBRIN"/>
* <enumeration value="HEMOLYSIS"/>
* <enumeration value="ICTERUS"/>
* <enumeration value="LIPEMIA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ActSpecObsInterferenceCode")
@XmlEnum
public enum ActSpecObsInterferenceCode {
INTFR,
FIBRIN,
HEMOLYSIS,
ICTERUS,
LIPEMIA;
public String value() {
return name();
}
public static ActSpecObsInterferenceCode fromValue(String v) {
return valueOf(v);
}
}
|
jembi/openhim-encounter-orchestrator
|
src/main/java/org/hl7/v3/ActSpecObsInterferenceCode.java
|
Java
|
mpl-2.0
| 966
|
require 'spec_helper'
describe 'RubyLint::Report' do
it 'adds a message using #add' do
report = RubyLint::Report.new
report.add(
:level => :info,
:message => 'info message',
:line => 1,
:column => 2,
:file => 'file.rb'
)
report.entries.length.should == 1
entry = report.entries[0]
entry.level.should == :info
entry.message.should == 'info message'
entry.line.should == 1
entry.column.should == 2
entry.file.should == 'file.rb'
end
it 'ignores invalid reporting levels' do
report = RubyLint::Report.new
report.add(
:level => :test,
:message => 'invalid message',
:line => 1,
:column => 1,
:file => 'file.rb'
)
report.entries.empty?.should == true
end
end
|
cabo/ruby-lint
|
spec/ruby-lint/report_spec.rb
|
Ruby
|
mpl-2.0
| 813
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<TITLE>
Uses of Class org.apache.poi.ss.formula.ptg.OperandPtg (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.ss.formula.ptg.OperandPtg (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/poi/ss/formula/ptg/\class-useOperandPtg.html" target="_top"><B>FRAMES</B></A>
<A HREF="OperandPtg.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.ss.formula.ptg.OperandPtg</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg">OperandPtg</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.ss.formula.ptg"><B>org.apache.poi.ss.formula.ptg</B></A></TD>
<TD>formula package contains binary PTG structures used in Formulas </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.ss.formula.ptg"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg">OperandPtg</A> in <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/package-summary.html">org.apache.poi.ss.formula.ptg</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg">OperandPtg</A> in <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/package-summary.html">org.apache.poi.ss.formula.ptg</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/Area2DPtgBase.html" title="class in org.apache.poi.ss.formula.ptg">Area2DPtgBase</A></B></CODE>
<BR>
Common superclass of 2-D area refs</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/Area3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">Area3DPtg</A></B></CODE>
<BR>
Title: Area 3D Ptg - 3D reference (Sheet + Area)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/Area3DPxg.html" title="class in org.apache.poi.ss.formula.ptg">Area3DPxg</A></B></CODE>
<BR>
Title: XSSF Area 3D Reference (Sheet + Area)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/AreaErrPtg.html" title="class in org.apache.poi.ss.formula.ptg">AreaErrPtg</A></B></CODE>
<BR>
AreaErr - handles deleted cell area references.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/AreaNPtg.html" title="class in org.apache.poi.ss.formula.ptg">AreaNPtg</A></B></CODE>
<BR>
Specifies a rectangular area of cells A1:A4 for instance.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/AreaPtg.html" title="class in org.apache.poi.ss.formula.ptg">AreaPtg</A></B></CODE>
<BR>
Specifies a rectangular area of cells A1:A4 for instance.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/AreaPtgBase.html" title="class in org.apache.poi.ss.formula.ptg">AreaPtgBase</A></B></CODE>
<BR>
Specifies a rectangular area of cells A1:A4 for instance.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/Deleted3DPxg.html" title="class in org.apache.poi.ss.formula.ptg">Deleted3DPxg</A></B></CODE>
<BR>
An XSSF only representation of a reference to a deleted area</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/DeletedArea3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">DeletedArea3DPtg</A></B></CODE>
<BR>
Title: Deleted Area 3D Ptg - 3D referecnce (Sheet + Area)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/DeletedRef3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">DeletedRef3DPtg</A></B></CODE>
<BR>
Title: Deleted Reference 3D Ptg</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/MemAreaPtg.html" title="class in org.apache.poi.ss.formula.ptg">MemAreaPtg</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/MemErrPtg.html" title="class in org.apache.poi.ss.formula.ptg">MemErrPtg</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/MemFuncPtg.html" title="class in org.apache.poi.ss.formula.ptg">MemFuncPtg</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/NamePtg.html" title="class in org.apache.poi.ss.formula.ptg">NamePtg</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/NameXPtg.html" title="class in org.apache.poi.ss.formula.ptg">NameXPtg</A></B></CODE>
<BR>
A Name, be that a Named Range or a Function / User Defined
Function, addressed in the HSSF External Sheet style.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/NameXPxg.html" title="class in org.apache.poi.ss.formula.ptg">NameXPxg</A></B></CODE>
<BR>
A Name, be that a Named Range or a Function / User Defined
Function, addressed in the HSSF External Sheet style.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/Ref3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">Ref3DPtg</A></B></CODE>
<BR>
Title: Reference 3D Ptg</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/Ref3DPxg.html" title="class in org.apache.poi.ss.formula.ptg">Ref3DPxg</A></B></CODE>
<BR>
Title: XSSF 3D Reference</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/RefErrorPtg.html" title="class in org.apache.poi.ss.formula.ptg">RefErrorPtg</A></B></CODE>
<BR>
RefError - handles deleted cell reference</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/RefNPtg.html" title="class in org.apache.poi.ss.formula.ptg">RefNPtg</A></B></CODE>
<BR>
RefNPtg</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/RefPtg.html" title="class in org.apache.poi.ss.formula.ptg">RefPtg</A></B></CODE>
<BR>
ReferencePtg - handles references (such as A1, A2, IA4)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/RefPtgBase.html" title="class in org.apache.poi.ss.formula.ptg">RefPtgBase</A></B></CODE>
<BR>
ReferencePtgBase - handles references (such as A1, A2, IA4)</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/package-summary.html">org.apache.poi.ss.formula.ptg</A> that return <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg">OperandPtg</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg">OperandPtg</A></CODE></FONT></TD>
<TD><CODE><B>OperandPtg.</B><B><A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html#copy()">copy</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/poi/ss/formula/ptg/\class-useOperandPtg.html" target="_top"><B>FRAMES</B></A>
<A HREF="OperandPtg.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2015 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
|
claywebb/java-bulletin
|
poi-3.13/docs/apidocs/org/apache/poi/ss/formula/ptg/class-use/OperandPtg.html
|
HTML
|
mpl-2.0
| 18,267
|
package google
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccDataSourceComputeBackendService_basic(t *testing.T) {
t.Parallel()
serviceName := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
checkName := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckComputeBackendServiceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccDataSourceComputeBackendService_basic(serviceName, checkName),
Check: testAccDataSourceComputeBackendServiceCheck("data.google_compute_backend_service.baz", "google_compute_backend_service.foobar"),
},
},
})
}
func testAccDataSourceComputeBackendServiceCheck(dsName, rsName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[rsName]
if !ok {
return fmt.Errorf("can't find resource called %s in state", rsName)
}
ds, ok := s.RootModule().Resources[dsName]
if !ok {
return fmt.Errorf("can't find data source called %s in state", dsName)
}
dsAttr := ds.Primary.Attributes
rsAttr := rs.Primary.Attributes
attrsToTest := []string{
"id",
"name",
"description",
"self_link",
"fingerprint",
"port_name",
"protocol",
}
for _, attrToTest := range attrsToTest {
if dsAttr[attrToTest] != rsAttr[attrToTest] {
return fmt.Errorf("%s is %s; want %s", attrToTest, dsAttr[attrToTest], rsAttr[attrToTest])
}
}
return nil
}
}
func testAccDataSourceComputeBackendService_basic(serviceName, checkName string) string {
return fmt.Sprintf(`
resource "google_compute_backend_service" "foobar" {
name = "%s"
description = "foobar backend service"
health_checks = ["${google_compute_http_health_check.zero.self_link}"]
}
resource "google_compute_http_health_check" "zero" {
name = "%s"
request_path = "/"
check_interval_sec = 1
timeout_sec = 1
}
data "google_compute_backend_service" "baz" {
name = "${google_compute_backend_service.foobar.name}"
}
`, serviceName, checkName)
}
|
drebes/terraform-provider-google
|
google/data_source_google_compute_backend_service_test.go
|
GO
|
mpl-2.0
| 2,298
|
var le__mcc__call__interface_8h =
[
[ "le_mcc_call_ObjRef_t", "le__mcc__call__interface_8h.html#adb403b78b90d26456b14cd87a6c05e13", null ],
[ "le_mcc_call_Event_t", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64d", [
[ "LE_MCC_CALL_EVENT_SETUP", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64daa83d79b7ccf291f545164197570fcdd4", null ],
[ "LE_MCC_CALL_EVENT_INCOMING", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64da971b31d8f5a8cabf795780e4d721adea", null ],
[ "LE_MCC_CALL_EVENT_ORIGINATING", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64da481e407f5712a697608e60c1b920f878", null ],
[ "LE_MCC_CALL_EVENT_ALERTING", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64daaa445ae80d34bb798b72f0f31bebe67b", null ],
[ "LE_MCC_CALL_EVENT_EARLY_MEDIA", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64da0d304272e7e8f9d6a4e1923daf63afb6", null ],
[ "LE_MCC_CALL_EVENT_CONNECTED", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64da13c1a8ce7da144401a7937f079309ff7", null ],
[ "LE_MCC_CALL_EVENT_TERMINATED", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64da7f95cd7924bc34e3def72205a3891f99", null ],
[ "LE_MCC_CALL_EVENT_ON_HOLD", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64dac4281988a5957cee6cc2d5bd466aca77", null ],
[ "LE_MCC_CALL_EVENT_TRANSFERED", "le__mcc__call__interface_8h.html#adcb2920422915a863a7ea52fe592d64daaf273c41d23e623f6a7bc568c3a87936", null ]
] ],
[ "le_mcc_call_TerminationReason_t", "le__mcc__call__interface_8h.html#aff3a5f9c95b4d6193c6cd4f5e18cfd45", [
[ "LE_MCC_CALL_TERM_NETWORK_FAIL", "le__mcc__call__interface_8h.html#aff3a5f9c95b4d6193c6cd4f5e18cfd45ae1bb2a2961ee568f23e46ca30e406c11", null ],
[ "LE_MCC_CALL_TERM_BAD_ADDRESS", "le__mcc__call__interface_8h.html#aff3a5f9c95b4d6193c6cd4f5e18cfd45a0e1637581f65a05a7f956b7f6dd87a11", null ],
[ "LE_MCC_CALL_TERM_BUSY", "le__mcc__call__interface_8h.html#aff3a5f9c95b4d6193c6cd4f5e18cfd45a3ad42e63dd9bfc1da9ef7506b1ab9a3f", null ],
[ "LE_MCC_CALL_TERM_LOCAL_ENDED", "le__mcc__call__interface_8h.html#aff3a5f9c95b4d6193c6cd4f5e18cfd45ac9a12fc2deae9482f59de4af60bc9ca1", null ],
[ "LE_MCC_CALL_TERM_REMOTE_ENDED", "le__mcc__call__interface_8h.html#aff3a5f9c95b4d6193c6cd4f5e18cfd45a780b9095d30894205afbd686719fad1d", null ],
[ "LE_MCC_CALL_TERM_NOT_DEFINED", "le__mcc__call__interface_8h.html#aff3a5f9c95b4d6193c6cd4f5e18cfd45af0e8d56718b57548c3533727060af5f4", null ]
] ],
[ "le_mcc_call_Answer", "le__mcc__call__interface_8h.html#a2baf050ffc6b4cd4ff465a621d31fd91", null ],
[ "le_mcc_call_ConnectService", "le__mcc__call__interface_8h.html#a10ec16cd704ac9d7e337d3475adb4ee9", null ],
[ "le_mcc_call_Delete", "le__mcc__call__interface_8h.html#a9f2a3ed81f334a3d8dc04b81ac87fd86", null ],
[ "le_mcc_call_DisconnectService", "le__mcc__call__interface_8h.html#a9161d6e76a1849a30652d5da17d99f2a", null ],
[ "le_mcc_call_GetCallerIdRestrict", "le__mcc__call__interface_8h.html#ac73adc5f613e7a92d2e4a12b7f527c22", null ],
[ "le_mcc_call_GetRemoteTel", "le__mcc__call__interface_8h.html#aaeef08727353b823be55f83d40c9290a", null ],
[ "le_mcc_call_GetRxAudioStream", "le__mcc__call__interface_8h.html#a340c69ac34db98ee1248a6d11a229372", null ],
[ "le_mcc_call_GetTerminationReason", "le__mcc__call__interface_8h.html#af6bf77424889dd65d573ad15333fef36", null ],
[ "le_mcc_call_GetTxAudioStream", "le__mcc__call__interface_8h.html#ae22c0dead782b11ecfa60a3a9532fde6", null ],
[ "le_mcc_call_HangUp", "le__mcc__call__interface_8h.html#a7a3f07a065bd6d6f1ae6ec9573a993f7", null ],
[ "le_mcc_call_HangUpAll", "le__mcc__call__interface_8h.html#ae49b9359c93235613e69368aa1c83687", null ],
[ "le_mcc_call_IsConnected", "le__mcc__call__interface_8h.html#a53eb3004475df2bd63c860552d1597ca", null ],
[ "le_mcc_call_SetCallerIdRestrict", "le__mcc__call__interface_8h.html#ae7d3baaab9205f0cbf04c947c6e25f47", null ],
[ "le_mcc_call_Start", "le__mcc__call__interface_8h.html#a20caad708661519760a699c9b45724c8", null ]
];
|
legatoproject/legato-docs
|
15_01_1/le__mcc__call__interface_8h.js
|
JavaScript
|
mpl-2.0
| 4,200
|
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using referrer-policy/generic/template/test.release.html.template. -->
<html>
<head>
<title>Referrer-Policy: Referrer Policy is set to 'no-referrer'</title>
<meta name="description" content="Check that sub-resource never gets the referrer URL.">
<!-- No meta: Referrer policy delivered via HTTP headers. -->
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-no-referrer">
<meta name="assert" content="The referrer URL is omitted when a
document served over http requires an https
sub-resource via iframe-tag using the http-rp
delivery method with swap-origin-redirect and when
the target request is cross-origin.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<!-- TODO(kristijanburnik): Minify and merge both: -->
<script src="/referrer-policy/generic/common.js"></script>
<script src="/referrer-policy/generic/referrer-policy-test-case.js?pipe=sub"></script>
</head>
<body>
<script>
ReferrerPolicyTestCase(
{
"referrer_policy": "no-referrer",
"delivery_method": "http-rp",
"redirection": "swap-origin-redirect",
"origin": "cross-origin",
"source_protocol": "http",
"target_protocol": "https",
"subresource": "iframe-tag",
"subresource_path": "/referrer-policy/generic/subresource/document.py",
"referrer_url": "omitted"
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
|
fduraffourg/servo
|
tests/wpt/web-platform-tests/referrer-policy/no-referrer/http-rp/cross-origin/http-https/iframe-tag/generic.swap-origin-redirect.http.html
|
HTML
|
mpl-2.0
| 1,960
|
/**
** TALLOC.C
**
** lean_and_mean malloc()/free implementation
** by tom ehlert, te@drivesnapshot.de
**
** please be careful:
**
** this is only slightly tested and has NO ERRORCHECCKING AT ALL
** no internal checking. no stack checking. nothing !!
**
** use it only, if your programs are already debugged !!
**/
#include <stddef.h>
#include <string.h>
#ifdef __TURBOC__
extern void *__brklvl;
#define sbrk(x) __brklvl
#define brk(newbrk) \
(((char *)(newbrk) > (char *)(&length) - 0x200) ? \
-1 : \
(__brklvl = (newbrk), 0))
#endif
#ifdef __WATCOMC__
#include <stdlib.h>
#define brk(newbrk) ((int)__brk((unsigned)(newbrk)))
#endif
#ifdef __GNUC__
#include <unistd.h>
#endif
#define BUSY (sizeof(size_t)-1) /* Bit set if memory block in use*/
#define isbusy(x) ((x->length)&BUSY)
/**
*** _memavl()
*** return max. memory available
*** Q & D
**/
#ifdef DEBUG
extern int printf(const char *x, ...);
#define dbprintf(x) printf x
#else
#define dbprintf(x)
#endif
/*#define printf getch() != ' ' ? exit(0) : printf*/
typedef union {
size_t length;
char data[1];
} block;
void *malloc(size_t length)
{
static block *alloc_bottom = NULL;
block *akt, *next;
block *ltop = sbrk(0);
if (alloc_bottom == NULL)
alloc_bottom = ltop;
length = (length + sizeof(size_t) + BUSY) & ~BUSY;
akt = alloc_bottom;
for (;;) {
if (akt == ltop) {
/* end of initialized memory */
next = (block *)&akt->data[length];
if (next < akt || brk(next) == -1)
return NULL;
break;
}
dbprintf(("follow [%x] = %x\n",akt, akt->length));
next = (block *)(&akt->data[akt->length & ~BUSY]);
if (next == ltop || isbusy(akt)) {
akt = next; /* next block */
} else if (isbusy(next)) {
size_t size = akt->length;
if (size >= length) { /* try to split */
if (size > length) { /* split */
((block *)&akt->data[length])->length =
size - length;
}
break;
}
akt = next; /* next block */
} else {
/* merge 2 blocks */
akt->length += next->length;
}
}
akt->length = length | BUSY;
dbprintf(("set [%x] = %x\n",akt,akt->length));
return &akt->data[sizeof(size_t)];
}
#ifdef __WATCOMC__
void *_nmalloc(unsigned length)
{
return malloc(length);
}
#endif
/**
** reset busy-bit
**/
void free(void *ptr)
{
if (ptr)
((char *) ptr)[-sizeof(size_t)] &= ~BUSY;
}
#ifdef TALLOC_NEED_REALLOC
/* there isn't often need for realloc ;)
*/
void* realloc(void *ptr,size_t newlength)
{
size_t oldlength = ((size_t*)ptr)[-1] & ~BUSY;
void *newptr;
newptr = malloc(newlength);
if (newptr == NULL)
{
if (newlength <= oldlength)
return ptr;
}
else {
memcpy(newptr,ptr,oldlength);
}
free(ptr);
return newptr;
}
#endif
#ifdef TEST
#include <stdio.h>
int gallocated = 0;
void *testalloc(size_t length)
{
void *p;
printf("alloc %x bytes - ",length);
p = malloc(length);
if (p) gallocated += length,printf("at %x - sum=%x\n",p,gallocated);
else printf("failed\n");
return p;
}
void testfree(void* p)
{
gallocated -= ((size_t*)p)[-1] & ~BUSY;
printf("free %x \n",p);
free(p);
}
main()
{
char *s1,*s2,*s3,*s4,*s5,*s6;
unsigned size;
s1 = testalloc(1);
s2 = testalloc(2);
s3 = testalloc(0x10);
s4 = testalloc(0x100);
s5 = testalloc(0x1000);
s6 = testalloc(0xfff0);
testfree(s3);
s3 = testalloc(6);
testfree(s2);
testalloc(8);
#ifdef __GNUC__
for(size = 0xe0000000; size;)
#else
for(size = 0xe000; size;)
#endif
{
if (testalloc(size))
;
else
size >>= 1;
}
testfree(s1);
testfree(s5);
testfree(s4);
testfree(s6);
return 1;
}
#endif
|
joyent/sdcboot
|
freedos/source/more/talloc.c
|
C
|
mpl-2.0
| 3,933
|
package org.hl7.v3;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for BXIT_CD complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BXIT_CD">
* <complexContent>
* <extension base="{urn:hl7-org:v3}CD">
* <attribute name="qty" type="{urn:hl7-org:v3}int" default="1" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BXIT_CD")
public class BXITCD
extends CD
{
@XmlAttribute(name = "qty")
protected BigInteger qty;
/**
* Gets the value of the qty property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getQty() {
if (qty == null) {
return new BigInteger("1");
} else {
return qty;
}
}
/**
* Sets the value of the qty property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setQty(BigInteger value) {
this.qty = value;
}
}
|
jembi/openhim-encounter-orchestrator
|
src/main/java/org/hl7/v3/BXITCD.java
|
Java
|
mpl-2.0
| 1,392
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.vo.beans;
public class PatientForDementiaVoBean extends ims.vo.ValueObjectBean
{
public PatientForDementiaVoBean()
{
}
public PatientForDementiaVoBean(ims.clinical.vo.PatientForDementiaVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.name = vo.getName() == null ? null : (ims.core.vo.beans.PersonNameBean)vo.getName().getBean();
this.dob = vo.getDob() == null ? null : (ims.framework.utils.beans.PartialDateBean)vo.getDob().getBean();
this.identifiers = vo.getIdentifiers() == null ? null : vo.getIdentifiers().getBeanCollection();
this.ward = vo.getWard() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getWard().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.clinical.vo.PatientForDementiaVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.name = vo.getName() == null ? null : (ims.core.vo.beans.PersonNameBean)vo.getName().getBean(map);
this.dob = vo.getDob() == null ? null : (ims.framework.utils.beans.PartialDateBean)vo.getDob().getBean();
this.identifiers = vo.getIdentifiers() == null ? null : vo.getIdentifiers().getBeanCollection();
this.ward = vo.getWard() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getWard().getBean(map);
}
public ims.clinical.vo.PatientForDementiaVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.clinical.vo.PatientForDementiaVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.clinical.vo.PatientForDementiaVo vo = null;
if(map != null)
vo = (ims.clinical.vo.PatientForDementiaVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.clinical.vo.PatientForDementiaVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.core.vo.beans.PersonNameBean getName()
{
return this.name;
}
public void setName(ims.core.vo.beans.PersonNameBean value)
{
this.name = value;
}
public ims.framework.utils.beans.PartialDateBean getDob()
{
return this.dob;
}
public void setDob(ims.framework.utils.beans.PartialDateBean value)
{
this.dob = value;
}
public ims.core.vo.beans.PatientIdBean[] getIdentifiers()
{
return this.identifiers;
}
public void setIdentifiers(ims.core.vo.beans.PatientIdBean[] value)
{
this.identifiers = value;
}
public ims.core.vo.beans.LocationLiteVoBean getWard()
{
return this.ward;
}
public void setWard(ims.core.vo.beans.LocationLiteVoBean value)
{
this.ward = value;
}
private Integer id;
private int version;
private ims.core.vo.beans.PersonNameBean name;
private ims.framework.utils.beans.PartialDateBean dob;
private ims.core.vo.beans.PatientIdBean[] identifiers;
private ims.core.vo.beans.LocationLiteVoBean ward;
}
|
IMS-MAXIMS/openMAXIMS
|
Source Library/openmaxims_workspace/ValueObjects/src/ims/clinical/vo/beans/PatientForDementiaVoBean.java
|
Java
|
agpl-3.0
| 5,183
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# 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 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/.
#
##############################################################################
{
"name": "MPS - Sale forecast",
"version": "1.0",
"depends": [
"base",
"product",
"sale",
"stock",
],
"author": "OdooMRP team",
"contributors": [
"Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>",
"Ainara Galdona <ainaragaldona@avanzosc.es>",
"Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>",
"Ana Juaristi <anajuaristi@avanzosc.es>",
],
"category": "MPS",
"website": "http://www.odoomrp.com",
"summary": "Sale forecast",
"data": ["security/ir.model.access.csv",
"wizard/sale_forecast_load_view.xml",
"views/sale_view.xml",
],
"installable": True,
"auto_install": False,
}
|
StefanRijnhart/odoomrp-wip
|
procurement_sale_forecast/__openerp__.py
|
Python
|
agpl-3.0
| 1,597
|
Ekylibre::FirstRun.add_loader :sales do |first_run|
# Import sales
first_run.import_file(:ekylibre_sales, "alamano/sales.csv")
# Import incoming link to sale
first_run.import_file(:ekylibre_incoming_payments, "alamano/incoming_payments.csv")
end
|
gaapt/ekylibre
|
lib/ekylibre/first_run/loaders/sales.rb
|
Ruby
|
agpl-3.0
| 257
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo.lookups;
import ims.framework.cn.data.TreeModel;
import ims.framework.cn.data.TreeNode;
import ims.vo.LookupInstanceCollection;
import ims.vo.LookupInstVo;
public class BedSpaceTypeCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel
{
private static final long serialVersionUID = 1L;
public void add(BedSpaceType value)
{
super.add(value);
}
public int indexOf(BedSpaceType instance)
{
return super.indexOf(instance);
}
public boolean contains(BedSpaceType instance)
{
return indexOf(instance) >= 0;
}
public BedSpaceType get(int index)
{
return (BedSpaceType)super.getIndex(index);
}
public void remove(BedSpaceType instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public Object clone()
{
BedSpaceTypeCollection newCol = new BedSpaceTypeCollection();
BedSpaceType item;
for (int i = 0; i < super.size(); i++)
{
item = this.get(i);
newCol.add(new BedSpaceType(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder()));
}
for (int i = 0; i < newCol.size(); i++)
{
item = newCol.get(i);
if (item.getParent() != null)
{
int parentIndex = this.indexOf(item.getParent());
if(parentIndex >= 0)
item.setParent(newCol.get(parentIndex));
else
item.setParent((BedSpaceType)item.getParent().clone());
}
}
return newCol;
}
public BedSpaceType getInstance(int instanceId)
{
return (BedSpaceType)super.getInstanceById(instanceId);
}
public TreeNode[] getRootNodes()
{
LookupInstVo[] roots = super.getRoots();
TreeNode[] nodes = new TreeNode[roots.length];
System.arraycopy(roots, 0, nodes, 0, roots.length);
return nodes;
}
public BedSpaceType[] toArray()
{
BedSpaceType[] arr = new BedSpaceType[this.size()];
super.toArray(arr);
return arr;
}
public static BedSpaceTypeCollection buildFromBeanCollection(java.util.Collection beans)
{
BedSpaceTypeCollection coll = new BedSpaceTypeCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while(iter.hasNext())
{
coll.add(BedSpaceType.buildLookup((ims.vo.LookupInstanceBean)iter.next()));
}
return coll;
}
public static BedSpaceTypeCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans)
{
BedSpaceTypeCollection coll = new BedSpaceTypeCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(BedSpaceType.buildLookup(beans[x]));
}
return coll;
}
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/lookups/BedSpaceTypeCollection.java
|
Java
|
agpl-3.0
| 4,802
|
/*
* digitalpetri OPC-UA SDK
*
* Copyright (C) 2015 Kevin Herron
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.digitalpetri.opcua.sdk.server.model.objects;
import java.util.Optional;
import com.digitalpetri.opcua.sdk.core.model.objects.ServerDiagnosticsType;
import com.digitalpetri.opcua.sdk.core.model.objects.SessionsDiagnosticsSummaryType;
import com.digitalpetri.opcua.sdk.core.model.variables.SamplingIntervalDiagnosticsArrayType;
import com.digitalpetri.opcua.sdk.core.model.variables.ServerDiagnosticsSummaryType;
import com.digitalpetri.opcua.sdk.core.model.variables.SubscriptionDiagnosticsArrayType;
import com.digitalpetri.opcua.sdk.core.nodes.ObjectNode;
import com.digitalpetri.opcua.sdk.core.nodes.VariableNode;
import com.digitalpetri.opcua.sdk.server.api.UaNamespace;
import com.digitalpetri.opcua.sdk.server.util.UaObjectType;
import com.digitalpetri.opcua.stack.core.types.builtin.DataValue;
import com.digitalpetri.opcua.stack.core.types.builtin.LocalizedText;
import com.digitalpetri.opcua.stack.core.types.builtin.NodeId;
import com.digitalpetri.opcua.stack.core.types.builtin.QualifiedName;
import com.digitalpetri.opcua.stack.core.types.builtin.Variant;
import com.digitalpetri.opcua.stack.core.types.builtin.unsigned.UByte;
import com.digitalpetri.opcua.stack.core.types.builtin.unsigned.UInteger;
@UaObjectType(name = "ServerDiagnosticsType")
public class ServerDiagnosticsNode extends BaseObjectNode implements ServerDiagnosticsType {
public ServerDiagnosticsNode(
UaNamespace namespace,
NodeId nodeId,
QualifiedName browseName,
LocalizedText displayName,
Optional<LocalizedText> description,
Optional<UInteger> writeMask,
Optional<UInteger> userWriteMask,
UByte eventNotifier) {
super(namespace, nodeId, browseName, displayName, description, writeMask, userWriteMask, eventNotifier);
}
public ServerDiagnosticsSummaryType getServerDiagnosticsSummary() {
Optional<VariableNode> serverDiagnosticsSummary = getVariableComponent("ServerDiagnosticsSummary");
return serverDiagnosticsSummary.map(node -> (ServerDiagnosticsSummaryType) node).orElse(null);
}
public SamplingIntervalDiagnosticsArrayType getSamplingIntervalDiagnosticsArray() {
Optional<VariableNode> samplingIntervalDiagnosticsArray = getVariableComponent("SamplingIntervalDiagnosticsArray");
return samplingIntervalDiagnosticsArray.map(node -> (SamplingIntervalDiagnosticsArrayType) node).orElse(null);
}
public SubscriptionDiagnosticsArrayType getSubscriptionDiagnosticsArray() {
Optional<VariableNode> subscriptionDiagnosticsArray = getVariableComponent("SubscriptionDiagnosticsArray");
return subscriptionDiagnosticsArray.map(node -> (SubscriptionDiagnosticsArrayType) node).orElse(null);
}
public SessionsDiagnosticsSummaryType getSessionsDiagnosticsSummary() {
Optional<ObjectNode> sessionsDiagnosticsSummary = getObjectComponent("SessionsDiagnosticsSummary");
return sessionsDiagnosticsSummary.map(node -> (SessionsDiagnosticsSummaryType) node).orElse(null);
}
public Boolean getEnabledFlag() {
Optional<Boolean> enabledFlag = getProperty("EnabledFlag");
return enabledFlag.orElse(null);
}
public synchronized void setServerDiagnosticsSummary(ServerDiagnosticsSummaryType serverDiagnosticsSummary) {
getVariableComponent("ServerDiagnosticsSummary").ifPresent(n -> {
n.setValue(new DataValue(new Variant(serverDiagnosticsSummary)));
});
}
public synchronized void setSamplingIntervalDiagnosticsArray(SamplingIntervalDiagnosticsArrayType samplingIntervalDiagnosticsArray) {
getVariableComponent("SamplingIntervalDiagnosticsArray").ifPresent(n -> {
n.setValue(new DataValue(new Variant(samplingIntervalDiagnosticsArray)));
});
}
public synchronized void setSubscriptionDiagnosticsArray(SubscriptionDiagnosticsArrayType subscriptionDiagnosticsArray) {
getVariableComponent("SubscriptionDiagnosticsArray").ifPresent(n -> {
n.setValue(new DataValue(new Variant(subscriptionDiagnosticsArray)));
});
}
public synchronized void setEnabledFlag(Boolean enabledFlag) {
getPropertyNode("EnabledFlag").ifPresent(n -> {
n.setValue(new DataValue(new Variant(enabledFlag)));
});
}
}
|
bencaldwell/ua-server-sdk
|
ua-server/src/main/java/com/digitalpetri/opcua/sdk/server/model/objects/ServerDiagnosticsNode.java
|
Java
|
agpl-3.0
| 5,099
|
/*
* NotebookOutput.hpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SESSION_NOTEBOOK_OUTPUT_HPP
#define SESSION_NOTEBOOK_OUTPUT_HPP
#include <string>
#define kChunkOutputPath "chunk_output"
#define kChunkOutputNone 0
#define kChunkOutputText 1
#define kChunkOutputPlot 2
#define kChunkOutputHtml 3
#define kChunkOutputError 4
#define kChunkConsoleInput 0
#define kChunkConsoleOutput 1
#define kChunkConsoleError 2
#define kChunkLibDir "lib"
namespace rstudio {
namespace core {
class FilePath;
class Error;
}
}
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
// forms for requesting the chunk output folder
enum ChunkOutputContext
{
ContextExact = 0, // always use the requested context
ContextSaved // fall back to saved context if exact doesn't exist
};
struct OutputPair
{
OutputPair() :
outputType(kChunkOutputNone), ordinal(1)
{}
OutputPair(unsigned type, unsigned ord):
outputType(type), ordinal(ord)
{}
unsigned outputType;
unsigned ordinal;
};
// given a document ID and a chunk ID, discover the last output the chunk had
OutputPair lastChunkOutput(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId);
void updateLastChunkOutput(const std::string& docId,
const std::string& chunkId,
const OutputPair& pair);
// compute chunk output folder paths for specific contexts
core::FilePath chunkOutputPath(
const std::string& docPath, const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId,
ChunkOutputContext ctxType);
core::FilePath chunkOutputPath(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId,
ChunkOutputContext ctxType);
core::FilePath chunkOutputPath(const std::string& docId,
const std::string& chunkId, ChunkOutputContext ctxType);
// compute individual chunk output unit paths
core::FilePath chunkOutputFile(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId,
const OutputPair& output);
core::FilePath chunkOutputFile(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId,
unsigned outputType);
core::Error cleanChunkOutput(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId,
bool preserveFolder);
// helper for emitting console data to file
core::Error appendConsoleOutput(int chunkConsoleOutputType,
const std::string& output,
const core::FilePath& filePath);
// send chunk output to client
void enqueueChunkOutput(const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId,
int outputType, const core::FilePath& path);
core::Error enqueueChunkOutput(
const std::string& docPath, const std::string& docId,
const std::string& chunkId, const std::string& nbCtxId,
const std::string& requestId);
core::Error initOutput();
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
#endif
|
jar1karp/rstudio
|
src/cpp/session/modules/rmarkdown/NotebookOutput.hpp
|
C++
|
agpl-3.0
| 3,801
|
// Copyright © 2015 HSL <https://www.hsl.fi>
// This program is dual-licensed under the EUPL v1.2 and AGPLv3 licenses.
package fi.hsl.parkandride.dev;
import com.querydsl.sql.RelationalPath;
import com.querydsl.sql.postgresql.PostgreSQLQueryFactory;
import fi.hsl.parkandride.FeatureProfile;
import fi.hsl.parkandride.back.sql.*;
import fi.hsl.parkandride.core.back.UserRepository;
import fi.hsl.parkandride.core.domain.*;
import fi.hsl.parkandride.core.service.*;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.inject.Inject;
import java.util.Objects;
import static fi.hsl.parkandride.back.ContactDao.CONTACT_ID_SEQ;
import static fi.hsl.parkandride.back.FacilityDao.FACILITY_ID_SEQ;
import static fi.hsl.parkandride.back.HubDao.HUB_ID_SEQ;
import static fi.hsl.parkandride.back.OperatorDao.OPERATOR_ID_SEQ;
import static fi.hsl.parkandride.back.UserDao.USER_ID_SEQ;
import static fi.hsl.parkandride.back.prediction.PredictorDao.PREDICTOR_ID_SEQ;
import static java.lang.String.format;
@Component
@Profile({FeatureProfile.DEV_API})
public class DevHelper {
private final PostgreSQLQueryFactory queryFactory;
private final JdbcTemplate jdbcTemplate;
@Resource UserRepository userRepository;
@Resource UserService userService;
@Resource AuthenticationService authenticationService;
@Resource BatchingRequestLogService batchingRequestLogService;
@Inject
public DevHelper(PostgreSQLQueryFactory queryFactory, JdbcTemplate jdbcTemplate) {
this.queryFactory = queryFactory;
this.jdbcTemplate = jdbcTemplate;
}
@TransactionalWrite
public void deleteAll() {
deleteHubs();
deleteFacilities();
deleteContacts();
deleteUsers();
deleteOperators();
deleteRequestLog();
deleteLocks();
}
@TransactionalWrite
private void deleteLocks() {
delete(QLock.lock);
}
@TransactionalWrite
public void deleteContacts() {
delete(QContact.contact);
resetContactSequence();
}
@TransactionalWrite
public void deleteUsers() {
delete(QAppUser.appUser);
resetUserSequence();
}
@TransactionalWrite
public User createOrUpdateUser(NewUser newUser) {
UserSecret userSecret;
try {
userSecret = userRepository.getUser(newUser.username);
if (newUser.operatorId != null && !Objects.equals(newUser.operatorId, userSecret.user.operatorId)) {
throw new IllegalArgumentException("Tried to create user '" + newUser.username + "' with operatorId " + newUser.operatorId
+ ", but there already was a user with same name and operatorId " + userSecret.user.operatorId
+ " and we can't change the operatorId afterwards");
}
if (newUser.role != userSecret.user.role) {
userRepository.updateUser(userSecret.user.id, newUser);
}
if (newUser.password != null) {
userRepository.updatePassword(userSecret.user.id, authenticationService.encryptPassword(newUser.password));
}
} catch (NotFoundException e) {
userSecret = new UserSecret();
userSecret.user = userService.createUserNoValidate(newUser);
}
return userSecret.user;
}
@TransactionalRead
public Login login(String username) {
UserSecret userSecret = userRepository.getUser(username);
Login login = new Login();
login.token = authenticationService.token(userSecret.user);
login.username = userSecret.user.username;
login.role = userSecret.user.role;
login.operatorId = userSecret.user.operatorId;
login.permissions = login.role.permissions;
return login;
}
@TransactionalWrite
public void deleteOperators() {
delete(QOperator.operator);
resetOperatorSequence();
}
@TransactionalWrite
public void deleteFacilities() {
delete(
QFacilityPredictionHistory.facilityPredictionHistory,
QFacilityPrediction.facilityPrediction,
QPredictor.predictor,
QFacilityUtilization.facilityUtilization,
QFacilityService.facilityService,
QFacilityPaymentMethod.facilityPaymentMethod,
QFacilityAlias.facilityAlias,
QPricing.pricing,
QPort.port,
QUnavailableCapacity.unavailableCapacity,
QFacilityStatusHistory.facilityStatusHistory,
QUnavailableCapacityHistory.unavailableCapacityHistory,
QFacilityCapacityHistory.facilityCapacityHistory,
QFacility.facility);
resetPredictorSequence();
resetFacilitySequence();
}
@TransactionalWrite
public void deleteHubs() {
delete(QHubFacility.hubFacility, QHub.hub);
resetHubSequence();
}
@TransactionalWrite
private void deleteRequestLog() {
batchingRequestLogService.clearLogStash();
delete(QRequestLog.requestLog);
delete(QRequestLogSource.requestLogSource);
delete(QRequestLogUrl.requestLogUrl);
}
@TransactionalWrite
public void resetHubSequence() {
resetSequence(HUB_ID_SEQ, queryFactory.from(QHub.hub).select(QHub.hub.id.max()).fetchOne());
}
@TransactionalWrite
public void resetFacilitySequence() {
resetSequence(FACILITY_ID_SEQ, queryFactory.from(QFacility.facility).select(QFacility.facility.id.max()).fetchOne());
}
@TransactionalWrite
public void resetPredictorSequence() {
resetSequence(PREDICTOR_ID_SEQ, queryFactory.from(QPredictor.predictor).select(QPredictor.predictor.id.max()).fetchOne());
}
@TransactionalWrite
public void resetContactSequence() {
resetSequence(CONTACT_ID_SEQ, queryFactory.from(QContact.contact).select(QContact.contact.id.max()).fetchOne());
}
@TransactionalWrite
public void resetUserSequence() {
resetSequence(USER_ID_SEQ, queryFactory.from(QAppUser.appUser).select(QAppUser.appUser.id.max()).fetchOne());
}
@TransactionalWrite
public void resetOperatorSequence() {
resetSequence(OPERATOR_ID_SEQ, queryFactory.from(QOperator.operator).select(QOperator.operator.id.max()).fetchOne());
}
private void delete(RelationalPath... tables) {
for (RelationalPath table : tables) {
queryFactory.delete(table).execute();
}
}
private void resetSequence(String sequence, Long currentMax) {
if (currentMax == null) {
currentMax = 0L;
}
jdbcTemplate.execute(format("drop sequence %s", sequence));
jdbcTemplate.execute(format("create sequence %s increment by 1 start with %s", sequence, currentMax + 1));
}
}
|
jpaajarv/parkandrideAPI
|
application/src/main/java/fi/hsl/parkandride/dev/DevHelper.java
|
Java
|
agpl-3.0
| 7,029
|
<?php
/**
* @file classes/controllers/grid/GridCellProvider.inc.php
*
* Copyright (c) 2000-2012 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @class GridCellProvider
* @ingroup controllers_grid
*
* @brief Base class for a grid column's cell provider
*/
class GridCellProvider {
/**
* Constructor
*/
function GridCellProvider() {
}
//
// Public methods
//
/**
* To be used by a GridRow to generate a rendered representation of
* the element for the given column.
*
* @param $row GridRow
* @param $column GridColumn
* @return string the rendered representation of the element for the given column
*/
function render(&$request, &$row, &$column) {
$columnId = $column->getId();
assert(!empty($columnId));
$templateVars = $this->getTemplateVarsFromRowColumn($row, $column);
// Construct a default cell id
$rowId = $row->getId();
assert(isset($rowId));
$cellId = $rowId.'-'.$columnId;
// Pass control to the view to render the cell
$templateMgr =& TemplateManager::getManager();
$templateMgr->assign('id', $cellId);
$templateMgr->assign_by_ref('column', $column);
$templateMgr->assign_by_ref('actions', $this->getCellActions($request, $row, $column));
$templateMgr->assign_by_ref('flags', $column->getFlags());
// assign all values from element (FIXME: by ref not working for some reason)
foreach ($templateVars as $varName => $varValue) {
$templateMgr->assign($varName, $varValue);
}
$template = $column->getTemplate();
assert(!empty($template));
return $templateMgr->fetch($template);
}
//
// Protected template methods
//
/**
* Subclasses have to implement this method to extract variables
* for a given column from a data element so that they may be assigned
* to template before rendering.
* @param $row GridRow
* @param $column GridColumn
* @return array
*/
function getTemplateVarsFromRowColumn(&$row, $column) {
return array();
}
/**
* Subclasses can override this template method to provide
* cell specific actions.
*
* NB: The default implementation delegates to the grid row for
* row specific actions. Another thinkable implementation would
* be column-specific actions in which case action instantiation
* should be delegated to the column.
*
* @param $row GridRow
* @param $column GridColumn
* @return array an array of LinkAction instances
*/
function &getCellActions(&$request, &$row, &$column, $position = GRID_ACTION_POSITION_DEFAULT) {
$actions =& $row->getCellActions($request, $column, $position);
return $actions;
}
}
|
yvonnehoffmann/MindResearchRepository
|
ojs-2.3.8/lib/pkp/classes/controllers/grid/GridCellProvider.inc.php
|
PHP
|
agpl-3.0
| 2,626
|
require 'rails_helper'
RSpec.describe 'projects/show' , :type => :view do
before :each do
@this_user = User.create! :nick => 'a-name' , :uid => 'a-uid'
@project = assign :project , (Project.create! :name => 'A Project' ,
:repo => 'https://example.org/user/repo' ,
:desc => 'A description' ,
:user_id => 1 )
end
it "infers the controller path" do
(expect controller.request.path_parameters[:controller]).to eq 'projects'
(expect controller.controller_path).to eq 'projects'
end
it "infers the controller action" do
(expect controller.request.path_parameters[:action]).to eq 'show'
end
it "renders attributes" do
render
(expect response).to render_template :show
(expect rendered).to match /A Project/
(expect rendered).to match /https:\/\/example.org\/user\/repo/
(expect rendered).to match /A description/
end
end
|
LiveCodingTVOfficial/community_website
|
spec/views/projects/show.html.erb_spec.rb
|
Ruby
|
agpl-3.0
| 1,111
|
#
# Copyright (C) 2011 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
class NotificationPolicy < ActiveRecord::Base
belongs_to :notification
belongs_to :user
belongs_to :communication_channel
before_save :infer_frequency
attr_accessible :notification, :user, :communication_channel, :frequency, :notification_id, :user_id, :communication_channel_id
# This is for choosing a policy for another context, so:
# user.notification_policies.for(notification) or
# user.notification_policies.for(communication_channel) or
# communication_channel.notification_policies.for(notification)
named_scope :for, lambda { |context|
case context
when User
{ :conditions => ['notification_policies.user_id = ?', context.id] }
when Notification
{ :conditions => ['notification_policies.notification_id = ?', context.id] }
when CommunicationChannel
{ :conditions => ['notification_policies.communication_channel_id = ?', context.id] }
else
{}
end
}
# TODO: the named_scope name should be self-explanatory... change
# this to by_frequency or something
# This is for choosing a policy by frequency
named_scope :by, lambda { |freq|
case freq
when Array
{ :conditions => { :frequency => freq.map{|f| f.to_s} } }
else
{ :conditions => ['notification_policies.frequency = ?', freq.to_s] }
end
}
named_scope :where, lambda { |where| { :include => [:communication_channel], :conditions => where } }
named_scope :in_state, lambda { |state| { :conditions => ["notification_policies.workflow_state = ?", state.to_s] } }
named_scope :for_channel, lambda { |channel| { :conditions => ['notification_policies.communication_channel_id = ?', channel.id] } }
def infer_frequency
self.frequency ||= "immediately"
end
protected :infer_frequency
def communication_preference
return nil unless broadcast
communication_channel || user.communication_channel
end
def self.spam_blocked_by(user)
NotificationPolicy.delete_all({:user_id => user.id})
cc = user.communication_channel
cc.confirm
Notification.all.each do |notification|
if notification.category == "Message"
NotificationPolicy.create(:notification => notification, :user => user, :communication_channel => cc, :frequency => 'immediately')
else
NotificationPolicy.create(:notification => notification, :user => user, :communication_channel => cc, :frequency => 'never')
end
end
true
rescue => e
puts e.to_s
false
end
def self.refresh_for(user)
categories = Notification.dashboard_categories
policies = user.notification_policies.to_a
params = {}
categories.each do |category|
ps = policies.select{|p| p.notification_id == category.id }
params["category_#{category.category_slug}".to_sym] = {}
ps.each do |p|
params["category_#{category.category_slug}".to_sym]["channel_#{p.communication_channel_id}"] = p.frequency
end
end
setup_for(user, params)
end
def self.setup_for(user, params)
@user = user
user.preferences[:send_scores_in_emails] = params[:root_account] &&
params[:root_account].settings[:allow_sending_scores_in_emails] != false &&
params[:user] && params[:user][:send_scores_in_emails] == '1'
params[:user].try(:delete, :send_scores_in_emails)
@user.update_attributes(params[:user])
@old_policies = @user.notification_policies
@channels = @user.communication_channels
categories = Notification.dashboard_categories
prefs_to_save = []
categories.each do |category|
category_data = params["category_#{category.category_slug}".to_sym]
channels = []
if category_data
category_data.each do |key, value|
tag, id = key.split("_", 2)
channels << @channels.find(id) if tag == "channel" rescue nil
end
channels.compact!
notifications = Notification.find_all_by_category(category.category)
notifications.each do |notification|
if channels.empty?
channels << @user.communication_channel
end
if category.category == 'Message'
found_immediately = channels.any?{|c| category_data["channel_#{c.id}".to_sym] == 'immediately' }
unless found_immediately
channels << @user.communication_channel
category_data["channel_#{@user.communication_channel.id}".to_sym] = 'immediately'
end
end
channels.uniq.each do |channel|
frequency = category_data["channel_#{channel.id}".to_sym] || 'never'
pref = @user.notification_policies.new
pref.notification_id = notification.id
pref.frequency = frequency
pref.communication_channel_id = channel.id
prefs_to_save << pref
end
end
end
end
NotificationPolicy.transaction do
NotificationPolicy.connection.execute("DELETE FROM notification_policies WHERE id IN (#{@old_policies.map(&:id).join(',')})") unless @old_policies.empty?
prefs_to_save.each{|p| p.save! }
end
categories = Notification.dashboard_categories
@user.reload
@policies = @user.notification_policies.select{|p| categories.include?(p.notification)}
@policies
end
end
|
faraazkhan/canvas
|
app/models/notification_policy.rb
|
Ruby
|
agpl-3.0
| 5,968
|
/* CSS */
.cpsx_block .count {
font-weight: inherit;
}
.cpsx_block p {
cursor: pointer;
}
.cpsx_block {
align : right;
overflow: hidden;
position: fixed;
bottom: 2px;
left: 5%;
border: 3px solid #CCCCCC;
background-color: white;
height: 300px;
width: 19%;
}
#toggle_checkbox {
display: none;
}
#toggle_checkbox:checked + .cpsx_block {
overflow: hidden;
position: fixed;
bottom: 0px;
left: 91%;
border: none;
background-color: none;
height: 37px;
width: 45px;
}
/* use this to embed in problem frame
#toggle_checkbox:checked + .cpsx_block {
align : right;
overflow: intitial;
position: static;
bottom: 0px;
left: 0%;
border: none;
background-color: white;
height: 200px;
width: 100%;
}
*/
.toggle_view {
background: #000000;
float: right;
display: table;
height: 37px;
width: 40px;
opacity: 0.25;
-webkit-transition-timing-function: ease-in-out; /* Safari and Chrome */
transition-timing-function: ease-in-out;
-webkit-transition: opacity .5s; /* For Safari 3.1 to 6.0 */
transition: opacity .5s;
}
.toggle_view:hover{
opacity: .60;
}
/* Does the rest of this do anything? */
.logoutbutton {
border: 1px solid #cacaca;
border-radius: 3px;
box-shadow: inset 0 1px 0 0 #fff;
color: #333;
display: inline-block;
font-size: inherit;font-weight: bold;
background-color: #eee;
background-image: linear-gradient(#eee,#d2d2d2);
padding: 1px 2px;
text-decoration: none;
text-shadow: 0 1px 0 #f8f8f8;
background-clip: padding-box;
font-size: 0.6125em;
height: 20px;
vertical-align: middle;
font-weight: 600;
margin-top:14px;
}
.printError {
color: #ae0a0a;
}
.boxprice {
background-color:#F4F4F4;
width:250px;
padding:15px;
border:1px solid #CCCCCC;
}
.submitbutton, .submitbutton input[type="button"]{
cursor:pointer;
padding:5px 25px;
background:#35b128;
border:1px solid #33842a;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 0 4px rgba(0,0,0, .75);
-moz-box-shadow: 0 0 4px rgba(0,0,0, .75);
box-shadow: 0 0 4px rgba(0,0,0, .75);
color:#f3f3f3;
font-size:1.1em;
}
.submitbutton:hover, .submitbutton:focus{
background-color :#399630;
-webkit-box-shadow: 0 0 1px rgba(0,0,0, .75);
-moz-box-shadow: 0 0 1px rgba(0,0,0, .75);
box-shadow: 0 0 1px rgba(0,0,0, .75);
}
|
ybergner/cpsx
|
xblock/cpsx/public/css/style.css
|
CSS
|
agpl-3.0
| 2,375
|
OC.L10N.register(
"templateeditor",
{
"Could not load template" : "Klarte ikke å laste mal",
"Saved" : "Lagret",
"Reset" : "Tilbakestill",
"An error occurred" : "En feil har oppstått",
"Sharing email - public link shares (HTML)" : "Delings-epost - offentlige lenke-delinger (HTML)",
"Sharing email - public link shares (plain text fallback)" : "Delings-epost - offentlige lenke-delinger (ren tekst)",
"Sharing email (HTML)" : "Delings-epost (HTML)",
"Sharing email (plain text fallback)" : "Delings-epost (ren tekst)",
"Lost password mail" : "E-post om mistet passord",
"New user email (HTML)" : "E-post om ny bruker (HTML)",
"New user email (plain text fallback)" : "E-post om ny bruker (ren tekst)",
"Activity notification mail" : "E-post med varsling om aktivitet",
"Mail Templates" : "Maler for e-poster",
"Theme" : "Tema",
"Template" : "Mal",
"Please choose a template" : "Velg en mal",
"Save" : "Lagre"
},
"nplurals=2; plural=(n != 1);");
|
ino1988/soulcloud
|
apps/templateeditor/l10n/nb_NO.js
|
JavaScript
|
agpl-3.0
| 1,023
|
/**
* Copyright (c) 2015, 2016 Bastien Bodart, François Michel, Clémentine Munyabarenzi
* 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/>.
*/
/**
* Une facture, sous forme d'une liste d'articles.
*
* @author Charles Pecheur
* @version 27 octobre 2012
*/
public class Facture {
private Article[] articles;
private String reference;
/**/private int numero;
/**
* @pre reference != null
* @post A cree une facture avec {description} et {articles}.
*/
public Facture(String reference, Article[] articles) {
this.reference = reference;
this.articles = articles;
}
/**
* @pre -
* @post A imprime la facture.
*/
public void printFacture() {
printEntete();
double totalPrix = 0.0;
double totalTVA = 0.0;
for(int i = 0; i < articles.length; i++) {
Article art = articles[i];
printArticle(art);
totalPrix = totalPrix + art.getPrix();
totalTVA = totalTVA + art.getTVA();
}
printTotaux(totalPrix, totalTVA);
}
/**
* @pre -
* @post A imprime l'en-tete de la facture, comprenant le descriptif
* et les tetes de colonnes.
*/
public void printEntete() {
System.out.println("Facture " + reference);
System.out.println();
printBarre();
System.out.println("| Description | prix HTVA | TVA | prix TVAC |");
printBarre();
}
/**
* @pre -
* @post A imprime une barre sur la largeur de la facture.
*/
public void printBarre() {
System.out.println("===================================================================================");
}
/**
* @pre -
* @post A imprime une ligne de facture pour l'article {art}.
*/
public void printArticle(Article art) {
System.out.printf("| %-40s | %10.2f | %10.2f | %10.2f |\n",
art.getDescription(), art.getPrix(), art.getTVA(), art.getPrixTVAC());
}
/**
* @pre -
* @post A imprime une ligne de facture avec les totaux {prix} et {tva}.
*/
public void printTotaux(double prix, double tva) {
printBarre();
System.out.printf("| %-40s | %10.2f | %10.2f | %10.2f |\n",
"T O T A L", prix, tva, prix+tva);
}
/**
* @pre -
* @post A imprime une liste de livraison, comprenant toutes les
* pieces facturees avec leur poids.
*/
public void printLivraison() {
// A COMPLETER
}
/**
* @pre pce != null
* @post Retourne le nombre d'exemplaires de {pce} factures,
* en totalisant sur plusieurs articles si necessaire.
*/
//public int getNombre(Piece pce) {
// // A COMPLETER
//}
}
|
UCL-INGI/Informatique-1
|
inginious_dir/m7real/jplag/template/Facture.java
|
Java
|
agpl-3.0
| 3,454
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.naes.vo.lookups;
import ims.framework.cn.data.TreeModel;
import ims.framework.cn.data.TreeNode;
import ims.vo.LookupInstanceCollection;
import ims.vo.LookupInstVo;
public class UnderlyingReasonCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel
{
private static final long serialVersionUID = 1L;
public void add(UnderlyingReason value)
{
super.add(value);
}
public int indexOf(UnderlyingReason instance)
{
return super.indexOf(instance);
}
public boolean contains(UnderlyingReason instance)
{
return indexOf(instance) >= 0;
}
public UnderlyingReason get(int index)
{
return (UnderlyingReason)super.getIndex(index);
}
public void remove(UnderlyingReason instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public Object clone()
{
UnderlyingReasonCollection newCol = new UnderlyingReasonCollection();
UnderlyingReason item;
for (int i = 0; i < super.size(); i++)
{
item = this.get(i);
newCol.add(new UnderlyingReason(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder()));
}
for (int i = 0; i < newCol.size(); i++)
{
item = newCol.get(i);
if (item.getParent() != null)
{
int parentIndex = this.indexOf(item.getParent());
if(parentIndex >= 0)
item.setParent(newCol.get(parentIndex));
else
item.setParent((UnderlyingReason)item.getParent().clone());
}
}
return newCol;
}
public UnderlyingReason getInstance(int instanceId)
{
return (UnderlyingReason)super.getInstanceById(instanceId);
}
public TreeNode[] getRootNodes()
{
LookupInstVo[] roots = super.getRoots();
TreeNode[] nodes = new TreeNode[roots.length];
System.arraycopy(roots, 0, nodes, 0, roots.length);
return nodes;
}
public UnderlyingReason[] toArray()
{
UnderlyingReason[] arr = new UnderlyingReason[this.size()];
super.toArray(arr);
return arr;
}
public static UnderlyingReasonCollection buildFromBeanCollection(java.util.Collection beans)
{
UnderlyingReasonCollection coll = new UnderlyingReasonCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while(iter.hasNext())
{
coll.add(UnderlyingReason.buildLookup((ims.vo.LookupInstanceBean)iter.next()));
}
return coll;
}
public static UnderlyingReasonCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans)
{
UnderlyingReasonCollection coll = new UnderlyingReasonCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(UnderlyingReason.buildLookup(beans[x]));
}
return coll;
}
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/ValueObjects/src/ims/naes/vo/lookups/UnderlyingReasonCollection.java
|
Java
|
agpl-3.0
| 4,902
|
import SPELLS from 'common/SPELLS';
/*
* Fields:
* int: spell scales with Intellect
* crit: spell scales with (is able to or procced from) Critical Strike
* hasteHpm: spell does more healing due to Haste, e.g. HoTs that gain more ticks
* hasteHpct: spell can be cast more frequently due to Haste, basically any spell except for non haste scaling CDs
* mastery: spell is boosted by Mastery
* masteryStack: spell's HoT counts as a Mastery Stack
* vers: spell scales with Versatility
* multiplier: spell scales with whatever procs it, should be ignored for purpose of weights and for 'total healing' number
* ignored: spell should be ignored for purpose of stat weights
*/
// This only works with actual healing events; casts are not recognized.
export default {
[SPELLS.OCEANS_EMBRACE.id]: { // Sea Star of the Depthmother
int: false,
crit: true,
hasteHpct: true, // until LoD's CD is below 8 sec, this speeds up the deck cycle time
mastery: false,
vers: true,
},
[SPELLS.GUIDING_HAND.id]: { // The Deceiver's Grand Design
int: false,
crit: true,
hasteHpct: false, // static CD
hasteHpm: true,
mastery: false,
vers: true,
},
[SPELLS.HIGHFATHERS_TIMEKEEPING_HEAL.id]: { // Highfather's Machination
int: false,
crit: true,
hasteHpct: true,
hasteHpm: false,
mastery: false,
vers: true,
},
[SPELLS.LEECH.id]: { // procs a percent of all your healing, so we ignore for weights and total healing
multiplier: true,
},
[SPELLS.VELENS_FUTURE_SIGHT_HEAL.id]: { // while active procs from any healing, so we ignore for weights and total healing
multiplier: true,
},
[SPELLS.LIGHTS_EMBRACE_HEALING.id]: {
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.INFUSION_OF_LIGHT_HEALING.id]: {
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.CHAOTIC_DARKNESS_HEALING.id]: {
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.EONARS_COMPASSION_HEAL.id]: {
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.XAVARICS_MAGNUM_OPUS.id]: { // Prydaz
int: false,
crit: false,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.HEALTHSTONE.id]: {
int: false,
crit: false,
hasteHpct: false,
mastery: false,
vers: false, // not 100% sure
},
[SPELLS.MARK_OF_THE_ANCIENT_PRIESTESS.id]: {
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
//TODO: Add Shadowbind, it scales from the crit on the damage part
};
|
enragednuke/WoWAnalyzer
|
src/Parser/Core/Modules/Features/SpellInfo.js
|
JavaScript
|
agpl-3.0
| 2,709
|
/* */
var apply = require('./_apply'),
castPath = require('./_castPath'),
isKey = require('./_isKey'),
last = require('./last'),
parent = require('./_parent'),
toKey = require('./_toKey');
function baseInvoke(object, path, args) {
if (!isKey(path, object)) {
path = castPath(path);
object = parent(object, path);
path = last(path);
}
var func = object == null ? object : object[toKey(path)];
return func == null ? undefined : apply(func, object, args);
}
module.exports = baseInvoke;
|
mscottnelson/grapph
|
public/jspm_packages/npm/lodash@4.13.1/_baseInvoke.js
|
JavaScript
|
agpl-3.0
| 525
|
module DspacePlugin::CollectionHelper
include ArticleHelper
def custom_options_for_article(article,tokenized_children)
@article = article
visibility_options(article,tokenized_children) +
content_tag('div',
hidden_field_tag('article[accept_comments]', 0)
)
end
end
|
cesarfex/redesocial
|
plugins/dspace/lib/dspace_plugin/collection_helper.rb
|
Ruby
|
agpl-3.0
| 296
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import { calculateAzeriteEffects } from 'common/stats';
import { formatPercentage } from 'common/format';
import AzeritePowerStatistic from 'interface/statistics/AzeritePowerStatistic';
import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText';
import ItemHealingDone from 'interface/others/ItemHealingDone';
import Analyzer from 'parser/core/Analyzer';
import isAtonement from '../core/isAtonement';
const DEPTH_OF_THE_SHADOWS_BONUS_MS = 2000;
const EVANGELISM_BONUS_MS = 6000;
class DepthOfTheShadows extends Analyzer {
_bonusFromAtonementDuration = 0;
_bonusFromDirectHealBuff = 0;
_bonusHealingForSingleDepthStack = 0;
_lastCastIsShadowmend = false;
_shadowmends = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.DEPTH_OF_THE_SHADOWS.id);
if (!this.active) {
return;
}
this._bonusHealingForSingleDepthStack = this.selectedCombatant.traitsBySpellId[SPELLS.DEPTH_OF_THE_SHADOWS.id]
.reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.DEPTH_OF_THE_SHADOWS.id, rank)[0], 0);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if(spellId !== SPELLS.SHADOW_MEND.id && spellId !== SPELLS.EVANGELISM_TALENT.id) {
return;
}
if (spellId === SPELLS.SHADOW_MEND.id) {
this._lastCastIsShadowmend = true;
}
if (spellId === SPELLS.EVANGELISM_TALENT.id){
this._shadowmends.forEach((cast, castIndex) => {
// We search for atonements applied with shadowmend that were in their
// normal atonement window when evangelism was casted
if(event.timestamp > cast.applyBuff.timestamp
&& event.timestamp < cast.applyBuff.timestamp + SPELLS.SHADOW_MEND.atonementDuration) {
this._shadowmends[castIndex].wasExtendedByEvangelismPreDepthWindow = true;
}
// We search for atonements applied with shadowmend that were in their
// depth window when evangelism was casted
if(event.timestamp > cast.applyBuff.timestamp + SPELLS.SHADOW_MEND.atonementDuration
&& event.timestamp < cast.applyBuff.timestamp + SPELLS.SHADOW_MEND.atonementDuration + DEPTH_OF_THE_SHADOWS_BONUS_MS){
this._shadowmends[castIndex].wasExtendedByEvangelismInDepthWindow = true;
}
});
}
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if(spellId !== SPELLS.ATONEMENT_BUFF.id){
return;
}
if (this._lastCastIsShadowmend) {
this._lastCastIsShadowmend = false;
this._shadowmends.push({
"applyBuff": event,
"atonementEvents": [],
"wasExtendedByEvangelismPreDepthWindow": false,
"wasExtendedByEvangelismInDepthWindow": false,
});
}
}
// After discussing this with multiple other priests, we concluded that
// atonements that were extended by evangelism in their depth window would
// be counted for it's entire duration since you woudn't have had atonement
// on the target in the first place. This is done here by not increasing
// the lower bound if it was extended by evangelism in the depth window
calculateBonusAtonement(event) {
if(!isAtonement(event)) { return; }
this._shadowmends.forEach((cast, castIndex) => {
const lowerBound = cast.applyBuff.timestamp
+ (cast.wasExtendedByEvangelismPreDepthWindow ? EVANGELISM_BONUS_MS : 0)
+ SPELLS.SHADOW_MEND.atonementDuration;
const upperBound = cast.applyBuff.timestamp
+ (cast.wasExtendedByEvangelismPreDepthWindow || cast.wasExtendedByEvangelismInDepthWindow ? EVANGELISM_BONUS_MS : 0)
+ SPELLS.SHADOW_MEND.atonementDuration
+ DEPTH_OF_THE_SHADOWS_BONUS_MS;
if(event.targetID === cast.applyBuff.targetID && event.timestamp > lowerBound && event.timestamp < upperBound) {
this._bonusFromAtonementDuration += event.amount;
this._shadowmends[castIndex].atonementEvents.push(event);
}
});
}
on_byPlayer_heal(event) {
if (event.ability.guid === SPELLS.SHADOW_MEND.id) {
let _depthStacks = 0;
const depthBuff = this.selectedCombatant.getBuff(SPELLS.DEPTH_OF_THE_SHADOWS_BUFF.id);
if(depthBuff) { _depthStacks = depthBuff.stacks; }
const bonusHealing = _depthStacks * this._bonusHealingForSingleDepthStack;
if(!event.overheal || (event.overheal && event.overheal < bonusHealing)) {
this._bonusFromDirectHealBuff += bonusHealing - (event.overheal || 0);
}
}
this.calculateBonusAtonement(event);
}
statistic() {
const total = this._bonusFromAtonementDuration + this._bonusFromDirectHealBuff;
const totalPct = this.owner.getPercentageOfTotalHealingDone(total);
const bonusFromAtonementPct = this.owner.getPercentageOfTotalHealingDone(this._bonusFromAtonementDuration);
const bonusFromDirectHealBuffPct = this.owner.getPercentageOfTotalHealingDone(this._bonusFromDirectHealBuff);
return (
<AzeritePowerStatistic
size="small"
tooltip={(
<>
Depth of the Shadow provided <b>{formatPercentage(totalPct)}%</b> healing.
<ul>
<li><b>{formatPercentage(bonusFromAtonementPct)}%</b> from extended Atonement</li>
<li><b>{formatPercentage(bonusFromDirectHealBuffPct)}%</b> from direct shadow mend buff</li>
</ul>
</>
)}
>
<BoringSpellValueText
spell={SPELLS.DEPTH_OF_THE_SHADOWS}
>
<ItemHealingDone amount={total} />
</BoringSpellValueText>
</AzeritePowerStatistic>
);
}
}
export default DepthOfTheShadows;
|
sMteX/WoWAnalyzer
|
src/parser/priest/discipline/modules/azeritetraits/DepthOfTheShadows.js
|
JavaScript
|
agpl-3.0
| 5,815
|
{% extends 'base.html' %}
{% load static %}
{% load autodidact %}
{% block header %}
{% endblock %}
{% block main %}
<main class="fullscreen">
<article>
{% block content %}
{% endblock %}
</article>
</main>
{% endblock %}
{% block footer %}
{% endblock %}
|
JaapJoris/bps
|
autodidact/templates/fullscreen.html
|
HTML
|
agpl-3.0
| 283
|
DELETE FROM `landblock_instance` WHERE `landblock` = 0xD956;
INSERT INTO `landblock_instance` (`guid`, `weenie_Class_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)
VALUES (0x7D956000, 929, 0xD9560031, 165.923, 18.6592, 20, 0.382683, 0, 0, -0.92388, False, '2019-02-10 00:00:00'); /* Shoushi */
/* @teleloc 0xD9560031 [165.923000 18.659200 20.000000] 0.382683 0.000000 0.000000 -0.923880 */
|
LtRipley36706/ACE-World
|
Database/3-Core/6 LandBlockExtendedData/SQL/D956.sql
|
SQL
|
agpl-3.0
| 484
|
/* @flow */
/* eslint-disable no-param-reassign*/
import { bus, cache, config } from '../../core-server';
import winston from 'winston';
import { room as Room, roomrel as RoomRel } from '../../models/models';
import * as place from '../../lib/places';
import * as constants from '../../lib/Constants';
import uuid from 'node-uuid';
import * as pg from '../../lib/pg';
import type { User } from '../../lib/schemaTypes';
const placesRoles = [ constants.ROLE_WORK, constants.ROLE_HOME, constants.ROLE_HOMETOWN ];
// postgres mock, because jest is acting up.
// const pg = {
// read: (conn, sql, cb) => {
// setImmediate(() => cb(null, [
// {
// id: '5055f5b6-466e-46bc-a55d-fe020ee9ac42',
// name: 'Bangalore',
// identities: [ 'place:ChIJbU60yXAWrjsR4E9-UejD3_g' ]
// }
// ]));
// }
// };
// */
function typeStringToNumber(type) {
switch (type) {
case 'home':
return constants.ROLE_HOME;
case 'work':
return constants.ROLE_WORK;
case 'hometown':
return constants.ROLE_HOMETOWN;
}
return 0;
}
function addRooms(change, addable, all) {
const identityIdMap = {};
for (const stub of all) {
if (stub.id) {
identityIdMap[stub.identity] = stub;
continue; /* already in db */
}
}
for (const stub of addable) {
if (stub.id) {
continue; /* already in db */
}
stub.id = uuid.v4();
identityIdMap[stub.identity] = stub;
stub.parents = stub.parents.map(e => identityIdMap[e].id);
stub.parents.filter(e => e); // filter out rooms that with no parents.
change[stub.id] = new Room({
id: stub.id,
name: stub.name,
tags: [ stub.type ],
identities: [ stub.identity ],
parents: stub.parents.reverse(),
});
}
}
function addRels(change, user, resources, addable) {
for (const stub of addable) {
if (stub.exists && !stub.doUpdate) continue;
const rel = new RoomRel({
user: user.id,
item: stub.id,
roles: [ ...stub.rels, constants.ROLE_FOLLOWER ].reduce((prev, curr) => {
if (prev.indexOf(curr) < 0) prev.push(curr);
return prev;
}, []),
resources,
});
change[rel.id] = rel;
}
}
function updateRels(change, user, updateable) {
for (const stub of updateable) {
if (stub.id && stub.doUpdate) {
const rel = new RoomRel({
user: user.id,
item: stub.id,
roles: [ ...stub.rels, constants.ROLE_FOLLOWER ].reduce((prev, curr) => {
if (prev.indexOf(curr) < 0) prev.push(curr);
return prev;
}, []),
});
change[rel.id] = rel;
}
}
}
function removeRels(change, removable) {
for (const rel of removable) {
const c = new RoomRel({ roles: [], item: rel.item, user: rel.user });
change[c.id] = c;
}
}
function sendInvitations (resources, user, deletedRels, relRooms, ...stubsets) {
const stubs = {}, changedRels = {},
all = [], addable = [], removable = [], updateable = [],
change = {};
deletedRels = deletedRels.map(typeStringToNumber);
for (const stubset of stubsets) {
changedRels[stubset.rel] = true;
// console.log("Changed rels:", stubset.rel);
for (const stub of stubset.stubs) {
stub.rels = [ stubset.rel ];
if (!stubs[stub.identity]) {
stubs[stub.identity] = stub;
} else {
stubs[stub.identity].rels.push(stubset.rel);
}
}
}
for (const relRoom of relRooms) {
if (!relRoom.room || !relRoom.room.identities) continue;
const identity = relRoom.room.identities.filter(
ident => ident.substr(0, 6) === 'place:'
)[0];
if (stubs[identity]) {
stubs[identity].exists = true;
stubs[identity].rels = stubs[identity].rels.concat(relRoom.roomrel.roles);
if (stubs[identity].rels.length !== relRoom.roomrel.roles) {
stubs[identity].doUpdate = true;
updateable.push(stubs[identity]);
}
} else {
const types = relRoom.roomrel.roles.filter(role =>
role >= constants.ROLE_HOME &&
role <= constants.ROLE_HOMETOWN &&
deletedRels.indexOf(role) > -1
);
if (types.length === 0) continue;
const type = types[0];
if (changedRels[type] || deletedRels.indexOf(type) >= 0) {
let shouldRemove = true;
for (const role of placesRoles.filter(e => e !== type)) {
if (relRoom.roomrel.roles.indexOf(role) >= 0) {
shouldRemove = false;
break;
}
}
if (shouldRemove) {
removable.push(relRoom.roomrel);
} else {
relRoom.roomrel.roles.splice(relRoom.roomrel.roles.indexOf(type), 1);
const newStub = {
identity,
rels: relRoom.roomrel.roles,
doUpdate: true,
};
updateable.push(newStub);
stubs[identity] = newStub;
}
} else {
all.push({ identity, type, name: relRoom.room.name });
}
}
}
for (const identity in stubs) {
const stub = stubs[identity];
all.push(stub);
if (!stub.exists) { addable.push(stub); }
}
pg.read(config.connStr, {
$: 'SELECT * FROM "rooms" WHERE identities && &{idents}',
idents: all.map(a => a.identity),
}, (err, rooms) => {
if (err) { winston.error(err); return; }
for (let room of rooms) {
room = new Room(room);
const stub = stubs[room.identities.filter(
ident => ident.substr(0, 6) === 'place:'
)[0]];
if (stub) stub.id = room.id;
}
addRooms(change, addable, all);
addRels(change, user, resources, addable);
updateRels(change, user, updateable);
removeRels(change, removable);
let time = Date.now();
// fix times
for (const key in change.entities) {
change.entities[key].createtime = change.entities[key].updatetime = time++;
}
bus.emit('change', { entities: change, source: 'belong' });
});
}
bus.on('change', change => {
/* While the work of this module is asynchronous, it will allow
the change to continue immediately and emit a new change when the
work is complete. */
if (change.entities) {
for (const id in change.entities) {
const user:User = change.entities[id],
deletedRels = [],
promises = [];
if (
user.type !== constants.TYPE_USER ||
!user.params || !user.params.places
) { continue; }
winston.info('User update: ', user);
if (user.params && user.params.places) {
const { home, work, hometown } = user.params.places;
if (home && home.id) {
promises.push(place.getStubset(home.id, constants.ROLE_HOME));
}
if (work && work.id) {
promises.push(place.getStubset(work.id, constants.ROLE_WORK));
}
if (hometown && hometown.id) {
promises.push(place.getStubset(hometown.id, constants.ROLE_HOMETOWN));
}
for (const rel in user.params.places) {
if (user.params.places[rel] === null) {
deletedRels.push(rel);
}
}
} else {
return;
}
/* Fetch the current rooms of this user. */
const currentRels = new Promise((resolve, reject) => {
cache.query({
type: 'roomrel',
link: { room: 'item' },
filter: {
roomrel: {
user: id,
roles_cts: [ constants.ROLE_FOLLOWER ]
}
},
order: 'createTime',
}, [ -Infinity, Infinity ], (err, results) => {
if (err) { reject(err); return; }
resolve(results);
});
});
const resource = change && change.auth && change.auth.resource;
Promise.all([ currentRels, ...promises ])
.then((res) => sendInvitations({
[resource]: constants.PRESENCE_FOREGROUND,
}, user, deletedRels, ...res))
.catch(err => winston.error(err));
}
}
});
|
scrollback/pure
|
src/modules/belong/belong.js
|
JavaScript
|
agpl-3.0
| 7,295
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "harness.h"
#undef VOLT_LOG_LEVEL
#define VOLT_LOG_LEVEL 200 //test DEBUG level
#include "common/debuglog.h"
using namespace std;
class DebugLogTest : public Test {
public:
DebugLogTest() {};
};
TEST_F(DebugLogTest, SimpleTest) {
VOLT_DEBUG("debug message");
VOLT_INFO("debug message2");
VOLT_TRACE("debug message3");
}
TEST_F(DebugLogTest, ParamTest) {
VOLT_DEBUG("debug value %d", 123);
VOLT_INFO("debug value2 %s", "hogehoge");
VOLT_ERROR("debug value3 %ld", -471L);
VOLT_WARN("debug value4 %d", 0);
}
TEST_F(DebugLogTest, MultiParamTest) {
VOLT_DEBUG("debug value %d, %s, %ld", 123, "hoho", 10L);
}
TEST_F(DebugLogTest, EnabledTest) {
#ifdef VOLT_DEBUG_ENABLED
VOLT_ERROR("this should be displayed");
#endif
#ifdef VOLT_TRACE_ENABLED
VOLT_ERROR("this should NOT be displayed");
#endif
}
int main() {
return TestSuite::globalInstance()->runAll();
}
|
migue/voltdb
|
tests/ee/common/debuglog_test.cpp
|
C++
|
agpl-3.0
| 3,404
|
<?php
/*
* This file is part of FacturaSctipts
* Copyright (C) 2015-2016 Carlos Garcia Gomez neorazorx@gmail.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/>.
*/
/**
* Description of sql_editor
*
* @author carlos
*/
class sql_editor extends fs_controller
{
/**
*
* @var array
*/
public $resultados;
/**
*
* @var string
*/
public $sentencia;
public function __construct()
{
parent::__construct(__CLASS__, 'SQL Editor', 'admin');
}
public function columnas_resultado()
{
return empty($this->resultados) ? [] : array_keys($this->resultados[0]);
}
/**
*
* @param string $sql
*/
protected function ejecutar($sql)
{
if (substr(strtolower($sql), 0, 6) == 'select') {
$this->resultados = $this->db->select($sql);
$this->new_message('Secuencia ejecutada.');
} else if (substr(strtolower($sql), 0, 4) == 'show') {
$this->resultados = $this->db->select($sql);
$this->new_message('Secuencia ejecutada.');
} else if (substr(strtolower($sql), 0, 8) == 'describe') {
$this->resultados = $this->db->select($sql);
$this->new_message('Secuencia ejecutada.');
} elseif ($this->db->exec($sql)) {
$this->new_message('Secuencia ejecutada correctamente.');
} else {
$this->new_error_msg('Error al ejercutar la secuencia.');
}
}
protected function private_core()
{
$this->resultados = [];
$this->sentencia = isset($_POST['sql']) ? $_POST['sql'] : '';
if (empty($this->sentencia)) {
return;
}
if (!$this->user->admin) {
$this->new_error_msg('Solamente un administrador puede usar esta página.');
return;
}
$this->ejecutar($this->sentencia);
}
}
|
FacturaScripts/sql_editor
|
controller/sql_editor.php
|
PHP
|
agpl-3.0
| 2,540
|
/**
* This file is part of mycollab-services.
*
* mycollab-services 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.
*
* mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>.
*/
package com.esofthead.mycollab.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
/**
*
* @author MyCollab Ltd.
* @since 4.6.0
*
*/
@Configuration
public class ValidatorConfiguration {
@Bean()
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setMappingLocations(new ClassPathResource("validator/crm-constraints.xml"),
new ClassPathResource("validator/user-constraints.xml"),
new ClassPathResource("validator/project-constraints.xml"),
new ClassPathResource("validator/tracker-constraints.xml"));
return bean;
}
}
|
maduhu/mycollab
|
mycollab-services/src/main/java/com/esofthead/mycollab/spring/ValidatorConfiguration.java
|
Java
|
agpl-3.0
| 1,576
|
<app-instance-page>
<app-instance-toolbar [hasDetailPane]="true">
Alarms
<app-help>
An alarm can be in these states:
<table class="ya-data-table">
<tr>
<td width="1">
<mat-icon class="icon16" style="vertical-align: middle">notifications</mat-icon>
</td>
<td>
The alarm is unacknowledged and the cause of the alarm still exists.
</td>
</tr>
<tr>
<td>
<mat-icon class="icon16" style="vertical-align: middle">notifications_none</mat-icon>
</td>
<td>
The alarm is unacknowledged and the cause that generated the alarm no longer exists.
</td>
</tr>
<tr>
<td>
<mat-icon class="icon16" style="vertical-align: middle">check_circle</mat-icon>
</td>
<td>
The alarm is acknowledged and the cause of the alarm still exists.
</td>
</tr>
<tr>
<td>
<mat-icon class="icon16" style="vertical-align: middle">check_circle_outline</mat-icon>
</td>
<td>
The alarm is acknowledged and the cause that generated the alarm no longer exists.
</td>
</tr>
<tr>
<td>
<mat-icon class="icon16" style="vertical-align: middle">timer</mat-icon>
</td>
<td>
The alarm was shelved.
</td>
</tr>
</table>
</app-help>
<button mat-button
color="primary"
(click)="acknowledgeAlarms(selection.selected)"
[disabled]="!selection.hasValue()"
*ngIf="mayControlAlarms()">
<mat-icon>notifications_off</mat-icon>
ACKNOWLEDGE
</button>
<button mat-button
color="primary"
(click)="shelveAlarms(selection.selected)"
[disabled]="!selection.hasValue()"
*ngIf="mayControlAlarms()">
<mat-icon>timer</mat-icon>
SHELVE
</button>
</app-instance-toolbar>
<app-detail-pane>
<ng-container *ngIf="detailAlarm$ | async as detailAlarm; else noDetail">
<app-detail-toolbar>
Alarm Detail
</app-detail-toolbar>
<div style="padding: 0 16px">
<app-alarm-detail [alarm]="detailAlarm"
[mayControl]="mayControlAlarms()"
(acknowledgeAlarm)="acknowledgeAlarms([$event])"
(shelveAlarm)="shelveAlarms([$event])"
(unshelveAlarm)="unshelveAlarms([$event])"
(clearAlarm)="clearAlarms([$event])">
</app-alarm-detail>
</div>
</ng-container>
<ng-template #noDetail>
<app-detail-toolbar>
Select an alarm
</app-detail-toolbar>
</ng-template>
</app-detail-pane>
<div class="table-wrapper">
<div class="panel-content" *ngIf="dataSource">
<app-alarms-page-tabs></app-alarms-page-tabs>
<dl class="dl-horizontal">
<dt>Unacknowledged alarms:</dt>
<dd>
<strong>{{ (dataSource.unacknowledgedAlarms$ | async)?.length }}</strong>
</dd>
<dt>Acknowledged alarms:</dt>
<dd>
<strong>{{ (dataSource.acknowledgedAlarms$ | async)?.length }}</strong>
</dd>
<dt>Shelved alarms:</dt>
<dd>
<strong>{{ (dataSource.shelvedAlarms$ | async)?.length }}</strong>
</dd>
</dl>
<form [formGroup]="filterForm">
<div class="filter-bar">
<app-search-filter formControlName="filter"
placeholder="Filter by text search">
</app-search-filter>
<app-select [options]="viewOptions" formControlName="view"></app-select>
</div>
</form>
<app-alarms-table [dataSource]="dataSource"
[selection]="selection"
[view]="view$ | async"
[mayControl]="mayControlAlarms()"
(acknowledgeAlarm)="acknowledgeAlarms([$event])"
(shelveAlarm)="shelveAlarms([$event])"
(unshelveAlarm)="unshelveAlarms([$event])"
(clearAlarm)="clearAlarms([$event])">
</app-alarms-table>
</div>
</div>
</app-instance-page>
|
fqqb/yamcs
|
yamcs-web/src/main/webapp/src/app/alarms/AlarmsPage.html
|
HTML
|
agpl-3.0
| 4,370
|
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# License: GNU General Public License v3. See license.txt
import webnotes
def execute():
webnotes.conn.sql("""drop table if exists `tabDocType Mapper`""")
webnotes.conn.sql("""drop table if exists `tabTable Mapper Detail`""")
webnotes.conn.sql("""drop table if exists `tabField Mapper Detail`""")
webnotes.delete_doc("DocType", "DocType Mapper")
webnotes.delete_doc("DocType", "Table Mapper Detail")
webnotes.delete_doc("DocType", "Field Mapper Detail")
|
gangadhar-kadam/sapphire_app
|
patches/july_2013/p01_remove_doctype_mappers.py
|
Python
|
agpl-3.0
| 516
|
//#############################################################################
//# #
//# 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.clinicaladmin.vo.beans;
public class PatientTumourRecurrenceVoBean extends ims.vo.ValueObjectBean
{
public PatientTumourRecurrenceVoBean()
{
}
public PatientTumourRecurrenceVoBean(ims.clinicaladmin.vo.PatientTumourRecurrenceVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.recurrencedate = vo.getRecurrenceDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRecurrenceDate().getBean();
this.recurrencesite = vo.getRecurrenceSite() == null ? null : (ims.vo.LookupInstanceBean)vo.getRecurrenceSite().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.clinicaladmin.vo.PatientTumourRecurrenceVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.recurrencedate = vo.getRecurrenceDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRecurrenceDate().getBean();
this.recurrencesite = vo.getRecurrenceSite() == null ? null : (ims.vo.LookupInstanceBean)vo.getRecurrenceSite().getBean();
}
public ims.clinicaladmin.vo.PatientTumourRecurrenceVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.clinicaladmin.vo.PatientTumourRecurrenceVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.clinicaladmin.vo.PatientTumourRecurrenceVo vo = null;
if(map != null)
vo = (ims.clinicaladmin.vo.PatientTumourRecurrenceVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.clinicaladmin.vo.PatientTumourRecurrenceVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.framework.utils.beans.DateBean getRecurrenceDate()
{
return this.recurrencedate;
}
public void setRecurrenceDate(ims.framework.utils.beans.DateBean value)
{
this.recurrencedate = value;
}
public ims.vo.LookupInstanceBean getRecurrenceSite()
{
return this.recurrencesite;
}
public void setRecurrenceSite(ims.vo.LookupInstanceBean value)
{
this.recurrencesite = value;
}
private Integer id;
private int version;
private ims.framework.utils.beans.DateBean recurrencedate;
private ims.vo.LookupInstanceBean recurrencesite;
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/ValueObjects/src/ims/clinicaladmin/vo/beans/PatientTumourRecurrenceVoBean.java
|
Java
|
agpl-3.0
| 4,115
|
/*
* RapidMiner
*
* Copyright (C) 2001-2013 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.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/.
*/
package com.rapidminer.datatable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.rapidminer.ObjectVisualizer;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.AttributeRole;
import com.rapidminer.example.AttributeWeights;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.Tools;
import com.rapidminer.example.set.SplittedExampleSet;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.example.table.DoubleArrayDataRow;
import com.rapidminer.example.table.MemoryExampleTable;
import com.rapidminer.gui.RapidMinerGUI;
import com.rapidminer.operator.UserError;
import com.rapidminer.tools.ObjectVisualizerService;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.ParameterService;
/**
* This class can be used to use an example set as data table. The data is directly
* read from the example set instead of building a copy. Please note that the method
* for adding new rows is not supported by this type of data tables.
*
* @author Ingo Mierswa
*/
public class DataTableExampleSetAdapter extends AbstractDataTable {
private static final int DEFAULT_MAX_SIZE_FOR_SHUFFLED_SAMPLING = 100000;
private ExampleSet exampleSet;
private List<Attribute> allAttributes = new ArrayList<Attribute>();
private int numberOfRegularAttributes = 0;
private AttributeWeights weights = null;
private Attribute idAttribute;
public DataTableExampleSetAdapter(ExampleSet exampleSet, AttributeWeights weights) {
this(exampleSet, weights, true);
}
/**
* @param ignoreId If this variable is true, the id will not be visible in the data table.
*/
public DataTableExampleSetAdapter(ExampleSet exampleSet, AttributeWeights weights, boolean ignoreId) {
super("Data Table");
this.exampleSet = exampleSet;
this.weights = weights;
for (Attribute attribute : exampleSet.getAttributes()) {
allAttributes.add(attribute);
}
this.idAttribute = exampleSet.getAttributes().getId();
Iterator<AttributeRole> s = exampleSet.getAttributes().specialAttributes();
while (s.hasNext()) {
Attribute specialAttribute = s.next().getAttribute();
if (!ignoreId || idAttribute == null || !idAttribute.getName().equals(specialAttribute.getName())) {
allAttributes.add(specialAttribute);
}
}
this.numberOfRegularAttributes = exampleSet.getAttributes().size();
// TODO: Find another solution for this hack
registerVisualizerForMe(exampleSet);
}
public DataTableExampleSetAdapter(DataTableExampleSetAdapter dataTableExampleSetAdapter) {
super(dataTableExampleSetAdapter.getName());
this.exampleSet = dataTableExampleSetAdapter.exampleSet; // shallow clone
this.allAttributes = dataTableExampleSetAdapter.allAttributes; // shallow clone
this.numberOfRegularAttributes = dataTableExampleSetAdapter.numberOfRegularAttributes;
this.weights = dataTableExampleSetAdapter.weights; // shallow clone
this.idAttribute = dataTableExampleSetAdapter.idAttribute; // shallow clone
// TODO: Find another solution for this hack
registerVisualizerForMe(dataTableExampleSetAdapter);
}
@Override
public int getNumberOfSpecialColumns() {
return allAttributes.size() - numberOfRegularAttributes;
}
@Override
public boolean isSpecial(int index) {
return index >= numberOfRegularAttributes;
}
@Override
public boolean isNominal(int index) {
return Ontology.ATTRIBUTE_VALUE_TYPE.isA(allAttributes.get(index).getValueType(), Ontology.NOMINAL);
}
@Override
public boolean isDate(int index) {
return Ontology.ATTRIBUTE_VALUE_TYPE.isA(allAttributes.get(index).getValueType(), Ontology.DATE);
}
@Override
public boolean isTime(int index) {
return Ontology.ATTRIBUTE_VALUE_TYPE.isA(allAttributes.get(index).getValueType(), Ontology.TIME);
}
@Override
public boolean isDateTime(int index) {
return Ontology.ATTRIBUTE_VALUE_TYPE.isA(allAttributes.get(index).getValueType(), Ontology.DATE_TIME);
}
@Override
public boolean isNumerical(int index) {
return Ontology.ATTRIBUTE_VALUE_TYPE.isA(allAttributes.get(index).getValueType(), Ontology.NUMERICAL);
}
@Override
public String mapIndex(int column, int value) {
return allAttributes.get(column).getMapping().mapIndex(value);
}
@Override
public int mapString(int column, String value) {
return allAttributes.get(column).getMapping().mapString(value);
}
@Override
public int getNumberOfValues(int column) {
return allAttributes.get(column).getMapping().size();
}
@Override
public String getColumnName(int i) {
return allAttributes.get(i).getName();
}
@Override
public int getColumnIndex(String name) {
for (int i = 0; i < allAttributes.size(); i++)
if (allAttributes.get(i).getName().equals(name))
return i;
return -1;
}
@Override
public boolean isSupportingColumnWeights() {
return weights != null;
}
@Override
public double getColumnWeight(int column) {
if (weights == null)
return Double.NaN;
else
return weights.getWeight(getColumnName(column));
}
@Override
public int getNumberOfColumns() {
return this.allAttributes.size();
}
@Override
public void add(DataTableRow row) {
throw new RuntimeException("DataTableExampleSetAdapter: adding new rows is not supported!");
}
@Override
public DataTableRow getRow(int index) {
return new Example2DataTableRowWrapper(exampleSet.getExample(index), allAttributes, idAttribute);
}
@Override
public Iterator<DataTableRow> iterator() {
return new Example2DataTableRowIterator(exampleSet.iterator(), allAttributes, idAttribute);
}
@Override
public int getNumberOfRows() {
return this.exampleSet.size();
}
@Override
public DataTable sample(int newSize) {
DataTableExampleSetAdapter result = new DataTableExampleSetAdapter(this);
double ratio = (double)newSize / (double)getNumberOfRows();
int maxNumberBeforeSampling = DEFAULT_MAX_SIZE_FOR_SHUFFLED_SAMPLING;
String maxString = ParameterService.getParameterValue(RapidMinerGUI.PROPERTY_RAPIDMINER_GUI_MAX_STATISTICS_ROWS);
if (maxString != null) {
try {
maxNumberBeforeSampling = Integer.parseInt(maxString);
} catch (NumberFormatException e) {
// do nothing
}
}
ExampleSet exampleSet = null;
if (getNumberOfRows() < maxNumberBeforeSampling) {
try {
exampleSet = new SplittedExampleSet(this.exampleSet, ratio, SplittedExampleSet.SHUFFLED_SAMPLING, false, 0);
} catch (UserError e) {
// this exception is only thrown for Stratified Sampling
}
if(exampleSet == null) {
return null; // cannot happen
}
((SplittedExampleSet)exampleSet).selectSingleSubset(0);
} else {
exampleSet = Tools.getLinearSubsetCopy(this.exampleSet, newSize, 0);
}
result.exampleSet = exampleSet;
return result;
}
public static ExampleSet createExampleSetFromDataTable(DataTable table) {
List<Attribute> attributes = new ArrayList<Attribute>();
for (int i = 0; i < table.getNumberOfColumns(); i++) {
if (table.isDate(i)) {
Attribute attribute = AttributeFactory.createAttribute(table.getColumnName(i), Ontology.DATE);
attributes.add(attribute);
} else if (table.isTime(i)) {
Attribute attribute = AttributeFactory.createAttribute(table.getColumnName(i), Ontology.TIME);
attributes.add(attribute);
} else if (table.isDateTime(i)) {
Attribute attribute = AttributeFactory.createAttribute(table.getColumnName(i), Ontology.DATE_TIME);
attributes.add(attribute);
} else if (table.isNominal(i)) {
Attribute attribute = AttributeFactory.createAttribute(table.getColumnName(i), Ontology.NOMINAL);
attributes.add(attribute);
} else {
Attribute attribute = AttributeFactory.createAttribute(table.getColumnName(i), Ontology.REAL);
attributes.add(attribute);
}
}
MemoryExampleTable exampleTable = new MemoryExampleTable(attributes);
for (int i = 0; i < table.getNumberOfRows(); i++) {
DataTableRow row = table.getRow(i);
double[] values = new double[attributes.size()];
for (int a = 0; a < values.length; a++) {
Attribute attribute = attributes.get(a);
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.DATE_TIME)) {
values[a] = row.getValue(a);
} else if (attribute.isNominal()) {
values[a] = attribute.getMapping().mapString(table.getValueAsString(row, a));
} else {
values[a] = row.getValue(a);
}
}
exampleTable.addDataRow(new DoubleArrayDataRow(values));
}
return exampleTable.createExampleSet();
}
private void registerVisualizerForMe(Object father) {
ObjectVisualizer visualizer = ObjectVisualizerService.getVisualizerForObject(father);
ObjectVisualizerService.addObjectVisualizer(this, visualizer);
}
}
|
aborg0/RapidMiner-Unuk
|
src/com/rapidminer/datatable/DataTableExampleSetAdapter.java
|
Java
|
agpl-3.0
| 10,747
|
/*
* Advanced Simulation Library <http://asl.org.il>
*
* Copyright 2015 Avtech Scientific <http://avtechscientific.com>
*
*
* This file is part of Advanced Simulation Library (ASL).
*
* ASL is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* ASL 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 ASL. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ACLELEMENTCONVERT_H
#define ACLELEMENTCONVERT_H
#include "../Operators/aclOperatorUnary.h"
namespace acl
{
///realizes \p convert_ functionality
/**
\ingroup SpecialPurposeFunctions
The element generates code corresponding to convert function with
an apropriate vector index.
The \p strong parameter defines the form of the operator:
convert_ in case of \p true or (type) in case of false
*/
class ElementConvert: public OperatorUnary
{
private:
bool strongForm;
public:
ElementConvert(Element a, TypeID type, bool strong=true);
virtual string str(const KernelConfiguration & kernelConfig) const;
};
} // namespace acl
#endif // ACLELEMENTCONVERT_H
|
ghisvail/ASL
|
src/acl/Operators/aclElementConvert.h
|
C
|
agpl-3.0
| 1,488
|
from .base_executor import ScriptExecutor
from judgeenv import env
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
fs = ['.*\.(?:so|rb$)', '/etc/localtime$', '/dev/urandom$', '/proc/self', '/usr/lib/ruby/gems/']
test_program = 'puts gets'
@classmethod
def get_command(cls):
return env['runtime'].get(cls.name.lower())
|
buhe/judge
|
executors/ruby.py
|
Python
|
agpl-3.0
| 393
|
<?php
/**
* @author Olivier Paroz <owncloud@interfasys.ch>
*
* @copyright Copyright (c) 2018, ownCloud GmbH
* @license AGPL-3.0
*
* This code 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.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace Test\Preview;
/**
* Class ImageTest
*
* @group DB
*
* @package Test\Preview
*/
class ImageTest extends Provider {
public function setUp() {
parent::setUp();
$fileName = 'testimage.jpg';
$this->imgPath = $this->prepareTestFile($fileName, \OC::$SERVERROOT . '/tests/data/' . $fileName);
$this->width = 1680;
$this->height = 1050;
$this->provider = new \OC\Preview\JPEG();
}
}
|
pollopolea/core
|
tests/lib/Preview/ImageTest.php
|
PHP
|
agpl-3.0
| 1,162
|
# coding: utf-8
require File.dirname(__FILE__) + '/test_helper'
describe 'SemanticFormBuilder#input' do
include FormtasticSpecHelper
before do
@output_buffer = ''
mock_everything
end
describe 'with inline order customization' do
it 'should allow input, hints, errors as order' do
Formtastic::SemanticFormBuilder.inline_order = [:input, :hints, :errors]
semantic_form_for(@new_post) do |builder|
builder.should_receive(:inline_input_for).once.ordered
builder.should_receive(:inline_hints_for).once.ordered
builder.should_receive(:inline_errors_for).once.ordered
concat(builder.input(:title))
end
end
it 'should allow hints, input, errors as order' do
Formtastic::SemanticFormBuilder.inline_order = [:hints, :input, :errors]
semantic_form_for(@new_post) do |builder|
builder.should_receive(:inline_hints_for).once.ordered
builder.should_receive(:inline_input_for).once.ordered
builder.should_receive(:inline_errors_for).once.ordered
concat(builder.input(:title))
end
end
end
describe 'arguments and options' do
it 'should require the first argument (the method on form\'s object)' do
lambda {
semantic_form_for(@new_post) do |builder|
concat(builder.input()) # no args passed in at all
end
}.should raise_error(ArgumentError)
end
describe ':required option' do
describe 'when true' do
before do
@string = Formtastic::SemanticFormBuilder.required_string = " required yo!" # ensure there's something in the string
@new_post.class.should_not_receive(:reflect_on_all_validations)
end
after do
Formtastic::SemanticFormBuilder.required_string = %{<abbr title="required">*</abbr>}
end
it 'should set a "required" class' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => true))
end
output_buffer.should_not have_tag('form li.optional')
output_buffer.should have_tag('form li.required')
end
it 'should append the "required" string to the label' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => true))
end
output_buffer.should have_tag('form li.required label', /#{@string}$/)
end
end
describe 'when false' do
before do
@string = Formtastic::SemanticFormBuilder.optional_string = " optional yo!" # ensure there's something in the string
@new_post.class.should_not_receive(:reflect_on_all_validations)
end
after do
Formtastic::SemanticFormBuilder.optional_string = ''
end
it 'should set an "optional" class' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => false))
end
output_buffer.should_not have_tag('form li.required')
output_buffer.should have_tag('form li.optional')
end
it 'should append the "optional" string to the label' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :required => false))
end
output_buffer.should have_tag('form li.optional label', /#{@string}$/)
end
end
describe 'when not provided' do
describe 'and an object was not given' do
it 'should use the default value' do
Formtastic::SemanticFormBuilder.all_fields_required_by_default.should == true
Formtastic::SemanticFormBuilder.all_fields_required_by_default = false
semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title))
end
output_buffer.should_not have_tag('form li.required')
output_buffer.should have_tag('form li.optional')
Formtastic::SemanticFormBuilder.all_fields_required_by_default = true
end
end
describe 'and an object was given' do
describe 'and the validation reflection plugin is available' do
before do
@new_post.class.stub!(:method_defined?).with(:reflect_on_validations_for).and_return(true)
end
describe 'and validates_presence_of was called for the method' do
it 'should be required' do
@new_post.class.should_receive(:reflect_on_validations_for).with(:title).and_return([
mock('MacroReflection', :macro => :validates_presence_of, :name => :title, :options => nil)
])
@new_post.class.should_receive(:reflect_on_validations_for).with(:body).and_return([
mock('MacroReflection', :macro => :validates_presence_of, :name => :body, :options => {:if => true})
])
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
concat(builder.input(:body))
end
output_buffer.should have_tag('form li.required')
output_buffer.should_not have_tag('form li.optional')
end
it 'should be not be required if the optional :if condition is not satisifed' do
should_be_required(:required => false, :options => { :if => false })
end
it 'should not be required if the optional :if proc evaluates to false' do
should_be_required(:required => false, :options => { :if => proc { |record| false } })
end
it 'should be required if the optional :if proc evaluates to true' do
should_be_required(:required => true, :options => { :if => proc { |record| true } })
end
it 'should not be required if the optional :unless proc evaluates to true' do
should_be_required(:required => false, :options => { :unless => proc { |record| true } })
end
it 'should be required if the optional :unless proc evaluates to false' do
should_be_required(:required => true, :options => { :unless => proc { |record| false } })
end
it 'should be required if the optional :if with a method string evaluates to true' do
@new_post.should_receive(:required_condition).and_return(true)
should_be_required(:required => true, :options => { :if => :required_condition })
end
it 'should be required if the optional :if with a method string evaluates to false' do
@new_post.should_receive(:required_condition).and_return(false)
should_be_required(:required => false, :options => { :if => :required_condition })
end
it 'should not be required if the optional :unless with a method string evaluates to false' do
@new_post.should_receive(:required_condition).and_return(false)
should_be_required(:required => true, :options => { :unless => :required_condition })
end
it 'should be required if the optional :unless with a method string evaluates to true' do
@new_post.should_receive(:required_condition).and_return(true)
should_be_required(:required => false, :options => { :unless => :required_condition })
end
end
# TODO make a matcher for this?
def should_be_required(options)
@new_post.class.should_receive(:reflect_on_validations_for).with(:body).and_return([
mock('MacroReflection', :macro => :validates_presence_of, :name => :body, :options => options[:options])
])
semantic_form_for(@new_post) do |builder|
concat(builder.input(:body))
end
if options[:required]
output_buffer.should_not have_tag('form li.optional')
output_buffer.should have_tag('form li.required')
else
output_buffer.should have_tag('form li.optional')
output_buffer.should_not have_tag('form li.required')
end
end
describe 'and validates_presence_of was not called for the method' do
before do
@new_post.class.should_receive(:reflect_on_validations_for).with(:title).and_return([])
end
it 'should not be required' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should_not have_tag('form li.required')
output_buffer.should have_tag('form li.optional')
end
end
end
describe 'and the validation reflection plugin is not available' do
it 'should use the default value' do
Formtastic::SemanticFormBuilder.all_fields_required_by_default.should == true
Formtastic::SemanticFormBuilder.all_fields_required_by_default = false
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should_not have_tag('form li.required')
output_buffer.should have_tag('form li.optional')
Formtastic::SemanticFormBuilder.all_fields_required_by_default = true
end
end
end
end
end
describe ':as option' do
describe 'when not provided' do
it 'should default to a string for forms without objects unless column is password' do
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:anything))
end
output_buffer.should have_tag('form li.string')
end
it 'should default to password for forms without objects if column is password' do
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:password))
concat(builder.input(:password_confirmation))
concat(builder.input(:confirm_password))
end
output_buffer.should have_tag('form li.password', :count => 3)
end
it 'should default to a string for methods on objects that don\'t respond to "column_for_attribute"' do
@new_post.stub!(:method_without_a_database_column)
@new_post.stub!(:column_for_attribute).and_return(nil)
default_input_type(nil, :method_without_a_database_column).should == :string
end
it 'should default to :password for methods that don\'t have a column in the database but "password" is in the method name' do
@new_post.stub!(:password_method_without_a_database_column)
@new_post.stub!(:column_for_attribute).and_return(nil)
default_input_type(nil, :password_method_without_a_database_column).should == :password
end
it 'should default to :password for methods on objects that don\'t respond to "column_for_attribute" but "password" is in the method name' do
@new_post.stub!(:password_method_without_a_database_column)
@new_post.stub!(:column_for_attribute).and_return(nil)
default_input_type(nil, :password_method_without_a_database_column).should == :password
end
it 'should default to :select for column names ending in "_id"' do
default_input_type(:integer, :user_id).should == :select
default_input_type(:integer, :section_id).should == :select
end
it 'should default to :password for :string column types with "password" in the method name' do
default_input_type(:string, :password).should == :password
default_input_type(:string, :hashed_password).should == :password
default_input_type(:string, :password_hash).should == :password
end
it 'should default to :text for :text column types' do
default_input_type(:text).should == :text
end
it 'should default to :date for :date column types' do
default_input_type(:date).should == :date
end
it 'should default to :datetime for :datetime and :timestamp column types' do
default_input_type(:datetime).should == :datetime
default_input_type(:timestamp).should == :datetime
end
it 'should default to :time for :time column types' do
default_input_type(:time).should == :time
end
it 'should default to :boolean for :boolean column types' do
default_input_type(:boolean).should == :boolean
end
it 'should default to :string for :string column types' do
default_input_type(:string).should == :string
end
it 'should default to :numeric for :integer, :float and :decimal column types' do
default_input_type(:integer).should == :numeric
default_input_type(:float).should == :numeric
default_input_type(:decimal).should == :numeric
end
it 'should default to :country for :string columns named country' do
default_input_type(:string, :country).should == :country
end
describe 'defaulting to file column' do
Formtastic::SemanticFormBuilder.file_methods.each do |method|
it "should default to :file for attributes that respond to ##{method}" do
@new_post.stub!(:column_for_attribute).and_return(nil)
column = mock('column')
Formtastic::SemanticFormBuilder.file_methods.each do |test|
column.stub!(:respond_to?).with(test).and_return(method == test)
end
@new_post.should_receive(method).and_return(column)
semantic_form_for(@new_post) do |builder|
builder.send(:default_input_type, method).should == :file
end
end
end
end
end
it 'should call the corresponding input method' do
[:select, :time_zone, :radio, :date, :datetime, :time, :boolean, :check_boxes, :hidden].each do |input_style|
@new_post.stub!(:generic_column_name)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255))
semantic_form_for(@new_post) do |builder|
builder.should_receive(:"#{input_style}_input").once.and_return("fake HTML output from #input")
concat(builder.input(:generic_column_name, :as => input_style))
end
end
Formtastic::SemanticFormBuilder::INPUT_MAPPINGS.keys.each do |input_style|
@new_post.stub!(:generic_column_name)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255))
semantic_form_for(@new_post) do |builder|
builder.should_receive(:input_simple).once.and_return("fake HTML output from #input")
concat(builder.input(:generic_column_name, :as => input_style))
end
end
end
end
describe ':label option' do
describe 'when provided' do
it 'should be passed down to the label tag' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => "Kustom"))
end
output_buffer.should have_tag("form li label", /Kustom/)
end
it 'should not generate a label if false' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => false))
end
output_buffer.should_not have_tag("form li label")
end
it 'should be dupped if frozen' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => "Kustom".freeze))
end
output_buffer.should have_tag("form li label", /Kustom/)
end
end
describe 'when not provided' do
describe 'when localized label is NOT provided' do
describe 'and object is not given' do
it 'should default the humanized method name, passing it down to the label tag' do
Formtastic::SemanticFormBuilder.label_str_method = :humanize
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:meta_description))
end
output_buffer.should have_tag("form li label", /#{'meta_description'.humanize}/)
end
end
describe 'and object is given' do
it 'should delegate the label logic to class human attribute name and pass it down to the label tag' do
@new_post.stub!(:meta_description) # a two word method name
@new_post.class.should_receive(:human_attribute_name).with('meta_description').and_return('meta_description'.humanize)
semantic_form_for(@new_post) do |builder|
concat(builder.input(:meta_description))
end
output_buffer.should have_tag("form li label", /#{'meta_description'.humanize}/)
end
end
end
describe 'when localized label is provided' do
before do
@localized_label_text = 'Localized title'
@default_localized_label_text = 'Default localized title'
::I18n.backend.store_translations :en,
:formtastic => {
:labels => {
:title => @default_localized_label_text,
:published => @default_localized_label_text,
:post => {
:title => @localized_label_text,
:published => @default_localized_label_text
}
}
}
::Formtastic::SemanticFormBuilder.i18n_lookups_by_default = false
end
it 'should render a label with localized label (I18n)' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => true))
concat(builder.input(:published, :as => :boolean, :label => true))
end
output_buffer.should have_tag('form li label', @localized_label_text)
end
it 'should render a hint paragraph containing an optional localized label (I18n) if first is not set' do
::I18n.backend.store_translations :en,
:formtastic => {
:labels => {
:post => {
:title => nil,
:published => nil
}
}
}
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :label => true))
concat(builder.input(:published, :as => :boolean, :label => true))
end
output_buffer.should have_tag('form li label', @default_localized_label_text)
end
end
end
end
describe ':hint option' do
describe 'when provided' do
it 'should be passed down to the paragraph tag' do
hint_text = "this is the title of the post"
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :hint => hint_text))
end
output_buffer.should have_tag("form li p.inline-hints", hint_text)
end
end
describe 'when not provided' do
describe 'when localized hint (I18n) is provided' do
before do
@localized_hint_text = "This is the localized hint."
@default_localized_hint_text = "This is the default localized hint."
::I18n.backend.store_translations :en,
:formtastic => {
:hints => {
:title => @default_localized_hint_text,
:post => {
:title => @localized_hint_text
}
}
}
::Formtastic::SemanticFormBuilder.i18n_lookups_by_default = false
end
describe 'when provided value (hint value) is set to TRUE' do
it 'should render a hint paragraph containing a localized hint (I18n)' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :hint => true))
end
output_buffer.should have_tag('form li p.inline-hints', @localized_hint_text)
end
it 'should render a hint paragraph containing an optional localized hint (I18n) if first is not set' do
::I18n.backend.store_translations :en,
:formtastic => {
:hints => {
:post => {
:title => nil
}
}
}
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :hint => true))
end
output_buffer.should have_tag('form li p.inline-hints', @default_localized_hint_text)
end
end
describe 'when provided value (label value) is set to FALSE' do
it 'should not render a hint paragraph' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :hint => false))
end
output_buffer.should_not have_tag('form li p.inline-hints', @localized_hint_text)
end
end
end
describe 'when localized hint (I18n) is not provided' do
it 'should not render a hint paragraph' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should_not have_tag('form li p.inline-hints')
end
end
end
end
describe ':wrapper_html option' do
describe 'when provided' do
it 'should be passed down to the li tag' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :wrapper_html => {:id => :another_id}))
end
output_buffer.should have_tag("form li#another_id")
end
it 'should append given classes to li default classes' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :wrapper_html => {:class => :another_class}, :required => true))
end
output_buffer.should have_tag("form li.string")
output_buffer.should have_tag("form li.required")
output_buffer.should have_tag("form li.another_class")
output_buffer.should have_tag("form li.title")
end
it 'should allow classes to be an array' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :wrapper_html => {:class => [ :my_class, :another_class ]}))
end
output_buffer.should have_tag("form li.string")
output_buffer.should have_tag("form li.my_class")
output_buffer.should have_tag("form li.another_class")
output_buffer.should have_tag("form li.title")
end
end
describe 'when not provided' do
it 'should use default id and class' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should have_tag("form li#post_title_input")
output_buffer.should have_tag("form li.string")
output_buffer.should have_tag("form li.title")
end
end
end
end
describe ':as any type of input' do
it 'should create a list item for each input' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
concat(builder.input(:body))
end
output_buffer.should have_tag('form li', :count => 2)
end
describe 'when there are errors on the object for this method' do
before do
@title_errors = ['must not be blank', 'must be longer than 10 characters', 'must be awesome']
@errors = mock('errors')
@errors.stub!(:[]).with(:title).and_return(@title_errors)
@new_post.stub!(:errors).and_return(@errors)
end
it 'should apply an errors class to the list item' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should have_tag('form li.error')
end
it 'should not wrap the input with the Rails default error wrapping' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should_not have_tag('div.fieldWithErrors')
end
it 'should render a paragraph for the errors' do
Formtastic::SemanticFormBuilder.inline_errors = :sentence
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should have_tag('form li.error p.inline-errors')
end
it 'should not display an error list' do
Formtastic::SemanticFormBuilder.inline_errors = :list
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
output_buffer.should have_tag('form li.error ul.errors')
end
end
describe 'when there are no errors on the object for this method' do
before do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title))
end
end
it 'should not apply an errors class to the list item' do
output_buffer.should_not have_tag('form li.error')
end
it 'should not render a paragraph for the errors' do
output_buffer.should_not have_tag('form li.error p.inline-errors')
end
it 'should not display an error list' do
output_buffer.should_not have_tag('form li.error ul.errors')
end
end
describe 'when no object is provided' do
before do
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:title))
end
end
it 'should not apply an errors class to the list item' do
output_buffer.should_not have_tag('form li.error')
end
it 'should not render a paragraph for the errors' do
output_buffer.should_not have_tag('form li.error p.inline-errors')
end
it 'should not display an error list' do
output_buffer.should_not have_tag('form li.error ul.errors')
end
end
end
# Test string_mappings: :string, :password and :numeric
string_mappings = Formtastic::SemanticFormBuilder::INPUT_MAPPINGS.slice(*Formtastic::SemanticFormBuilder::STRING_MAPPINGS)
string_mappings.each do |type, template_method|
describe ":as => #{type.inspect}" do
before do
@new_post.stub!(:title)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type, :limit => 50))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end
end
it "should have a #{type} class on the wrapper" do
output_buffer.should have_tag("form li.#{type}")
end
it 'should have a post_title_input id on the wrapper' do
output_buffer.should have_tag('form li#post_title_input')
end
it 'should generate a label for the input' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label[@for="post_title"]')
output_buffer.should have_tag('form li label', /Title/)
end
input_type = template_method.to_s.split('_').first
it "should generate a #{input_type} input" do
output_buffer.should have_tag("form li input")
output_buffer.should have_tag("form li input#post_title")
output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]")
output_buffer.should have_tag("form li input[@name=\"post[title]\"]")
end
unless type == :numeric
it 'should have a maxlength matching the column limit' do
@new_post.column_for_attribute(:title).limit.should == 50
output_buffer.should have_tag("form li input[@maxlength='50']")
end
it 'should use default_text_field_size for columns longer than default_text_field_size' do
default_size = Formtastic::SemanticFormBuilder.default_text_field_size
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type, :limit => default_size * 2))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end
output_buffer.should have_tag("form li input[@size='#{default_size}']")
end
it 'should use the column size for columns shorter than default_text_field_size' do
column_limit_shorted_than_default = 1
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type, :limit => column_limit_shorted_than_default))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end
output_buffer.should have_tag("form li input[@size='#{column_limit_shorted_than_default}']")
end
end
it 'should use default_text_field_size for methods without database columns' do
default_size = Formtastic::SemanticFormBuilder.default_text_field_size
@new_post.stub!(:column_for_attribute).and_return(nil) # Return a nil column
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type))
end
output_buffer.should have_tag("form li input[@size='#{default_size}']")
end
it 'should use input_html to style inputs' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type, :input_html => { :class => 'myclass' }))
end
output_buffer.should have_tag("form li input.myclass")
end
it 'should consider input_html :id in labels' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type, :input_html => { :id => 'myid' }))
end
output_buffer.should have_tag('form li label[@for="myid"]')
end
it 'should generate input and labels even if no object is given' do
semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title, :as => type))
end
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label[@for="project_title"]')
output_buffer.should have_tag('form li label', /Title/)
output_buffer.should have_tag("form li input")
output_buffer.should have_tag("form li input#project_title")
output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]")
output_buffer.should have_tag("form li input[@name=\"project[title]\"]")
end
end
end
# Test other mappings that are not strings: :text and :file.
other_mappings = Formtastic::SemanticFormBuilder::INPUT_MAPPINGS.except(*Formtastic::SemanticFormBuilder::STRING_MAPPINGS)
other_mappings.each do |type, template_method|
describe ":as => #{type.inspect}" do
before do
@new_post.stub!(:body)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:body, :as => type))
end
end
it "should have a #{type} class on the wrapper" do
output_buffer.should have_tag("form li.#{type}")
end
it 'should have a post_title_input id on the wrapper' do
output_buffer.should have_tag('form li#post_body_input')
end
it 'should generate a label for the input' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label[@for="post_body"]')
output_buffer.should have_tag('form li label', /Body/)
end
input_type = template_method.to_s.gsub(/_field|_/, '')
if template_method.to_s =~ /_field$/ # password_field
it "should generate a #{input_type} input" do
output_buffer.should have_tag("form li input")
output_buffer.should have_tag("form li input#post_body")
output_buffer.should have_tag("form li input[@name=\"post[body]\"]")
output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]")
end
it 'should use input_html to style inputs' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type, :input_html => { :class => 'myclass' }))
end
output_buffer.should have_tag("form li input.myclass")
end
else # text_area
it "should generate a #{input_type} input" do
output_buffer.should have_tag("form li #{input_type}")
output_buffer.should have_tag("form li #{input_type}#post_body")
output_buffer.should have_tag("form li #{input_type}[@name=\"post[body]\"]")
end
it 'should use input_html to style inputs' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => type, :input_html => { :class => 'myclass' }))
end
output_buffer.should have_tag("form li #{input_type}.myclass")
end
end
describe 'when no object is given' do
before(:each) do
semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:title, :as => type))
end
end
it 'should generate input' do
if template_method.to_s =~ /_field$/ # password_field
output_buffer.should have_tag("form li input")
output_buffer.should have_tag("form li input#project_title")
output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]")
output_buffer.should have_tag("form li input[@name=\"project[title]\"]")
else
output_buffer.should have_tag("form li #{input_type}")
output_buffer.should have_tag("form li #{input_type}#project_title")
output_buffer.should have_tag("form li #{input_type}[@name=\"project[title]\"]")
end
end
it 'should generate labels' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label[@for="project_title"]')
output_buffer.should have_tag('form li label', /Title/)
end
end
end
end
describe ":as => :hidden" do
before do
@new_post.stub!(:secret)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden))
end
end
it "should have a hidden class on the wrapper" do
output_buffer.should have_tag('form li.hidden')
end
it 'should have a post_hidden_input id on the wrapper' do
output_buffer.should have_tag('form li#post_secret_input')
end
it 'should not generate a label for the input' do
output_buffer.should_not have_tag('form li label')
end
it "should generate a input field" do
output_buffer.should have_tag("form li input#post_secret")
output_buffer.should have_tag("form li input[@type=\"hidden\"]")
output_buffer.should have_tag("form li input[@name=\"post[secret]\"]")
end
it "should not render inline errors" do
@errors = mock('errors')
@errors.stub!(:[]).with(:secret).and_return(["foo", "bah"])
@new_post.stub!(:errors).and_return(@errors)
semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden))
end
output_buffer.should_not have_tag("form li p.inline-errors")
output_buffer.should_not have_tag("form li ul.errors")
end
end
describe ":as => :time_zone" do
before do
@new_post.stub!(:time_zone)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:time_zone))
end
end
it "should have a time_zone class on the wrapper" do
output_buffer.should have_tag('form li.time_zone')
end
it 'should have a post_title_input id on the wrapper' do
output_buffer.should have_tag('form li#post_time_zone_input')
end
it 'should generate a label for the input' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label[@for="post_time_zone"]')
output_buffer.should have_tag('form li label', /Time zone/)
end
it "should generate a select" do
output_buffer.should have_tag("form li select")
output_buffer.should have_tag("form li select#post_time_zone")
output_buffer.should have_tag("form li select[@name=\"post[time_zone]\"]")
end
it 'should use input_html to style inputs' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:time_zone, :input_html => { :class => 'myclass' }))
end
output_buffer.should have_tag("form li select.myclass")
end
describe 'when no object is given' do
before(:each) do
semantic_form_for(:project, :url => 'http://test.host/') do |builder|
concat(builder.input(:time_zone, :as => :time_zone))
end
end
it 'should generate labels' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label[@for="project_time_zone"]')
output_buffer.should have_tag('form li label', /Time zone/)
end
it 'should generate select inputs' do
output_buffer.should have_tag("form li select")
output_buffer.should have_tag("form li select#project_time_zone")
output_buffer.should have_tag("form li select[@name=\"project[time_zone]\"]")
end
end
end
describe ":as => :country" do
before do
@new_post.stub!(:country)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string))
end
describe "when country_select is not available as a helper from a plugin" do
it "should raise an error, sugesting the author installs a plugin" do
lambda {
semantic_form_for(@new_post) do |builder|
concat(builder.input(:country, :as => :country))
end
}.should raise_error
end
end
describe "when country_select is available as a helper (from a plugin)" do
before do
semantic_form_for(@new_post) do |builder|
builder.stub!(:country_select).and_return("<select><option>...</option></select>")
concat(builder.input(:country, :as => :country))
end
end
it "should have a time_zone class on the wrapper" do
output_buffer.should have_tag('form li.country')
end
it 'should have a post_title_input id on the wrapper' do
output_buffer.should have_tag('form li#post_country_input')
end
it 'should generate a label for the input' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label[@for="post_country"]')
output_buffer.should have_tag('form li label', /Country/)
end
it "should generate a select" do
output_buffer.should have_tag("form li select")
end
end
describe ":priority_countries option" do
it "should be passed down to the country_select helper when provided" do
priority_countries = ["Foo", "Bah"]
semantic_form_for(@new_post) do |builder|
builder.stub!(:country_select).and_return("<select><option>...</option></select>")
builder.should_receive(:country_select).with(:country, priority_countries, {}, {}).and_return("<select><option>...</option></select>")
concat(builder.input(:country, :as => :country, :priority_countries => priority_countries))
end
end
it "should default to the @@priority_countries config when absent" do
priority_countries = Formtastic::SemanticFormBuilder.priority_countries
priority_countries.should_not be_empty
priority_countries.should_not be_nil
semantic_form_for(@new_post) do |builder|
builder.stub!(:country_select).and_return("<select><option>...</option></select>")
builder.should_receive(:country_select).with(:country, priority_countries, {}, {}).and_return("<select><option>...</option></select>")
concat(builder.input(:country, :as => :country))
end
end
end
end
describe ':as => :radio' do
before do
@new_post.stub!(:author).and_return(@bob)
@new_post.stub!(:author_id).and_return(@bob.id)
::Post.stub!(:reflect_on_association).and_return { |column_name| mock('reflection', :options => {}, :klass => ::Author, :macro => :belongs_to) }
end
describe 'for belongs_to association' do
before do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :radio, :value_as_class => true))
end
end
it 'should have a radio class on the wrapper' do
output_buffer.should have_tag('form li.radio')
end
it 'should have a post_author_input id on the wrapper' do
output_buffer.should have_tag('form li#post_author_input')
end
it 'should generate a fieldset and legend containing label text for the input' do
output_buffer.should have_tag('form li fieldset')
output_buffer.should have_tag('form li fieldset legend')
output_buffer.should have_tag('form li fieldset legend', /Author/)
end
it 'should generate an ordered list with a list item for each choice' do
output_buffer.should have_tag('form li fieldset ol')
output_buffer.should have_tag('form li fieldset ol li', :count => ::Author.find(:all).size)
end
it 'should have one option with a "checked" attribute' do
output_buffer.should have_tag('form li input[@checked]', :count => 1)
end
describe "each choice" do
it 'should contain a label for the radio input with a nested input and label text' do
::Author.find(:all).each do |author|
output_buffer.should have_tag('form li fieldset ol li label', /#{author.to_label}/)
output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_id_#{author.id}']")
end
end
it 'should use values as li.class when value_as_class is true' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li fieldset ol li.#{author.id} label")
end
end
it "should have a radio input" do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li fieldset ol li label input#post_author_id_#{author.id}")
output_buffer.should have_tag("form li fieldset ol li label input[@type='radio']")
output_buffer.should have_tag("form li fieldset ol li label input[@value='#{author.id}']")
output_buffer.should have_tag("form li fieldset ol li label input[@name='post[author_id]']")
end
end
it "should mark input as checked if it's the the existing choice" do
@new_post.author_id.should == @bob.id
@new_post.author.id.should == @bob.id
@new_post.author.should == @bob
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :radio))
end
output_buffer.should have_tag("form li fieldset ol li label input[@checked='checked']")
end
end
describe 'and no object is given' do
before(:each) do
output_buffer.replace ''
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :radio, :collection => ::Author.find(:all)))
end
end
it 'should generate a fieldset with legend' do
output_buffer.should have_tag('form li fieldset legend', /Author/)
end
it 'should generate an li tag for each item in the collection' do
output_buffer.should have_tag('form li fieldset ol li', :count => ::Author.find(:all).size)
end
it 'should generate labels for each item' do
::Author.find(:all).each do |author|
output_buffer.should have_tag('form li fieldset ol li label', /#{author.to_label}/)
output_buffer.should have_tag("form li fieldset ol li label[@for='project_author_id_#{author.id}']")
end
end
it 'should generate inputs for each item' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li fieldset ol li label input#project_author_id_#{author.id}")
output_buffer.should have_tag("form li fieldset ol li label input[@type='radio']")
output_buffer.should have_tag("form li fieldset ol li label input[@value='#{author.id}']")
output_buffer.should have_tag("form li fieldset ol li label input[@name='project[author_id]']")
end
end
end
end
end
describe ':as => :select' do
before do
@new_post.stub!(:author).and_return(@bob)
@new_post.stub!(:author_id).and_return(@bob.id)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :integer, :limit => 255))
end
describe 'for a belongs_to association' do
before do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select))
end
end
it 'should have a select class on the wrapper' do
output_buffer.should have_tag('form li.select')
end
it 'should have a post_author_input id on the wrapper' do
output_buffer.should have_tag('form li#post_author_input')
end
it 'should have a label inside the wrapper' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label', /Author/)
output_buffer.should have_tag("form li label[@for='post_author_id']")
end
it 'should have a select inside the wrapper' do
output_buffer.should have_tag('form li select')
output_buffer.should have_tag('form li select#post_author_id')
end
it 'should not create a multi-select' do
output_buffer.should_not have_tag('form li select[@multiple]')
end
it 'should create a select without size' do
output_buffer.should_not have_tag('form li select[@size]')
end
it 'should have a blank option' do
output_buffer.should have_tag("form li select option[@value='']")
end
it 'should have a select option for each Author' do
output_buffer.should have_tag('form li select option', :count => ::Author.find(:all).size + 1)
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li select option[@value='#{author.id}']", /#{author.to_label}/)
end
end
it 'should have one option with a "selected" attribute' do
output_buffer.should have_tag('form li select option[@selected]', :count => 1)
end
it 'should not singularize the association name' do
@new_post.stub!(:author_status).and_return(@bob)
@new_post.stub!(:author_status_id).and_return(@bob.id)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :integer, :limit => 255))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author_status, :as => :select))
end
output_buffer.should have_tag('form li select#post_author_status_id')
end
end
describe 'for a has_many association' do
before do
semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :select))
end
end
it 'should have a select class on the wrapper' do
output_buffer.should have_tag('form li.select')
end
it 'should have a post_author_input id on the wrapper' do
output_buffer.should have_tag('form li#author_posts_input')
end
it 'should have a label inside the wrapper' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label', /Post/)
output_buffer.should have_tag("form li label[@for='author_post_ids']")
end
it 'should have a select inside the wrapper' do
output_buffer.should have_tag('form li select')
output_buffer.should have_tag('form li select#author_post_ids')
end
it 'should have a multi-select select' do
output_buffer.should have_tag('form li select[@multiple="multiple"]')
end
it 'should have a select option for each Post' do
output_buffer.should have_tag('form li select option', :count => ::Post.find(:all).size)
::Post.find(:all).each do |post|
output_buffer.should have_tag("form li select option[@value='#{post.id}']", /#{post.to_label}/)
end
end
it 'should not have a blank option' do
output_buffer.should_not have_tag("form li select option[@value='']")
end
it 'should have one option with a "selected" attribute' do
output_buffer.should have_tag('form li select option[@selected]', :count => 1)
end
end
describe 'for a has_and_belongs_to_many association' do
before do
semantic_form_for(@freds_post) do |builder|
concat(builder.input(:authors, :as => :select))
end
end
it 'should have a select class on the wrapper' do
output_buffer.should have_tag('form li.select')
end
it 'should have a post_author_input id on the wrapper' do
output_buffer.should have_tag('form li#post_authors_input')
end
it 'should have a label inside the wrapper' do
output_buffer.should have_tag('form li label')
output_buffer.should have_tag('form li label', /Author/)
output_buffer.should have_tag("form li label[@for='post_author_ids']")
end
it 'should have a select inside the wrapper' do
output_buffer.should have_tag('form li select')
output_buffer.should have_tag('form li select#post_author_ids')
end
it 'should have a multi-select select' do
output_buffer.should have_tag('form li select[@multiple="multiple"]')
end
it 'should have a select option for each Author' do
output_buffer.should have_tag('form li select option', :count => ::Author.find(:all).size)
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li select option[@value='#{author.id}']", /#{author.to_label}/)
end
end
it 'should not have a blank option' do
output_buffer.should_not have_tag("form li select option[@value='']")
end
it 'should have one option with a "selected" attribute' do
output_buffer.should have_tag('form li select option[@selected]', :count => 1)
end
end
describe 'when :prompt => "choose something" is set' do
before do
@new_post.stub!(:author_id).and_return(nil)
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select, :prompt => "choose author"))
end
end
it 'should have a select with prompt' do
output_buffer.should have_tag("form li select option[@value='']", /choose author/)
end
it 'should not have a blank select option' do
output_buffer.should_not have_tag("form li select option[@value='']", "")
end
end
describe 'when no object is given' do
before(:each) do
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author, :as => :select, :collection => ::Author.find(:all)))
end
end
it 'should generate label' do
output_buffer.should have_tag('form li label', /Author/)
output_buffer.should have_tag("form li label[@for='project_author']")
end
it 'should generate select inputs' do
output_buffer.should have_tag('form li select#project_author')
output_buffer.should have_tag('form li select option', :count => ::Author.find(:all).size + 1)
end
it 'should generate an option to each item' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li select option[@value='#{author.id}']", /#{author.to_label}/)
end
end
end
describe 'when :selected is set' do
before do
@new_post.stub!(:author_id).and_return(nil)
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => :select, :selected => @bob.id ))
end
end
it 'should have a selected item' do
output_buffer.should have_tag("form li select option[@selected='selected']")
end
it 'bob should be selected' do
output_buffer.should have_tag("form li select option[@selected='selected']", /bob/i)
output_buffer.should have_tag("form li select option[@selected='selected'][@value='42']")
end
end
end
describe ':as => :check_boxes' do
describe 'for a has_many association' do
before do
semantic_form_for(@fred) do |builder|
concat(builder.input(:posts, :as => :check_boxes, :value_as_class => true))
end
end
it 'should have a check_boxes class on the wrapper' do
output_buffer.should have_tag('form li.check_boxes')
end
it 'should have a author_posts_input id on the wrapper' do
output_buffer.should have_tag('form li#author_posts_input')
end
it 'should generate a fieldset and legend containing label text for the input' do
output_buffer.should have_tag('form li fieldset')
output_buffer.should have_tag('form li fieldset legend')
output_buffer.should have_tag('form li fieldset legend', /Posts/)
end
it 'should generate an ordered list with a list item for each choice' do
output_buffer.should have_tag('form li fieldset ol')
output_buffer.should have_tag('form li fieldset ol li', :count => ::Post.find(:all).size)
end
it 'should have one option with a "checked" attribute' do
output_buffer.should have_tag('form li input[@checked]', :count => 1)
end
it 'should generate hidden inputs with default value blank' do
output_buffer.should have_tag("form li fieldset ol li label input[@type='hidden'][@value='']", :count => ::Post.find(:all).size)
end
describe "each choice" do
it 'should contain a label for the radio input with a nested input and label text' do
::Post.find(:all).each do |post|
output_buffer.should have_tag('form li fieldset ol li label', /#{post.to_label}/)
output_buffer.should have_tag("form li fieldset ol li label[@for='author_post_ids_#{post.id}']")
end
end
it 'should use values as li.class when value_as_class is true' do
::Post.find(:all).each do |post|
output_buffer.should have_tag("form li fieldset ol li.#{post.id} label")
end
end
it 'should have a checkbox input for each post' do
::Post.find(:all).each do |post|
output_buffer.should have_tag("form li fieldset ol li label input#author_post_ids_#{post.id}")
output_buffer.should have_tag("form li fieldset ol li label input[@name='author[post_ids][]']", :count => 2)
end
end
it "should mark input as checked if it's the the existing choice" do
::Post.find(:all).include?(@fred.posts.first).should be_true
output_buffer.should have_tag("form li fieldset ol li label input[@checked='checked']")
end
end
describe 'and no object is given' do
before(:each) do
output_buffer.replace ''
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:author_id, :as => :check_boxes, :collection => ::Author.find(:all)))
end
end
it 'should generate a fieldset with legend' do
output_buffer.should have_tag('form li fieldset legend', /Author/)
end
it 'shold generate an li tag for each item in the collection' do
output_buffer.should have_tag('form li fieldset ol li', :count => ::Author.find(:all).size)
end
it 'should generate labels for each item' do
::Author.find(:all).each do |author|
output_buffer.should have_tag('form li fieldset ol li label', /#{author.to_label}/)
output_buffer.should have_tag("form li fieldset ol li label[@for='project_author_id_#{author.id}']")
end
end
it 'should generate inputs for each item' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li fieldset ol li label input#project_author_id_#{author.id}")
output_buffer.should have_tag("form li fieldset ol li label input[@type='checkbox']")
output_buffer.should have_tag("form li fieldset ol li label input[@value='#{author.id}']")
output_buffer.should have_tag("form li fieldset ol li label input[@name='project[author_id][]']")
end
end
end
end
end
describe 'for collections' do
before do
@new_post.stub!(:author).and_return(@bob)
@new_post.stub!(:author_id).and_return(@bob.id)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :integer, :limit => 255))
end
{ :select => :option, :radio => :input, :check_boxes => :'input[@type="checkbox"]' }.each do |type, countable|
describe ":as => #{type.inspect}" do
describe 'when the :collection option is not provided' do
it 'should perform a basic find on the association class' do
::Author.should_receive(:find)
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type))
end
end
end
describe 'when the :collection option is provided' do
before do
@authors = ::Author.find(:all) * 2
output_buffer.replace '' # clears the output_buffer from the before block, hax!
end
it 'should not call find() on the parent class' do
::Author.should_not_receive(:find)
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type, :collection => @authors))
end
end
it 'should use the provided collection' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type, :collection => @authors))
end
output_buffer.should have_tag("form li.#{type} #{countable}", :count => @authors.size + (type == :select ? 1 : 0))
end
describe 'and the :collection is an array of strings' do
before do
@new_post.stub!(:category_name).and_return('')
@categories = [ 'General', 'Design', 'Development', 'Quasi-Serious Inventions' ]
end
it "should use the string as the label text and value for each #{countable}" do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => type, :collection => @categories))
end
@categories.each do |value|
output_buffer.should have_tag("form li.#{type}", /#{value}/)
output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value}']")
end
end
if type == :radio
it 'should generate a sanitized label for attribute' do
@bob.stub!(:category_name).and_return(@categories)
semantic_form_for(@new_post) do |builder|
builder.semantic_fields_for(@bob) do |bob_builder|
concat(bob_builder.input(:category_name, :as => type, :collection => @categories))
end
end
output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_category_name_general']")
output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_category_name_design']")
output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_category_name_development']")
output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_category_name_quasiserious_inventions']")
end
end
end
describe 'and the :collection is a hash of strings' do
before do
@new_post.stub!(:category_name).and_return('')
@categories = { 'General' => 'gen', 'Design' => 'des','Development' => 'dev' }
end
it "should use the key as the label text and the hash value as the value attribute for each #{countable}" do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => type, :collection => @categories))
end
@categories.each do |label, value|
output_buffer.should have_tag("form li.#{type}", /#{label}/)
output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value}']")
end
end
end
describe 'and the :collection is an array of arrays' do
before do
@new_post.stub!(:category_name).and_return('')
@categories = { 'General' => 'gen', 'Design' => 'des', 'Development' => 'dev' }.to_a
end
it "should use the first value as the label text and the last value as the value attribute for #{countable}" do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => type, :collection => @categories))
end
@categories.each do |text, value|
label = type == :select ? :option : :label
output_buffer.should have_tag("form li.#{type} #{label}", /#{text}/i)
output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value.to_s}']")
output_buffer.should have_tag("form li.#{type} #{countable}#post_category_name_#{value.to_s}") if type == :radio
end
end
end
if type == :radio
describe 'and the :collection is an array of arrays with boolean values' do
before do
@new_post.stub!(:category_name).and_return('')
@choices = { 'Yeah' => true, 'Nah' => false }.to_a
end
it "should use the first value as the label text and the last value as the value attribute for #{countable}" do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => type, :collection => @choices))
end
output_buffer.should have_tag("form li.#{type} #{countable}#post_category_name_true")
output_buffer.should have_tag("form li.#{type} #{countable}#post_category_name_false")
end
end
end
describe 'and the :collection is an array of symbols' do
before do
@new_post.stub!(:category_name).and_return('')
@categories = [ :General, :Design, :Development ]
end
it "should use the symbol as the label text and value for each #{countable}" do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => type, :collection => @categories))
end
@categories.each do |value|
label = type == :select ? :option : :label
output_buffer.should have_tag("form li.#{type} #{label}", /#{value}/i)
output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value.to_s}']")
end
end
end
describe 'and the :collection is an OrderedHash of strings' do
before do
@new_post.stub!(:category_name).and_return('')
@categories = ActiveSupport::OrderedHash.new('General' => 'gen', 'Design' => 'des','Development' => 'dev')
end
it "should use the key as the label text and the hash value as the value attribute for each #{countable}" do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:category_name, :as => type, :collection => @categories))
end
@categories.each do |label, value|
output_buffer.should have_tag("form li.#{type}", /#{label}/)
output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value}']")
end
end
end
describe 'when the :label_method option is provided' do
describe 'as a symbol' do
before do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type, :label_method => :login))
end
end
it 'should have options with text content from the specified method' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li.#{type}", /#{author.login}/)
end
end
end
describe 'as a proc' do
before do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type, :label_method => Proc.new {|a| a.login.reverse }))
end
end
it 'should have options with the proc applied to each' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li.#{type}", /#{author.login.reverse}/)
end
end
end
end
describe 'when the :label_method option is not provided' do
Formtastic::SemanticFormBuilder.collection_label_methods.each do |label_method|
describe "when the collection objects respond to #{label_method}" do
before do
@fred.stub!(:respond_to?).and_return { |m| m.to_s == label_method }
::Author.find(:all).each { |a| a.stub!(label_method).and_return('The Label Text') }
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type))
end
end
it "should render the options with #{label_method} as the label" do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li.#{type}", /The Label Text/)
end
end
end
end
end
describe 'when the :value_method option is provided' do
describe 'as a symbol' do
before do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type, :value_method => :login))
end
end
it 'should have options with values from specified method' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{author.login}']")
end
end
end
describe 'as a proc' do
before do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:author, :as => type, :value_method => Proc.new {|a| a.login.reverse }))
end
end
it 'should have options with the proc applied to each value' do
::Author.find(:all).each do |author|
output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{author.login.reverse}']")
end
end
end
end
end
end
end
describe 'for boolean attributes' do
{ :select => :option, :radio => :input }.each do |type, countable|
checked_or_selected = { :select => :selected, :radio => :checked }[type]
describe ":as => #{type.inspect}" do
before do
@new_post.stub!(:allow_comments)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => type))
end
end
it "should have a #{type} class on the wrapper" do
output_buffer.should have_tag("form li.#{type}")
end
it 'should have a post_allow_comments_input id on the wrapper' do
output_buffer.should have_tag('form li#post_allow_comments_input')
end
it 'should generate a fieldset containing a legend' do
output_buffer.should have_tag("form li.#{type}", /Allow comments/)
end
it "should generate two #{countable}" do
output_buffer.should have_tag("form li.#{type} #{countable}", :count => (type == :select ? 3 : 2))
output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="true"]})
output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="false"]})
end
describe 'when the locale sets the label text' do
before do
I18n.backend.store_translations 'en', :formtastic => {:yes => 'Absolutely!', :no => 'Never!'}
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => type))
end
end
after do
I18n.backend.store_translations 'en', :formtastic => {:yes => nil, :no => nil}
end
it 'should allow translation of the labels' do
output_buffer.should have_tag("form li.#{type}", /Absolutely\!/)
output_buffer.should have_tag("form li.#{type}", /Never\!/)
end
end
describe 'when the value is nil' do
before do
@new_post.stub!(:allow_comments).and_return(nil)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => type))
end
end
it "should not mark either #{countable} as #{checked_or_selected}" do
output_buffer.should_not have_tag(%{form li.#{type} input[@#{checked_or_selected}="#{checked_or_selected}"]})
end
end
describe 'when the value is true' do
before do
@new_post.stub!(:allow_comments).and_return(true)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => type))
end
end
it "should mark the true #{countable} as #{checked_or_selected}" do
output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="true"][@#{checked_or_selected}="#{checked_or_selected}"]}, :count => 1)
end
it "should not mark the false #{countable} as #{checked_or_selected}" do
output_buffer.should_not have_tag(%{form li.#{type} #{countable}[@value="false"][@#{checked_or_selected}="#{checked_or_selected}"]})
end
end
describe 'when the value is false' do
before do
@new_post.stub!(:allow_comments).and_return(false)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => type))
end
end
it "should not mark the true #{countable} as #{checked_or_selected}" do
output_buffer.should_not have_tag(%{form li.#{type} #{countable}[@value="true"][@#{checked_or_selected}="#{checked_or_selected}"]})
end
it "should mark the false #{countable} as #{checked_or_selected}" do
output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="false"][@#{checked_or_selected}="#{checked_or_selected}"]}, :count => 1)
end
end
describe 'when :true and :false options are provided' do
before do
@new_post.stub!(:allow_comments)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => type, :true => "Absolutely", :false => "No Way"))
end
end
it 'should use them as labels' do
output_buffer.should have_tag("form li.#{type}", /Absolutely/)
output_buffer.should have_tag("form li.#{type}", /No Way/)
end
end
end
end
end
end
describe ':as => :date' do
before do
@new_post.stub!(:publish_at)
#@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :date))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :date))
@builder = builder
end
end
it 'should have a date class on the wrapper li' do
output_buffer.should have_tag('form li.date')
end
it 'should have a fieldset inside the li wrapper' do
output_buffer.should have_tag('form li.date fieldset')
end
it 'should have a legend containing the label text inside the fieldset' do
output_buffer.should have_tag('form li.date fieldset legend', /Publish at/)
end
it 'should have an ordered list of three items inside the fieldset' do
output_buffer.should have_tag('form li.date fieldset ol')
output_buffer.should have_tag('form li.date fieldset ol li', :count => 3)
end
it 'should have three labels for year, month and day' do
output_buffer.should have_tag('form li.date fieldset ol li label', :count => 3)
output_buffer.should have_tag('form li.date fieldset ol li label', /year/i)
output_buffer.should have_tag('form li.date fieldset ol li label', /month/i)
output_buffer.should have_tag('form li.date fieldset ol li label', /day/i)
end
it 'should have three selects for year, month and day' do
output_buffer.should have_tag('form li.date fieldset ol li select', :count => 3)
end
end
describe ':as => :datetime' do
before do
@new_post.stub!(:publish_at)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :datetime))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime))
end
end
it 'should have a datetime class on the wrapper li' do
output_buffer.should have_tag('form li.datetime')
end
it 'should have a fieldset inside the li wrapper' do
output_buffer.should have_tag('form li.datetime fieldset')
end
it 'should have a legend containing the label text inside the fieldset' do
output_buffer.should have_tag('form li.datetime fieldset legend', /Publish at/)
end
it 'should have an ordered list of five items inside the fieldset' do
output_buffer.should have_tag('form li.datetime fieldset ol')
output_buffer.should have_tag('form li.datetime fieldset ol li', :count => 5)
end
it 'should have five labels for year, month, day, hour and minute' do
output_buffer.should have_tag('form li.datetime fieldset ol li label', :count => 5)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /year/i)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /month/i)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /day/i)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /hour/i)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /minute/i)
end
it 'should have five selects for year, month, day, hour and minute' do
output_buffer.should have_tag('form li.datetime fieldset ol li select', :count => 5)
end
it 'should generate a sanitized label and matching ids for attribute' do
@bob.stub!(:publish_at)
@bob.stub!(:column_for_attribute).and_return(mock('column', :type => :datetime))
semantic_form_for(@new_post) do |builder|
builder.semantic_fields_for(@bob, :index => 10) do |bob_builder|
concat(bob_builder.input(:publish_at, :as => :datetime))
end
end
1.upto(5) do |i|
output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_10_publish_at_#{i}i']")
output_buffer.should have_tag("form li fieldset ol li #post_author_10_publish_at_#{i}i")
end
end
describe 'when :discard_input => true is set' do
it 'should use default hidden value equals to 1 when attribute returns nil' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime, :discard_day => true))
end
output_buffer.should have_tag("form li input[@type='hidden'][@value='1']")
end
it 'should use default attribute value when it is not nil' do
@new_post.stub!(:publish_at).and_return(Date.new(2007,12,27))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime, :discard_day => true))
end
output_buffer.should have_tag("form li input[@type='hidden'][@value='27']")
end
end
describe 'inputs order' do
it 'should have a default' do
semantic_form_for(@new_post) do |builder|
self.should_receive(:select_year).once.ordered.and_return('')
self.should_receive(:select_month).once.ordered.and_return('')
self.should_receive(:select_day).once.ordered.and_return('')
builder.input(:publish_at, :as => :datetime)
end
end
it 'should be specified with :order option' do
I18n.backend.store_translations 'en', :date => { :order => [:month, :year, :day] }
semantic_form_for(@new_post) do |builder|
self.should_receive(:select_month).once.ordered.and_return('')
self.should_receive(:select_year).once.ordered.and_return('')
self.should_receive(:select_day).once.ordered.and_return('')
builder.input(:publish_at, :as => :datetime)
end
end
it 'should be changed through I18n' do
semantic_form_for(@new_post) do |builder|
self.should_receive(:select_day).once.ordered.and_return('')
self.should_receive(:select_month).once.ordered.and_return('')
self.should_receive(:select_year).once.ordered.and_return('')
builder.input(:publish_at, :as => :datetime, :order => [:day, :month, :year])
end
end
end
describe 'when the locale changes the label text' do
before do
I18n.backend.store_translations 'en', :datetime => {:prompts => {
:year => 'The Year', :month => 'The Month', :day => 'The Day',
:hour => 'The Hour', :minute => 'The Minute'
}}
semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :datetime))
end
end
after do
I18n.backend.store_translations 'en', :formtastic => {
:year => nil, :month => nil, :day => nil,
:hour => nil, :minute => nil
}
end
it 'should have translated labels for year, month, day, hour and minute' do
output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Year/)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Month/)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Day/)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Hour/)
output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Minute/)
end
end
describe 'when no object is given' do
before(:each) do
output_buffer.replace ''
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:publish_at, :as => :datetime))
@builder = builder
end
end
it 'should have fieldset with legend' do
output_buffer.should have_tag('form li.datetime fieldset legend', /Publish at/)
end
it 'should have labels for each input' do
output_buffer.should have_tag('form li.datetime fieldset ol li label', :count => 5)
end
it 'should have selects for each inputs' do
output_buffer.should have_tag('form li.datetime fieldset ol li select', :count => 5)
end
end
end
describe ':as => :time' do
before do
@new_post.stub!(:publish_at)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :time))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:publish_at, :as => :time))
end
end
it 'should have a time class on the wrapper li' do
output_buffer.should have_tag('form li.time')
end
it 'should have a fieldset inside the li wrapper' do
output_buffer.should have_tag('form li.time fieldset')
end
it 'should have a legend containing the label text inside the fieldset' do
output_buffer.should have_tag('form li.time fieldset legend', /Publish at/)
end
it 'should have an ordered list of two items inside the fieldset' do
output_buffer.should have_tag('form li.time fieldset ol')
output_buffer.should have_tag('form li.time fieldset ol li', :count => 2)
end
it 'should have five labels for hour and minute' do
output_buffer.should have_tag('form li.time fieldset ol li label', :count => 2)
output_buffer.should have_tag('form li.time fieldset ol li label', /hour/i)
output_buffer.should have_tag('form li.time fieldset ol li label', /minute/i)
end
it 'should have two selects for hour and minute' do
output_buffer.should have_tag('form li.time fieldset ol li', :count => 2)
end
end
describe ':as => :boolean' do
before do
@new_post.stub!(:allow_comments)
@new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean))
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean))
end
end
it 'should have a boolean class on the wrapper' do
output_buffer.should have_tag('form li.boolean')
end
it 'should have a post_allow_comments_input id on the wrapper' do
output_buffer.should have_tag('form li#post_allow_comments_input')
end
it 'should generate a label containing the input' do
output_buffer.should have_tag('form li label', :count => 1)
output_buffer.should have_tag('form li label[@for="post_allow_comments"]')
output_buffer.should have_tag('form li label', /Allow comments/)
output_buffer.should have_tag('form li label input[@type="checkbox"]')
end
it 'should generate a checkbox input' do
output_buffer.should have_tag('form li label input')
output_buffer.should have_tag('form li label input#post_allow_comments')
output_buffer.should have_tag('form li label input[@type="checkbox"]')
output_buffer.should have_tag('form li label input[@name="post[allow_comments]"]')
output_buffer.should have_tag('form li label input[@type="checkbox"][@value="1"]')
end
it 'should allow checked and unchecked values to be sent' do
semantic_form_for(@new_post) do |builder|
concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'checked', :unchecked_value => 'unchecked'))
end
output_buffer.should have_tag('form li label input[@type="checkbox"][@value="checked"]')
output_buffer.should have_tag('form li label input[@type="hidden"][@value="unchecked"]')
end
it 'should generate a label and a checkbox even if no object is given' do
semantic_form_for(:project, :url => 'http://test.host') do |builder|
concat(builder.input(:allow_comments, :as => :boolean))
end
output_buffer.should have_tag('form li label[@for="project_allow_comments"]')
output_buffer.should have_tag('form li label', /Allow comments/)
output_buffer.should have_tag('form li label input[@type="checkbox"]')
output_buffer.should have_tag('form li label input#project_allow_comments')
output_buffer.should have_tag('form li label input[@type="checkbox"]')
output_buffer.should have_tag('form li label input[@name="project[allow_comments]"]')
end
end
end
|
pbelasco/pub_data_brasil
|
vendor/plugins/formtastic/spec/input_spec.rb
|
Ruby
|
agpl-3.0
| 87,084
|
Given /^there is a project called "([^\"]*)"$/ do |name|
Project.find_by_name(name) || Factory(:project, :name => name)
end
Given /^"([^\"]*)" is the owner of the project "([^\"]*)"/ do |login, project_name|
user = User.find_by_login(login)
project = Project.find_by_name(project_name)
project.add_user(user)
project.update_attribute(:user, user)
end
Given /^"([^\"]*)" sent an invitation to "([^\"]*)" for the project "([^\"]*)"$/ do |login, email, project_name|
user = User.find_by_login(login)
project = Project.find_by_name(project_name)
Factory(:invitation, :user => user, :email => email, :project => project)
end
Given /^the owner of the project "([^\"]*)" sent an invitation to "([^\"]*)"$/ do |project_name, login|
user = User.find_by_login(login)
project = Project.find_by_name(project_name)
invite = Invitation.new(:user_or_email => user.login)
invite.project = project
invite.user = project.user
invite.save!
end
Then /"([^\"]*)" should belong to the project "([^\"]*)" as (?:a|an) ([^\"]*)$/ do |login, project, role|
user = User.find_by_login(login)
project = Project.find_by_name(project)
project.people.find_by_user_id(user.id).role.should == Person::ROLES[role.to_sym]
end
# "Given a project with users @john and @richard"
Given(/^a project with users? (.+)$/) do |users|
@current_project = Factory(:project)
each_user(users, true) do |user|
person = Factory(:person, :user => user, :project => @current_project)
person.user.update_attribute :splash_screen, false
end
end
Given(/^(@.+) left the project$/) do |users|
each_user(users) do |user|
@current_project.remove_user user
end
end
Given /I am currently in the project (.*)$/ do |project_type|
@current_project ||= Factory(project_type.to_sym)
visit(projects_path(@current_project))
end
Given /I am in the project called "([^\"]*)"$/ do |name|
Given %(there is a project called "#{name}")
project = Project.find_by_name(name)
project.add_user(@current_user)
end
Given /^"([^\"]*)" is in the project called "([^\"]*)"$/ do |username,name|
Given %(there is a project called "#{name}")
project = Project.find_by_name(name)
project.add_user User.find_by_login(username)
end
Given /^"([^\"]*)" is not in the project called "([^\"]*)"$/ do |username,name|
Given %(there is a project called "#{name}")
project = Project.find_by_name(name)
project.remove_user User.find_by_login(username)
end
Given /^all the users are in the project with name: "([^\"]*)"$/ do |name|
Given %(there is a project called "#{name}")
project = Project.find_by_name(name)
User.all.each { |user| project.add_user(user) }
end
|
wesbillman/projects
|
features/step_definitions/project_steps.rb
|
Ruby
|
agpl-3.0
| 2,663
|
{% extends "education_group_app/blocks/layout.html" %}
{% load i18n bootstrap3 %}
{% comment "License" %}
* OSIS stands for Open Student Information System. It's an application
* designed to manage the core business of higher education institutions,
* such as universities, faculties, institutes and professional schools.
* The core business involves the administration of students, teachers,
* courses, programs and so on.
*
* Copyright (C) 2015-2020 Université catholique de Louvain (http://www.uclouvain.be)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of this license - GNU General Public License - is available
* at the root of the source code of this program. If not,
* see http://www.gnu.org/licenses/.
{% endcomment %}
{% block breadcrumb %}
{{ block.super }}
<li>
{{ mini_training_obj.acronym }}
</li>
<li>
{{ mini_training_version_obj.version_name }}
</li>
<li class="active">
{% trans 'Update Training' %}
</li>
{% endblock breadcrumb %}
{% block header_content %}
<div class="page-header">
<h2>
{{ mini_training_obj.acronym }} {{ version_label }} - {{ mini_training_obj.academic_year }}
</h2>
<h3>
{{ mini_training_obj.titles.title_fr }} {% if mini_training_version_obj.title_fr %} [
{{ mini_training_version_obj.title_fr }}]{% endif %}
</h3>
</div>
{% endblock header_content %}
{% block content %}
<form id="UpsertMiniTrainingVersionForm" class="mini_training_version_form osis-form" method="POST">
{% csrf_token %}
{% bootstrap_form_errors mini_training_version_form %}
<div class="panel panel-default">
<div class="panel-heading">
{% include "blocks/forms/create_cancel_buttons.html" %}
</div>
<div class="panel-body">
<ul class="nav nav-tabs" role="tablist">
{% for tab in tabs %}
{% if tab.display %}
<li role="presentation" class="form-tab {% if tab.active %}active{% endif %}">
<a data-toggle="tab" href="#tab-{{ forloop.counter }}" role="tab">{{ tab.text }}</a>
</li>
{% endif %}
{% endfor %}
</ul>
<div class="tab-content">
{% for tab in tabs %}
<div id="tab-{{ forloop.counter }}" class="tab-pane {% if tab.active %}active{% endif %}">
{% include tab.include_html %}
</div>
{% endfor %}
</div>
</div>
<div class="panel-footer text-right">
{% include "blocks/forms/create_cancel_buttons.html" %}
</div>
</div>
</form>
{% endblock content %}
|
uclouvain/OSIS-Louvain
|
program_management/templates/tree_version/mini_training/update.html
|
HTML
|
agpl-3.0
| 3,360
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Catalin Tomozei using IMS Development Environment (version 1.70 build 3427.16359)
// Copyright (C) 1995-2009 IMS MAXIMS plc. All rights reserved.
package ims.rules.forms.ruleseditorcomponent;
import java.io.Serializable;
public final class AccessLogic extends BaseAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public boolean isAccessible()
{
if(!super.isAccessible())
return false;
// TODO: Add your conditions here.
return true;
}
public boolean isReadOnly()
{
if(super.isReadOnly())
return true;
// TODO: Add your conditions here.
return false;
}
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/Rules/src/ims/rules/forms/ruleseditorcomponent/AccessLogic.java
|
Java
|
agpl-3.0
| 2,553
|
/*
* Copyright (C) 2000 - 2016 Silverpeas
*
* 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.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.importexport;
import java.io.Serializable;
/**
* This interface defines the features an immporter of serializable resources in Silverpeas have to
* satisfy. All importer in Silverpeas should implement this interface. An importer in Silverpeas is
* defined for a specific type of serializable resources and it has the responsability to know how
* to import them from a specific or a specified format.
* @param <T> The type of the serializable resources to import.
*/
public interface Importer<T extends Serializable> {
/**
* Imports a serialized resource from either the reader or the input stream and according to the
* import parameters carried by the specified descriptor. The resource is deserialized in an
* instance of T.
* @param descriptor the import descriptor in which information about the import process is
* indicated.
* @throws ImportException when an unexpected error occurs while importing the resource.
* @return an instance of T corresponfding to the imported resource.
*/
T importFrom(final ImportDescriptor descriptor) throws ImportException;
}
|
ebonnet/Silverpeas-Core
|
core-library/src/main/java/org/silverpeas/core/importexport/Importer.java
|
Java
|
agpl-3.0
| 2,274
|
/**
* Copyright 2014-2017 Vincent Noel (vincent.noel@butantan.gov.br)
*
* This file is part of SigNetSim.
*
* libSigNetSim 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.
*
* SigNetSim 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 SigNetSim. If not, see <http://www.gnu.org/licenses/>.
*/
/* This file contains all the class for the javascript methods of the forms used in signetsim
* In an effort to organize things a little, we will first declare the base class, then the mixins,
* then the inherited classes. And we'll make a list in this header
* Base class : Form.
*
*
* Mixin :
* - HasIndicator
*
*
* Derivated classes :
* - FloatForm : Form for floats, usign ajax verification
* - SbmlIdForm : Form for sbml ids, using ajax verification
* - MathForm : Form for math formulas, using ajax verification
* - SliderForm : Form for checkbox
* - Dropdown : Form for dropdown menus
* - EditableInput : Form for editable input, with post_treatment
* - SBOTermInput : Form for SBO term, printing the description of the term
* - ListForm : Form group, with the possibility to add and remove items
* - FormGroup : Form group, base class for the sbml elements forms
*/
let HasIndicator = (superclass) => class extends superclass {
setIndicatorValid(){
$("#" + this.field + "_validating").removeClass("in");
$("#" + this.field + "_invalid").removeClass("in");
$("#" + this.field + "_valid").addClass("in");
}
setIndicatorInvalid(){
$("#" + this.field + "_validating").removeClass("in");
$("#" + this.field + "_valid").removeClass("in");
$("#" + this.field + "_invalid").addClass("in");
}
setIndicatorValidating(){
$("#" + this.field + "_valid").removeClass("in");
$("#" + this.field + "_invalid").removeClass("in");
$("#" + this.field + "_validating").addClass("in");
}
setIndicatorEmpty(){
$("#" + this.field + "_validating").removeClass("in");
$("#" + this.field + "_invalid").removeClass("in");
$("#" + this.field + "_valid").removeClass("in");
}
};
class Form
{
constructor(field, description){
this.field = field;
this.description = description;
}
}
class ValueForm extends Form
{
constructor(field, description, default_value="", on_input=null, required=false){
super(field, description);
this.default_value = default_value;
this.error_message = "";
this.required = required;
$('#' + this.field).on('paste keyup', () => {
if (on_input !== null){
on_input();
}
if (this.required) {
this.check();
}
});
if (this.required) {
this.check();
}
}
clearValue() {
$("#" + this.field).val(this.default_value);
}
getValue() {
return $.trim($("#" + this.field).val());
}
setValue(value) {
$("#" + this.field).val(value);
if (this.required) {
this.check();
}
}
setError(error_message){
this.error_message = error_message;
}
clearError(){
this.unhighlight();
}
getError() {
return this.error_message;
}
hasError(){
return this.error_message !== "";
}
highlight(){
$("#" + this.field + "_label").addClass("text-danger");
$("#" + this.field + "_group").addClass("has-error");
}
unhighlight(){
$("#" + this.field + "_label").removeClass("text-danger");
$("#" + this.field + "_group").removeClass("has-error");
}
clear() {
this.clearValue();
this.clearError();
}
check() {
if (this.required && this.getValue() === ""){
this.setError("is empty !");
}
else {
this.setError("");
}
}
}
class FloatForm extends ValueForm
{
constructor(field, description, required, default_value=1)
{
super(field, description, default_value, () => { this.check(); });
this.required = required;
}
check() {
ajax_call(
"POST", getFloatValidatorURL(),
{'value' : this.getValue(), 'required': this.required},
(data) => {
$.each(data, (index, element) => {
if (index === "error"){ this.setError(element.toString()); }
else { this.setError("couldn't be validated : unknown response"); }
});
},
() => { this.setError("couldn't be validated : unable to connect"); }
);
}
setValue(value){
super.setValue(value);
this.check();
}
}
class SbmlIdForm extends HasIndicator(ValueForm)
{
constructor(field, description, default_value="", has_scope=false, scope_field="")
{
super(field, description, default_value, () => { this.check(); });
this.initial_value = "";
// For local parameters, we need to have an extra information : the scope (global, or local to a reaction)
this.hasScope = has_scope;
this.scope_field = scope_field;
this.initial_scope = 0;
this.check();
}
setInitialValue(value){
this.initial_value = value;
}
setInitialScope(scope) {
this.initial_scope = scope;
this.check();
}
getScope() {
return parseInt($("#" + this.scope_field).val());
}
setValue(value) {
super.setValue(value);
this.check();
}
check()
{
let sbml_id = this.getValue();
let scope;
if (this.hasScope){ scope = this.getScope(); }
if (sbml_id !== "")
{
// We actually only need to check
if (
// If there is no scope, but the value has been changed
(!this.hasScope && this.initial_value !== sbml_id)
// Or if there is a scope, and either the value or the scope has been changed
|| (this.hasScope && (this.initial_value !== sbml_id || this.initial_scope !== scope))
){
this.setIndicatorValidating();
let post_data;
if (!this.hasScope){
post_data = {'sbml_id': sbml_id };}
else{
post_data = {'sbml_id': sbml_id, 'reaction_id': scope};}
ajax_call(
"POST", getSbmlIdValidatorURL(),
post_data,
(data) => {
$.each(data, (index, element) => {
if (index === 'error')
{
this.setError(element.toString());
if (element === "") {
this.setIndicatorValid();
} else {
this.setIndicatorInvalid();
}
}
else
{
this.setError("couldn't be verified : unknown error");
this.setIndicatorInvalid();
}
});
},
() => {
this.setError("couldn't be verified : connection failed.");
this.setIndicatorInvalid();
}
);
}
// Otherwise no need to check, it's valid
else { this.setIndicatorValid(); this.setError("");}//super.clearError(); }
}
else
{
this.setError("is empty !");
this.setIndicatorInvalid();
}
}
clear()
{
super.clear();
// super.setIndicatorEmpty();
this.check();
super.unhighlight();
this.initial_scope = 0;
}
}
class MathForm extends HasIndicator(ValueForm)
{
constructor(field, description, default_value="", required=false)
{
super(field, description, default_value);
this.required = required;
this.scope = -1;
$("#" + this.field).on('paste keyup', () => { this.check(); });
}
setScope(scope){
this.scope = scope;
}
check()
{
this.setIndicatorValidating();
if (this.getValue() === "") {
if (this.required) {
this.setError("is empty !");
this.setIndicatorInvalid();
}
else{
this.setIndicatorEmpty();
}
} else {
let post_data;
if (this.scope >= 0){
post_data = {'math': this.getValue(), 'scope': this.scope}
} else {
post_data = {'math': this.getValue()}
}
ajax_call(
"POST", getMathValidatorURL(),
post_data,
(data) => {
$.each(data, (index, element) => {
if (index === "valid" && element === "true"){
this.clearError();
this.setIndicatorValid();
} else {
this.setError("is invalid");
this.setIndicatorInvalid();
}
});
},
() => {
this.setError("couldn't be validated : unable to connect");
this.setIndicatorInvalid();
}
);
}
}
clear()
{
super.clear();
}
}
class UsernameForm extends HasIndicator(ValueForm)
{
constructor(field, description, required, default_value="")
{
super(field, description, default_value, () => { this.check(); }, required);
this.required = required;
}
check() {
this.setIndicatorValidating();
ajax_call(
"POST", getUsernameValidatorURL(),
{'username' : this.getValue()},
(data) => {
$.each(data, (index, element) => {
if (index === "error"){
this.setError(element.toString());
if (element === "") {
this.setIndicatorValid();
} else {
this.setIndicatorInvalid();
}
}
else {
this.setError("couldn't be validated : unknown response");
this.setIndicatorInvalid();
}
});
},
() => {
this.setError("couldn't be validated : unable to connect");
this.setIndicatorInvalid();
}
);
}
setValue(value){
super.setValue(value);
this.check();
}
}
class SliderForm extends ValueForm
{
constructor(field, description, default_value=1, post_treatment=null)
{
super(field, description, default_value);
this.disabled = false;
this.post_treatment = post_treatment;
}
getValue()
{
return $('#' + this.field).prop('checked');
}
setValue(value){
if (parseInt(value) === 1){
this.switch_on();
} else {
this.switch_off();
}
}
switch_on()
{
if (!this.disabled) {
$('#' + this.field).prop('checked', true);
if (this.post_treatment !== null){
this.post_treatment();
}
}
}
switch_off()
{
if (!this.disabled){
$('#' + this.field).prop('checked', false);
if (this.post_treatment !== null){
this.post_treatment();
}
}
}
disable()
{
this.disabled = true;
}
enable()
{
this.disabled = false;
}
toggle()
{
console.log("toggling");
if (this.getValue()) {
this.switch_off();
} else {
this.switch_on();
}
}
clear()
{
if (this.default_value) {
this.switch_on();
} else {
this.switch_off();
}
}
}
class Dropdown extends ValueForm {
constructor(field, description="", post_treatment=null, default_value="", default_label="Choose an item", required=false) {
super(field, description, default_value);
this.default_label = default_label;
this.required = required;
this.post_treatment = post_treatment;
$("#" + this.field + "_list li").on('click', (element) =>
{
this.clearError();
this.setLabel($(element.currentTarget).text());
this.setValue($(element.currentTarget).index());
if (post_treatment !== null) {
post_treatment();
}
if (this.required){
this.check();
}
});
// Initialize error
if (this.required){
this.check();
}
}
setLabel(label){
$("#" + this.field + "_label").html(label);
}
setValue(value){
$("#" + this.field + "_value").val(value);
}
getLabel(){
return $("#" + this.field + "_label").html();
}
getValue(){
return parseInt($("#" + this.field + "_value").val());
}
clear(){
this.setLabel(this.default_label);
this.setValue(this.default_value);
}
check(){
if (this.required && Number.isNaN(this.getValue())){
this.setError("isn't selected !");
}
else {
this.setError("");
}
}
setList(list) {
let ul_element = $("#" + this.field + "_list");
ul_element.empty();
for (const value of list) {
ul_element.append(
$("<li>").append(
$("<a>").attr('href', '#').text(value)
)
);
}
$("#" + this.field + "_list li").on('click', (element) =>
{
this.clearError();
this.setLabel($(element.currentTarget).text());
this.setValue($(element.currentTarget).index());
if (this.post_treatment !== null) {
this.post_treatment();
}
if (this.required){
this.check();
}
});
}
hide()
{
$("#" + this.field + "_loaded").removeClass("in");
$("#" + this.field + "_loading_failed").removeClass("in");
$("#" + this.field + "_loading").removeClass("in");
}
showLoading()
{
$("#" + this.field + "_loaded").removeClass("in");
$("#" + this.field + "_loading_failed").removeClass("in");
$("#" + this.field + "_loading").addClass("in");
}
showLoaded()
{
$("#" + this.field + "_loading").removeClass("in");
$("#" + this.field + "_loading_failed").removeClass("in");
$("#" + this.field + "_loaded").addClass("in");
}
showLoadingFailed(){
$("#" + this.field + "_loading").removeClass("in");
$("#" + this.field + "_loaded").removeClass("in");
$("#" + this.field + "_loading_failed").addClass("in");
}
}
class NoneDropdown extends Dropdown {
constructor(field, description="", post_treatment=null, default_value="", default_label="Choose an item", required=false) {
super(field, description, post_treatment, default_value, default_label, required);
$("#" + this.field + "_list li").on('click', (element) =>
{
this.clearError();
this.setLabel($(element.currentTarget).text());
this.setValue($(element.currentTarget).index()-2);
if (post_treatment !== null) {
post_treatment();
}
if (this.required){
this.check();
}
});
}
}
class EditableInput extends ValueForm
{
constructor(field) {
super(field);
this.field = field;
$("#" + this.field + "_edit").on('click', () => { this.edit_on(); });
$("#" + this.field + "_edit_cancel").on('click', () => { this.edit_off(); });
}
edit_on() {
$("#" + this.field + "_edit_on").addClass("in");
$("#" + this.field + "_edit_off").removeClass("in");
$("#" + this.field + "_edit_off_actions").addClass("in");
$("#" + this.field + "_edit_on_actions").removeClass("in");
}
edit_off() {
$("#" + this.field + "_edit_off").addClass("in");
$("#" + this.field + "_edit_on").removeClass("in");
$("#" + this.field + "_edit_on_actions").addClass("in");
$("#" + this.field + "_edit_off_actions").removeClass("in");
}
validate() { }
}
class SBOTermInput extends EditableInput
{
constructor(field)
{
super(field);
}
setValue(value) {
$("#" + this.field).val(value);
}
setName(name){
$("#" + this.field + "_name").html(name);
}
setLink(link){
if (link !== ""){
$("#" + this.field + "_link").attr("href", "http://www.ebi.ac.uk/sbo/main/display?nodeId=" + link);
} else {
$("#" + this.field + "_link").removeAttr("href");
}
}
resolve()
{
ajax_call(
"POST", getSBOTermURL(),
{'sboterm': this.getValue()},
(data) =>
{
$.each(data, (index, element) =>
{
if (index === "name")
{
this.setName(element.toString());
this.setLink(this.getValue());
}
});
super.edit_off();
},
() => { console.log("resolve sbo failed"); }
);
}
}
class ListForm extends Form{
constructor(field, description, parent_form_name, form_name, post_treatment=null, removable=true, editable=false) {
super(field, description);
this.field = field;
this.description = description;
this.parent_form_name = parent_form_name;
this.form_name = form_name;
this.index = 0;
this.post_treatment = post_treatment;
this.removable = removable;
this.editable = editable;
this.objects = [];
// this.error_messages = [];
// this.error_objects = [];
}
add(content="", script="")
{
if (this.removable || this.editable)
{
let buttons = $("<div>").attr({'class': 'form-inline pull-right'});
if (this.editable){
buttons.append(
$("<button>").attr({
'type': 'button',
'onclick': this.parent_form_name + "." + this.form_name + ".edit(" + this.index + ")",
'class': 'btn btn-primary btn-xs'
})
.append(
$("<span>").attr({
'class': 'glyphicon glyphicon-pencil'
})
)
);
}
if (this.removable){
if (this.editable) {
buttons.append(" ");
}
buttons.append(
$("<button>").attr({
'type': 'button',
'onclick': this.parent_form_name + "." + this.form_name + ".remove(" + this.index + ")",
'class': 'btn btn-danger btn-xs'
})
.append(
$("<span>").attr({
'class': 'glyphicon glyphicon-remove'
})
)
);
}
$("#body_" + this.field + "s").append(
$("<tr>").attr({'class': 'row', 'id': this.field + "_" + this.index.toString() + "_tr"}).append(
content,
$("<td>").attr({'class': 'col-xs-2 text-right'}).append(buttons),
$("<script>").attr('type', 'application/javascript').text(script)
)
);
} else {
$("#body_" + this.field + "s").append(
$("<tr>").attr({'class': 'row', 'id': this.field + "_" + this.index.toString() + "_tr"}).append(
content,
$("<script>").attr('type', 'application/javascript')
.text(script)
)
);
}
this.index++;
}
remove(element_id)
{
$("#" + this.field + "_" + element_id + "_tr").remove();
}
edit(element_id)
{
}
update()
{
if (this.post_treatment !== null) {
this.post_treatment();
}
}
clear()
{
$("#body_" + this.field + "s").empty();
this.index = 0;
this.error_messages = [];
}
hasError()
{
for (const i_object in this.objects){
if (this.objects[i_object].hasError()){
return true;
}
}
return false;
}
clearError()
{
for (const i_object in this.objects){
this.objects[i_object].clearError();
}
}
}
class FormGroup {
constructor(error_field="error_modal")
{
this.error_field = error_field;
this.list = [];
this.listErrorChecking = [];
this.nb_errors = 0;
}
addForm(form, error_checking=false) {
this.list.push(form);
this.listErrorChecking.push(error_checking);
}
addError(form)
{
if (form instanceof ListForm){
for (const i_error in form.objects){
if (form.objects[i_error].hasError()){
this.nb_errors++;
form.objects[i_error].highlight();
this.addGlobalError(
form.objects[i_error].field,
form.objects[i_error].description + " " + form.objects[i_error].error_message
);
}
}
} else {
this.nb_errors++;
form.highlight();
this.addGlobalError(form.field, form.description + " " + form.error_message);
}
}
addGlobalError(field, message)
{
if ($("#" + this.error_field).children().length === 0)
{
$("#" + this.error_field).append(
"<div class=\"alert alert-danger fade in\" id=\"" + this.error_field + "_list\">\
<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>\
</div>"
);
}
if ($("#" + this.error_field + "_list").find("#error_message_" + field).length === 0)
{
$("#" + this.error_field + "_list").append(
"<span id=\"error_message_" + field + "\">\
<strong>Error : </strong>" + message + "\
</span><br/>"
);
}
this.nb_errors++;
}
removeForm(form){
let t_index = this.list.indexOf(form);
if (t_index > -1){
this.list.splice(t_index, 1);
this.listErrorChecking.splice(t_index, 1);
}
}
clearErrors()
{
for (let [index, form] of this.list.entries()) {
if (this.listErrorChecking[index]) {
form.clearError();
}
}
$("#" + this.error_field).empty();
this.nb_errors = 0;
}
checkErrors() {
this.clearErrors();
for (let [index, form] of this.list.entries())
{
if (this.listErrorChecking[index]){
if (form.hasError()){
this.addError(form);
}
}
}
}
clearForms() {
this.clearErrors();
for (let form of this.list) {
form.clear();
}
}
}
class ModalForm extends FormGroup
{
constructor(field, description) {
super();
this.field = field;
this.description = description;
}
new()
{
$("#" + this.field + "_title").html("New " + this.description);
this.clearForms();
$('#' + this.field).modal('show');
}
load(load_function)
{
$("#" + this.field + "_title").html("Edit " + this.description);
load_function;
$('#' + this.field).modal('show');
}
save() {
this.checkErrors();
if (this.nb_errors == 0)
{
$("#" + this.field).modal("hide");
}
return (this.nb_errors == 0);
}
}
|
msreis/SigNetSim
|
signetsim/static/js/forms.js
|
JavaScript
|
agpl-3.0
| 24,881
|
/*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bisq.core.btc.wallet;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.KeyChainGroup;
import java.security.SecureRandom;
class BisqKeyChainGroup extends KeyChainGroup {
private final boolean useBitcoinDeterministicKeyChain;
public boolean isUseBitcoinDeterministicKeyChain() {
return useBitcoinDeterministicKeyChain;
}
public BisqKeyChainGroup(NetworkParameters params, @SuppressWarnings("SameParameterValue") boolean useBitcoinDeterministicKeyChain) {
super(params);
this.useBitcoinDeterministicKeyChain = useBitcoinDeterministicKeyChain;
}
public BisqKeyChainGroup(NetworkParameters params, DeterministicKeyChain chain, boolean useBitcoinDeterministicKeyChain) {
super(params, chain);
this.useBitcoinDeterministicKeyChain = useBitcoinDeterministicKeyChain;
}
@Override
public void createAndActivateNewHDChain() {
DeterministicKeyChain chain = useBitcoinDeterministicKeyChain ? new BtcDeterministicKeyChain(new SecureRandom()) : new BisqDeterministicKeyChain(new SecureRandom());
addAndActivateHDChain(chain);
}
}
|
sakazz/exchange
|
core/src/main/java/io/bisq/core/btc/wallet/BisqKeyChainGroup.java
|
Java
|
agpl-3.0
| 1,884
|
#!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# 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 Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import sys
import os
import imp
import subprocess
import re
import json
import pprint
import shutil
import copy
import StringIO
import logging
import itertools
import numpy
import time
import math
import uuid
import tempfile
from pkg_resources import resource_filename
from optparse import OptionParser
from nupic.database.ClientJobsDAO import ClientJobsDAO
from nupic.support import configuration, initLogging
from nupic.support.unittesthelpers.testcasebase import (unittest,
TestCaseBase as HelperTestCaseBase)
from nupic.swarming import HypersearchWorker
from nupic.swarming.api import getSwarmModelParams, createAndStartSwarm
from nupic.swarming.hypersearch.utils import generatePersistentJobGUID
from nupic.swarming.DummyModelRunner import OPFDummyModelRunner
DEFAULT_JOB_TIMEOUT_SEC = 60 * 2
# Filters _debugOut messages
g_debug = True
# Our setUpModule entry block sets this to an instance of MyTestEnvironment()
g_myEnv = None
# These are the args after using the optparse
# This value for the swarm maturity window gives more repeatable results for
# unit tests that use multiple workers
g_repeatableSwarmMaturityWindow = 5
class MyTestEnvironment(object):
# =======================================================================
def __init__(self):
# Save all command line options
self.options = _ArgParser.parseArgs()
# Create the path to our source experiments
thisFile = __file__
testDir = os.path.split(os.path.abspath(thisFile))[0]
self.testSrcExpDir = os.path.join(testDir, 'experiments')
self.testSrcDataDir = os.path.join(testDir, 'data')
return
class ExperimentTestBaseClass(HelperTestCaseBase):
def setUp(self):
""" Method called to prepare the test fixture. This is called by the
unittest framework immediately before calling the test method; any exception
raised by this method will be considered an error rather than a test
failure. The default implementation does nothing.
"""
pass
def tearDown(self):
""" Method called immediately after the test method has been called and the
result recorded. This is called even if the test method raised an exception,
so the implementation in subclasses may need to be particularly careful
about checking internal state. Any exception raised by this method will be
considered an error rather than a test failure. This method will only be
called if the setUp() succeeds, regardless of the outcome of the test
method. The default implementation does nothing.
"""
# Reset our log items
self.resetExtraLogItems()
def shortDescription(self):
""" Override to force unittest framework to use test method names instead
of docstrings in the report.
"""
return None
def _printTestHeader(self):
""" Print out what test we are running
"""
print "###############################################################"
print "Running test: %s.%s..." % (self.__class__, self._testMethodName)
def _setDataPath(self, env):
""" Put the path to our datasets int the NTA_DATA_PATH variable which
will be used to set the environment for each of the workers
Parameters:
---------------------------------------------------------------------
env: The current environment dict
"""
assert env is not None
# If already have a path, concatenate to it
if "NTA_DATA_PATH" in env:
newPath = "%s:%s" % (env["NTA_DATA_PATH"], g_myEnv.testSrcDataDir)
else:
newPath = g_myEnv.testSrcDataDir
env["NTA_DATA_PATH"] = newPath
def _launchWorkers(self, cmdLine, numWorkers):
""" Launch worker processes to execute the given command line
Parameters:
-----------------------------------------------
cmdLine: The command line for each worker
numWorkers: number of workers to launch
retval: list of workers
"""
workers = []
for i in range(numWorkers):
stdout = tempfile.TemporaryFile()
stderr = tempfile.TemporaryFile()
p = subprocess.Popen(cmdLine, bufsize=1, env=os.environ, shell=True,
stdin=None, stdout=stdout, stderr=stderr)
workers.append(p)
return workers
def _getJobInfo(self, cjDAO, workers, jobID):
""" Return the job info for a job
Parameters:
-----------------------------------------------
cjDAO: client jobs database instance
workers: list of workers for this job
jobID: which job ID
retval: job info
"""
# Get the job info
jobInfo = cjDAO.jobInfo(jobID)
# Since we're running outside of the Nupic engine, we launched the workers
# ourself, so see how many are still running and jam the correct status
# into the job info. When using the Nupic engine, it would do this
# for us.
runningCount = 0
for worker in workers:
retCode = worker.poll()
if retCode is None:
runningCount += 1
if runningCount > 0:
status = ClientJobsDAO.STATUS_RUNNING
else:
status = ClientJobsDAO.STATUS_COMPLETED
jobInfo = jobInfo._replace(status=status)
if status == ClientJobsDAO.STATUS_COMPLETED:
jobInfo = jobInfo._replace(
completionReason=ClientJobsDAO.CMPL_REASON_SUCCESS)
return jobInfo
def _generateHSJobParams(self,
expDirectory=None,
hsImp='v2',
maxModels=2,
predictionCacheMaxRecords=None,
dataPath=None,
maxRecords=10):
"""
This method generates a canned Hypersearch Job Params structure based
on some high level options
Parameters:
---------------------------------------------------------------------
predictionCacheMaxRecords:
If specified, determine the maximum number of records in
the prediction cache.
dataPath: When expDirectory is not specified, this is the data file
to be used for the operation. If this value is not specified,
it will use the /extra/qa/hotgym/qa_hotgym.csv.
"""
if expDirectory is not None:
descriptionPyPath = os.path.join(expDirectory, "description.py")
permutationsPyPath = os.path.join(expDirectory, "permutations.py")
permutationsPyContents = open(permutationsPyPath, 'rb').read()
descriptionPyContents = open(descriptionPyPath, 'rb').read()
jobParams = {'persistentJobGUID' : generatePersistentJobGUID(),
'permutationsPyContents': permutationsPyContents,
'descriptionPyContents': descriptionPyContents,
'maxModels': maxModels,
'hsVersion': hsImp}
if predictionCacheMaxRecords is not None:
jobParams['predictionCacheMaxRecords'] = predictionCacheMaxRecords
else:
# Form the stream definition
if dataPath is None:
dataPath = resource_filename("nupic.data",
os.path.join("extra", "qa", "hotgym",
"qa_hotgym.csv"))
streamDef = dict(
version = 1,
info = "TestHypersearch",
streams = [
dict(source="file://%s" % (dataPath),
info=dataPath,
columns=["*"],
first_record=0,
last_record=maxRecords),
],
)
# Generate the experiment description
expDesc = {
"predictionField": "consumption",
"streamDef": streamDef,
"includedFields": [
{ "fieldName": "gym",
"fieldType": "string"
},
{ "fieldName": "consumption",
"fieldType": "float",
"minValue": 0,
"maxValue": 200,
},
],
"iterationCount": maxRecords,
"resetPeriod": {
'weeks': 0,
'days': 0,
'hours': 8,
'minutes': 0,
'seconds': 0,
'milliseconds': 0,
'microseconds': 0,
},
}
jobParams = {
"persistentJobGUID": _generatePersistentJobGUID(),
"description":expDesc,
"maxModels": maxModels,
"hsVersion": hsImp,
}
if predictionCacheMaxRecords is not None:
jobParams['predictionCacheMaxRecords'] = predictionCacheMaxRecords
return jobParams
def _runPermutationsLocal(self, jobParams, loggingLevel=logging.INFO,
env=None, waitForCompletion=True,
continueJobId=None, ignoreErrModels=False):
""" This runs permutations on the given experiment using just 1 worker
in the current process
Parameters:
-------------------------------------------------------------------
jobParams: filled in job params for a hypersearch
loggingLevel: logging level to use in the Hypersearch worker
env: if not None, this is a dict of environment variables
that should be sent to each worker process. These can
aid in re-using the same description/permutations file
for different tests.
waitForCompletion: If True, wait for job to complete before returning
If False, then return resultsInfoForAllModels and
metricResults will be None
continueJobId: If not None, then this is the JobId of a job we want
to continue working on with another worker.
ignoreErrModels: If true, ignore erred models
retval: (jobId, jobInfo, resultsInfoForAllModels, metricResults)
"""
print
print "=================================================================="
print "Running Hypersearch job using 1 worker in current process"
print "=================================================================="
# Plug in modified environment variables
if env is not None:
saveEnvState = copy.deepcopy(os.environ)
os.environ.update(env)
# Insert the job entry into the database in the pre-running state
cjDAO = ClientJobsDAO.get()
if continueJobId is None:
jobID = cjDAO.jobInsert(client='test', cmdLine='<started manually>',
params=json.dumps(jobParams),
alreadyRunning=True, minimumWorkers=1, maximumWorkers=1,
jobType = cjDAO.JOB_TYPE_HS)
else:
jobID = continueJobId
# Command line args.
args = ['ignoreThis', '--jobID=%d' % (jobID),
'--logLevel=%d' % (loggingLevel)]
if continueJobId is None:
args.append('--clearModels')
# Run it in the current process
try:
HypersearchWorker.main(args)
# The dummy model runner will call sys.exit(0) when
# NTA_TEST_sysExitAfterNIterations is set
except SystemExit:
pass
except:
raise
# Restore environment
if env is not None:
os.environ = saveEnvState
# ----------------------------------------------------------------------
# Make sure all models completed successfully
models = cjDAO.modelsGetUpdateCounters(jobID)
modelIDs = [model.modelId for model in models]
if len(modelIDs) > 0:
results = cjDAO.modelsGetResultAndStatus(modelIDs)
else:
results = []
metricResults = []
for result in results:
if result.results is not None:
metricResults.append(json.loads(result.results)[1].values()[0])
else:
metricResults.append(None)
if not ignoreErrModels:
self.assertNotEqual(result.completionReason, cjDAO.CMPL_REASON_ERROR,
"Model did not complete successfully:\n%s" % (result.completionMsg))
# Print worker completion message
jobInfo = cjDAO.jobInfo(jobID)
return (jobID, jobInfo, results, metricResults)
def _runPermutationsCluster(self, jobParams, loggingLevel=logging.INFO,
maxNumWorkers=4, env=None,
waitForCompletion=True, ignoreErrModels=False,
timeoutSec=DEFAULT_JOB_TIMEOUT_SEC):
""" Given a prepared, filled in jobParams for a hypersearch, this starts
the job, waits for it to complete, and returns the results for all
models.
Parameters:
-------------------------------------------------------------------
jobParams: filled in job params for a hypersearch
loggingLevel: logging level to use in the Hypersearch worker
maxNumWorkers: max # of worker processes to use
env: if not None, this is a dict of environment variables
that should be sent to each worker process. These can
aid in re-using the same description/permutations file
for different tests.
waitForCompletion: If True, wait for job to complete before returning
If False, then return resultsInfoForAllModels and
metricResults will be None
ignoreErrModels: If true, ignore erred models
retval: (jobID, jobInfo, resultsInfoForAllModels, metricResults)
"""
print
print "=================================================================="
print "Running Hypersearch job on cluster"
print "=================================================================="
# --------------------------------------------------------------------
# Submit the job
if env is not None and len(env) > 0:
envItems = []
for (key, value) in env.iteritems():
envItems.append("export %s=%s" % (key, value))
envStr = "%s;" % (';'.join(envItems))
else:
envStr = ''
cmdLine = '%s python -m nupic.swarming.HypersearchWorker ' \
'--jobID={JOBID} --logLevel=%d' \
% (envStr, loggingLevel)
cjDAO = ClientJobsDAO.get()
jobID = cjDAO.jobInsert(client='test', cmdLine=cmdLine,
params=json.dumps(jobParams),
minimumWorkers=1, maximumWorkers=maxNumWorkers,
jobType = cjDAO.JOB_TYPE_HS)
# Launch the workers ourself if necessary (no nupic engine running).
workerCmdLine = '%s python -m nupic.swarming.HypersearchWorker ' \
'--jobID=%d --logLevel=%d' \
% (envStr, jobID, loggingLevel)
workers = self._launchWorkers(cmdLine=workerCmdLine, numWorkers=maxNumWorkers)
print "Successfully submitted new test job, jobID=%d" % (jobID)
print "Each of %d workers executing the command line: " % (maxNumWorkers), \
cmdLine
if not waitForCompletion:
return (jobID, None, None)
if timeoutSec is None:
timeout=DEFAULT_JOB_TIMEOUT_SEC
else:
timeout=timeoutSec
# --------------------------------------------------------------------
# Wait for it to complete
startTime = time.time()
lastUpdate = time.time()
lastCompleted = 0
lastCompletedWithError = 0
lastCompletedAsOrphan = 0
lastStarted = 0
lastJobStatus = "NA"
lastJobResults = None
lastActiveSwarms = None
lastEngStatus = None
modelIDs = []
print "\n%-15s %-15s %-15s %-15s %-15s" % ("jobStatus", "modelsStarted",
"modelsCompleted", "modelErrs", "modelOrphans")
print "-------------------------------------------------------------------"
while (lastJobStatus != ClientJobsDAO.STATUS_COMPLETED) \
and (time.time() - lastUpdate < timeout):
printUpdate = False
if g_myEnv.options.verbosity == 0:
time.sleep(0.5)
# --------------------------------------------------------------------
# Get the job status
jobInfo = self._getJobInfo(cjDAO, workers, jobID)
if jobInfo.status != lastJobStatus:
if jobInfo.status == ClientJobsDAO.STATUS_RUNNING \
and lastJobStatus != ClientJobsDAO.STATUS_RUNNING:
print "# Swarm job now running. jobID=%s" \
% (jobInfo.jobId)
lastJobStatus = jobInfo.status
printUpdate = True
if g_myEnv.options.verbosity >= 1:
if jobInfo.engWorkerState is not None:
activeSwarms = json.loads(jobInfo.engWorkerState)['activeSwarms']
if activeSwarms != lastActiveSwarms:
#print "-------------------------------------------------------"
print ">> Active swarms:\n ", '\n '.join(activeSwarms)
lastActiveSwarms = activeSwarms
print
if jobInfo.results != lastJobResults:
#print "-------------------------------------------------------"
print ">> New best:", jobInfo.results, "###"
lastJobResults = jobInfo.results
if jobInfo.engStatus != lastEngStatus:
print '>> Status: "%s"' % jobInfo.engStatus
print
lastEngStatus = jobInfo.engStatus
# --------------------------------------------------------------------
# Get the list of models created for this job
modelCounters = cjDAO.modelsGetUpdateCounters(jobID)
if len(modelCounters) != lastStarted:
modelIDs = [x.modelId for x in modelCounters]
lastStarted = len(modelCounters)
printUpdate = True
# --------------------------------------------------------------------
# See how many have finished
if len(modelIDs) > 0:
completed = 0
completedWithError = 0
completedAsOrphan = 0
infos = cjDAO.modelsGetResultAndStatus(modelIDs)
for info in infos:
if info.status == ClientJobsDAO.STATUS_COMPLETED:
completed += 1
if info.completionReason == ClientJobsDAO.CMPL_REASON_ERROR:
completedWithError += 1
if info.completionReason == ClientJobsDAO.CMPL_REASON_ORPHAN:
completedAsOrphan += 1
if completed != lastCompleted \
or completedWithError != lastCompletedWithError \
or completedAsOrphan != lastCompletedAsOrphan:
lastCompleted = completed
lastCompletedWithError = completedWithError
lastCompletedAsOrphan = completedAsOrphan
printUpdate = True
# --------------------------------------------------------------------
# Print update?
if printUpdate:
lastUpdate = time.time()
if g_myEnv.options.verbosity >= 1:
print ">>",
print "%-15s %-15d %-15d %-15d %-15d" % (lastJobStatus, lastStarted,
lastCompleted,
lastCompletedWithError,
lastCompletedAsOrphan)
# ========================================================================
# Final total
print "\n<< %-15s %-15d %-15d %-15d %-15d" % (lastJobStatus, lastStarted,
lastCompleted,
lastCompletedWithError,
lastCompletedAsOrphan)
# Success?
jobInfo = self._getJobInfo(cjDAO, workers, jobID)
if not ignoreErrModels:
self.assertEqual (jobInfo.completionReason,
ClientJobsDAO.CMPL_REASON_SUCCESS)
# Get final model results
models = cjDAO.modelsGetUpdateCounters(jobID)
modelIDs = [model.modelId for model in models]
if len(modelIDs) > 0:
results = cjDAO.modelsGetResultAndStatus(modelIDs)
else:
results = []
metricResults = []
for result in results:
if result.results is not None:
metricResults.append(json.loads(result.results)[1].values()[0])
else:
metricResults.append(None)
if not ignoreErrModels:
self.assertNotEqual(result.completionReason, cjDAO.CMPL_REASON_ERROR,
"Model did not complete successfully:\n%s" % (result.completionMsg))
return (jobID, jobInfo, results, metricResults)
def runPermutations(self, expDirectory, hsImp='v2', maxModels=2,
maxNumWorkers=4, loggingLevel=logging.INFO,
onCluster=False, env=None, waitForCompletion=True,
continueJobId=None, dataPath=None, maxRecords=None,
timeoutSec=None, ignoreErrModels=False,
predictionCacheMaxRecords=None, **kwargs):
""" This runs permutations on the given experiment using just 1 worker
Parameters:
-------------------------------------------------------------------
expDirectory: directory containing the description.py and permutations.py
hsImp: which implementation of Hypersearch to use
maxModels: max # of models to generate
maxNumWorkers: max # of workers to use, N/A if onCluster is False
loggingLevel: logging level to use in the Hypersearch worker
onCluster: if True, run on the Hadoop cluster
env: if not None, this is a dict of environment variables
that should be sent to each worker process. These can
aid in re-using the same description/permutations file
for different tests.
waitForCompletion: If True, wait for job to complete before returning
If False, then return resultsInfoForAllModels and
metricResults will be None
continueJobId: If not None, then this is the JobId of a job we want
to continue working on with another worker.
ignoreErrModels: If true, ignore erred models
maxRecords: This value is passed to the function, _generateHSJobParams(),
to represent the maximum number of records to generate for
the operation.
dataPath: This value is passed to the function, _generateHSJobParams(),
which points to the data file for the operation.
predictionCacheMaxRecords:
If specified, determine the maximum number of records in
the prediction cache.
retval: (jobID, jobInfo, resultsInfoForAllModels, metricResults,
minErrScore)
"""
# Put in the path to our datasets
if env is None:
env = dict()
self._setDataPath(env)
# ----------------------------------------------------------------
# Prepare the jobParams
jobParams = self._generateHSJobParams(expDirectory=expDirectory,
hsImp=hsImp, maxModels=maxModels,
maxRecords=maxRecords,
dataPath=dataPath,
predictionCacheMaxRecords=predictionCacheMaxRecords)
jobParams.update(kwargs)
if onCluster:
(jobID, jobInfo, resultInfos, metricResults) \
= self._runPermutationsCluster(jobParams=jobParams,
loggingLevel=loggingLevel,
maxNumWorkers=maxNumWorkers,
env=env,
waitForCompletion=waitForCompletion,
ignoreErrModels=ignoreErrModels,
timeoutSec=timeoutSec)
else:
(jobID, jobInfo, resultInfos, metricResults) \
= self._runPermutationsLocal(jobParams=jobParams,
loggingLevel=loggingLevel,
env=env,
waitForCompletion=waitForCompletion,
continueJobId=continueJobId,
ignoreErrModels=ignoreErrModels)
if not waitForCompletion:
return (jobID, jobInfo, resultInfos, metricResults, None)
# Print job status
print "\n------------------------------------------------------------------"
print "Hadoop completion reason: %s" % (jobInfo.completionReason)
print "Worker completion reason: %s" % (jobInfo.workerCompletionReason)
print "Worker completion msg: %s" % (jobInfo.workerCompletionMsg)
if jobInfo.engWorkerState is not None:
print "\nEngine worker state:"
print "---------------------------------------------------------------"
pprint.pprint(json.loads(jobInfo.engWorkerState))
# Print out best results
minErrScore=None
metricAmts = []
for result in metricResults:
if result is None:
metricAmts.append(numpy.inf)
else:
metricAmts.append(result)
metricAmts = numpy.array(metricAmts)
if len(metricAmts) > 0:
minErrScore = metricAmts.min()
minModelID = resultInfos[metricAmts.argmin()].modelId
# Get model info
cjDAO = ClientJobsDAO.get()
modelParams = cjDAO.modelsGetParams([minModelID])[0].params
print "Model params for best model: \n%s" \
% (pprint.pformat(json.loads(modelParams)))
print "Best model result: %f" % (minErrScore)
else:
print "No models finished"
return (jobID, jobInfo, resultInfos, metricResults, minErrScore)
class OneNodeTests(ExperimentTestBaseClass):
"""
"""
# AWS tests attribute required for tagging via automatic test discovery via
# nosetests
engineAWSClusterTest=True
def setUp(self):
super(OneNodeTests, self).setUp()
if not g_myEnv.options.runInProc:
self.skipTest("Skipping One Node test since runInProc is not specified")
def testSimpleV2(self, onCluster=False, env=None, **kwargs):
"""
Try running simple permutations
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
**kwargs)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
def testDeltaV2(self, onCluster=False, env=None, **kwargs):
""" Try running a simple permutations with delta encoder
Test which tests the delta encoder. Runs a swarm of the sawtooth dataset
With a functioning delta encoder this should give a perfect result
DEBUG: disabled temporarily because this test takes too long!!!
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'delta')
# Test it out
if env is None:
env = dict()
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_TEST_exitAfterNModels"] = str(20)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
**kwargs)
self.assertLess(minErrScore, 0.002)
return
def testSimpleV2NoSpeculation(self, onCluster=False, env=None, **kwargs):
""" Try running a simple permutations
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
speculativeParticles=False,
**kwargs)
self.assertEqual(minErrScore, 20)
self.assertGreater(len(resultInfos), 1)
self.assertLess(len(resultInfos), 350)
return
def testCLAModelV2(self, onCluster=False, env=None, maxModels=2,
**kwargs):
""" Try running a simple permutations using an actual CLA model, not
a dummy
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'dummyV2')
# Test it out
if env is None:
env = dict()
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=maxModels,
**kwargs)
self.assertEqual(len(resultInfos), maxModels)
return
def testCLAMultistepModel(self, onCluster=False, env=None, maxModels=2,
**kwargs):
""" Try running a simple permutations using an actual CLA model, not
a dummy
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simple_cla_multistep')
# Test it out
if env is None:
env = dict()
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=maxModels,
**kwargs)
self.assertEqual(len(resultInfos), maxModels)
return
def testLegacyCLAMultistepModel(self, onCluster=False, env=None, maxModels=2,
**kwargs):
""" Try running a simple permutations using an actual CLA model, not
a dummy. This is a legacy CLA multi-step model that doesn't declare a
separate 'classifierOnly' encoder for the predicted field.
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'legacy_cla_multistep')
# Test it out
if env is None:
env = dict()
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=maxModels,
**kwargs)
self.assertEqual(len(resultInfos), maxModels)
return
def testFilterV2(self, onCluster=False):
""" Try running a simple permutations
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# Don't allow the consumption encoder maxval to get to it's optimum
# value (which is 250). This increases our errScore by +25.
env = dict()
env["NTA_TEST_maxvalFilter"] = '225'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = '6'
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None)
self.assertEqual(minErrScore, 45)
self.assertLess(len(resultInfos), 400)
return
def testLateWorker(self, onCluster=False):
""" Try running a simple permutations where a worker comes in late,
after the some models have already been evaluated
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
env = dict()
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_TEST_exitAfterNModels"] = '100'
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=None,
onCluster=onCluster,
env=env,
waitForCompletion=True,
)
self.assertEqual(len(resultInfos), 100)
# Run another worker the rest of the way
env.pop("NTA_TEST_exitAfterNModels")
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=None,
onCluster=onCluster,
env=env,
waitForCompletion=True,
continueJobId = jobID,
)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
def testOrphanedModel(self, onCluster=False, modelRange=(0,1)):
""" Run a worker on a model for a while, then have it exit before the
model finishes. Then, run another worker, which should detect the orphaned
model.
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# NTA_TEST_numIterations is watched by the dummyModelParams() method of
# the permutations file.
# NTA_TEST_sysExitModelRange is watched by the dummyModelParams() method of
# the permutations file. It tells it to do a sys.exit() after so many
# iterations.
# We increase the swarm maturity window to make our unit tests more
# repeatable. There is an element of randomness as to which model
# parameter combinations get evaluated first when running with
# multiple workers, so this insures that we can find the "best" model
# that we expect to see in our unit tests.
env = dict()
env["NTA_TEST_numIterations"] = '2'
env["NTA_TEST_sysExitModelRange"] = '%d,%d' % (modelRange[0], modelRange[1])
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] \
= '%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=300,
onCluster=onCluster,
env=env,
waitForCompletion=False,
)
# At this point, we should have 1 model, still running
(beg, end) = modelRange
self.assertEqual(len(resultInfos), end)
numRunning = 0
for res in resultInfos:
if res.status == ClientJobsDAO.STATUS_RUNNING:
numRunning += 1
self.assertEqual(numRunning, 1)
# Run another worker the rest of the way, after delaying enough time to
# generate an orphaned model
env["NTA_CONF_PROP_nupic_hypersearch_modelOrphanIntervalSecs"] = '1'
time.sleep(2)
# Here we launch another worker to finish up the job. We set the maxModels
# to 300 (200 something should be enough) in case the orphan detection is
# not working, it will make sure we don't loop for excessively long.
# With orphan detection working, we should detect that the first model
# would never complete, orphan it, and create a new one in the 1st sprint.
# Without orphan detection working, we will wait forever for the 1st sprint
# to finish, and will create a bunch of gen 1, then gen2, then gen 3, etc.
# and gen 0 will never finish, so the swarm will never mature.
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=300,
onCluster=onCluster,
env=env,
waitForCompletion=True,
continueJobId = jobID,
)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
def testOrphanedModelGen1(self):
""" Run a worker on a model for a while, then have it exit before a
model finishes in gen index 2. Then, run another worker, which should detect
the orphaned model.
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testOrphanedModel(modelRange=(10,11))
def testErredModel(self, onCluster=False, modelRange=(6,7)):
""" Run with 1 or more models generating errors
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# We increase the swarm maturity window to make our unit tests more
# repeatable. There is an element of randomness as to which model
# parameter combinations get evaluated first when running with
# multiple workers, so this insures that we can find the "best" model
# that we expect to see in our unit tests.
env = dict()
env["NTA_TEST_errModelRange"] = '%d,%d' % (modelRange[0], modelRange[1])
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] \
= '%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
ignoreErrModels=True
)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
def testJobFailModel(self, onCluster=False, modelRange=(6,7)):
""" Run with 1 or more models generating jobFail exception
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# We increase the swarm maturity window to make our unit tests more
# repeatable. There is an element of randomness as to which model
# parameter combinations get evaluated first when running with
# multiple workers, so this insures that we can find the "best" model
# that we expect to see in our unit tests.
env = dict()
env["NTA_TEST_jobFailErr"] = 'True'
maxNumWorkers = 4
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
maxNumWorkers=maxNumWorkers,
ignoreErrModels=True
)
# Make sure workerCompletionReason was error
self.assertEqual (jobInfo.workerCompletionReason,
ClientJobsDAO.CMPL_REASON_ERROR)
self.assertLess (len(resultInfos), maxNumWorkers+1)
return
def testTooManyErredModels(self, onCluster=False, modelRange=(5,10)):
""" Run with too many models generating errors
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# We increase the swarm maturity window to make our unit tests more
# repeatable. There is an element of randomness as to which model
# parameter combinations get evaluated first when running with
# multiple workers, so this insures that we can find the "best" model
# that we expect to see in our unit tests.
env = dict()
env["NTA_TEST_errModelRange"] = '%d,%d' % (modelRange[0], modelRange[1])
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] \
= '%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
ignoreErrModels=True
)
self.assertEqual (jobInfo.workerCompletionReason,
ClientJobsDAO.CMPL_REASON_ERROR)
return
def testFieldThreshold(self, onCluster=False, env=None, **kwargs):
""" Test minimum field contribution threshold for a field to be included in further sprints
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'field_threshold_temporal')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (0)
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (2)
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (100)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'attendance',
'visitor_winloss'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
self.assertEqual( bestModel.optimizedMetric, 75)
#==========================================================================
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (20)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'attendance',
'home_winloss',
'visitor_winloss'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
assert bestModel.optimizedMetric == 55, bestModel.optimizedMetric
#==========================================================================
# Find best combo possible
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (0.0)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'attendance',
'home_winloss',
'precip',
'timestamp_dayOfWeek',
'timestamp_timeOfDay',
'visitor_winloss'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
assert bestModel.optimizedMetric == 25, bestModel.optimizedMetric
def testSpatialClassification(self, onCluster=False, env=None, **kwargs):
"""
Try running a spatial classification swarm
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'spatial_classification')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
**kwargs)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
# Check the expected field contributions
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
actualFieldContributions = jobResults['fieldContributions']
print "Actual field contributions:", \
pprint.pformat(actualFieldContributions)
expectedFieldContributions = {
'address': 100 * (90.0-30)/90.0,
'gym': 100 * (90.0-40)/90.0,
'timestamp_dayOfWeek': 100 * (90.0-80.0)/90.0,
'timestamp_timeOfDay': 100 * (90.0-90.0)/90.0,
}
for key, value in expectedFieldContributions.items():
self.assertEqual(actualFieldContributions[key], value,
"actual field contribution from field '%s' does not "
"match the expected value of %f" % (key, value))
# Check the expected best encoder combination
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'address',
'gym'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
return
def testAlwaysInputPredictedField(self, onCluster=False, env=None,
**kwargs):
"""
Run a swarm where 'inputPredictedField' is set in the permutations
file. The dummy model for this swarm is designed to give the lowest
error when the predicted field is INCLUDED, so make sure we don't get
this low error
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'input_predicted_field')
# Test it out not requiring the predicted field. This should yield a
# low error score
if env is None:
env = dict()
env["NTA_TEST_inputPredictedField"] = "auto"
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (2)
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
**kwargs)
self.assertEqual(minErrScore, -50)
self.assertLess(len(resultInfos), 350)
# Now, require the predicted field. This should yield a high error score
if env is None:
env = dict()
env["NTA_TEST_inputPredictedField"] = "yes"
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (2)
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
**kwargs)
self.assertEqual(minErrScore, -40)
self.assertLess(len(resultInfos), 350)
return
def testFieldThresholdNoPredField(self, onCluster=False, env=None, **kwargs):
""" Test minimum field contribution threshold for a field to be included
in further sprints when doing a temporal search that does not require
the predicted field.
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'input_predicted_field')
# Test it out without any max field branching in effect
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_TEST_inputPredictedField"] = "auto"
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (0)
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (2)
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (0)
if True:
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Verify the best model and check the field contributions.
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'address',
'gym',
'timestamp_dayOfWeek',
'timestamp_timeOfDay'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
self.assertEqual( bestModel.optimizedMetric, -50)
# Check the field contributions
actualFieldContributions = jobResults['fieldContributions']
print "Actual field contributions:", \
pprint.pformat(actualFieldContributions)
expectedFieldContributions = {
'consumption': 0.0,
'address': 100 * (60.0-40.0)/60.0,
'timestamp_timeOfDay': 100 * (60.0-20.0)/60.0,
'timestamp_dayOfWeek': 100 * (60.0-10.0)/60.0,
'gym': 100 * (60.0-30.0)/60.0}
for key, value in expectedFieldContributions.items():
self.assertEqual(actualFieldContributions[key], value,
"actual field contribution from field '%s' does not "
"match the expected value of %f" % (key, value))
if True:
#==========================================================================
# Now test ignoring all fields that contribute less than 55% to the
# error score. This means we can only use the timestamp_timeOfDay and
# timestamp_dayOfWeek fields.
# This should bring our best error score up to 50-30-40 = -20
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (55)
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (5)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the best model
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'timestamp_dayOfWeek',
'timestamp_timeOfDay'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
self.assertEqual( bestModel.optimizedMetric, -20)
# Check field contributions returned
actualFieldContributions = jobResults['fieldContributions']
print "Actual field contributions:", \
pprint.pformat(actualFieldContributions)
expectedFieldContributions = {
'consumption': 0.0,
'address': 100 * (60.0-40.0)/60.0,
'timestamp_timeOfDay': 100 * (60.0-20.0)/60.0,
'timestamp_dayOfWeek': 100 * (60.0-10.0)/60.0,
'gym': 100 * (60.0-30.0)/60.0}
for key, value in expectedFieldContributions.items():
self.assertEqual(actualFieldContributions[key], value,
"actual field contribution from field '%s' does not "
"match the expected value of %f" % (key, value))
if True:
#==========================================================================
# Now, test using maxFieldBranching to limit the max number of fields to
# 3. This means we can only use the timestamp_timeOfDay, timestamp_dayOfWeek,
# gym fields.
# This should bring our error score to 50-30-40-20 = -40
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (0)
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (3)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the best model
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'gym',
'timestamp_dayOfWeek',
'timestamp_timeOfDay'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
self.assertEqual( bestModel.optimizedMetric, -40)
if True:
#==========================================================================
# Now, test setting max models so that no swarm can finish completely.
# Make sure we get the expected field contributions
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (0)
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (5)
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (0)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=10,
dummyModel={'iterations':200},
**kwargs)
# Get the best model
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'timestamp_dayOfWeek'])
self.assertEqual(params["particleState"]["swarmId"],
expectedSwarmId,
"Actual swarm id = %s\nExpcted swarm id = %s" \
% (params["particleState"]["swarmId"],
expectedSwarmId))
self.assertEqual( bestModel.optimizedMetric, 10)
# Check field contributions returned
actualFieldContributions = jobResults['fieldContributions']
print "Actual field contributions:", \
pprint.pformat(actualFieldContributions)
expectedFieldContributions = {
'consumption': 0.0,
'address': 100 * (60.0-40.0)/60.0,
'timestamp_timeOfDay': 100 * (60.0-20.0)/60.0,
'timestamp_dayOfWeek': 100 * (60.0-10.0)/60.0,
'gym': 100 * (60.0-30.0)/60.0}
class MultiNodeTests(ExperimentTestBaseClass):
"""
Test hypersearch on multiple nodes
"""
# AWS tests attribute required for tagging via automatic test discovery via
# nosetests
engineAWSClusterTest=True
def testSimpleV2(self):
""" Try running a simple permutations
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testSimpleV2(onCluster=True) #, maxNumWorkers=7)
def testDeltaV2(self):
""" Try running a simple permutations
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testDeltaV2(onCluster=True) #, maxNumWorkers=7)
def testSmartSpeculation(self, onCluster=True, env=None, **kwargs):
""" Try running a simple permutations
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'smart_speculation_temporal')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (1)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobInfoStr = cjDAO.jobGetFields(jobID, ['results','engWorkerState'])
jobResultsStr = jobInfoStr[0]
engState = jobInfoStr[1]
engState = json.loads(engState)
swarms = engState["swarms"]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
# Make sure that the only nonkilled models are the ones that would have been
# run without speculation
prefix = 'modelParams|sensorParams|encoders|'
correctOrder = ["A","B","C","D","E","F","G","Pred"]
correctOrder = [prefix + x for x in correctOrder]
for swarm in swarms:
if swarms[swarm]["status"] == 'killed':
swarmId = swarm.split(".")
if(len(swarmId)>1):
# Make sure that something before the last two encoders is in the
# wrong sprint progression, hence why it was killed
# The last encoder is the predicted field and the second to last is
# the current new addition
wrong=0
for i in range(len(swarmId)-2):
if correctOrder[i] != swarmId[i]:
wrong=1
assert wrong==1, "Some of the killed swarms should not have been " \
+ "killed as they are a legal combination."
if swarms[swarm]["status"] == 'completed':
swarmId = swarm.split(".")
if(len(swarmId)>3):
# Make sure that the completed swarms are all swarms that should
# have been run.
# The last encoder is the predicted field and the second to last is
# the current new addition
for i in range(len(swarmId)-3):
if correctOrder[i] != swarmId[i]:
assert False , "Some of the completed swarms should not have " \
"finished as they are illegal combinations"
if swarms[swarm]["status"] == 'active':
assert False , "Some swarms are still active at the end of hypersearch"
pass
def testSmartSpeculationSpatialClassification(self, onCluster=True,
env=None, **kwargs):
""" Test that smart speculation does the right thing with spatial
classification models. This also applies to temporal models where the
predicted field is optional (or excluded) since Hypersearch treats them
the same.
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir,
'smart_speculation_spatial_classification')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (1)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
maxNumWorkers=5,
dummyModel={'iterations':200},
**kwargs)
# Get the worker state
cjDAO = ClientJobsDAO.get()
jobInfoStr = cjDAO.jobGetFields(jobID, ['results','engWorkerState'])
jobResultsStr = jobInfoStr[0]
engState = jobInfoStr[1]
engState = json.loads(engState)
swarms = engState["swarms"]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
# Make sure that the only non-killed models are the ones that would have been
# run without speculation
prefix = 'modelParams|sensorParams|encoders|'
correctOrder = ["A","B","C"]
correctOrder = [prefix + x for x in correctOrder]
for swarm in swarms:
if swarms[swarm]["status"] == 'killed':
swarmId = swarm.split(".")
if(len(swarmId) > 1):
# Make sure that the best encoder is not in this swarm
if correctOrder[0] in swarmId:
raise RuntimeError("Some of the killed swarms should not have been "
"killed as they are a legal combination.")
elif swarms[swarm]["status"] == 'completed':
swarmId = swarm.split(".")
if(len(swarmId) >= 2):
# Make sure that the completed swarms are all swarms that should
# have been run.
for i in range(len(swarmId)-1):
if correctOrder[i] != swarmId[i]:
raise RuntimeError("Some of the completed swarms should not have "
"finished as they are illegal combinations")
elif swarms[swarm]["status"] == 'active':
raise RuntimeError("Some swarms are still active at the end of "
"hypersearch")
def testFieldBranching(self, onCluster=True, env=None, **kwargs):
""" Try running a simple permutations
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'max_branching_temporal')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (4)
env["NTA_CONF_PROP_nupic_hypersearch_min_field_contribution"] = \
'%f' % (-20.0)
env["NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm"] = \
'%d' % (2)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'attendance', 'home_winloss', 'timestamp_dayOfWeek',
'timestamp_timeOfDay', 'visitor_winloss'])
assert params["particleState"]["swarmId"] == expectedSwarmId, \
params["particleState"]["swarmId"]
assert bestModel.optimizedMetric == 432, bestModel.optimizedMetric
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (3)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'attendance', 'home_winloss', 'timestamp_timeOfDay',
'visitor_winloss'])
assert params["particleState"]["swarmId"] == expectedSwarmId, \
params["particleState"]["swarmId"]
assert bestModel.optimizedMetric == 465, bestModel.optimizedMetric
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (5)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'attendance', 'home_winloss', 'precip', 'timestamp_dayOfWeek',
'timestamp_timeOfDay', 'visitor_winloss'])
assert params["particleState"]["swarmId"] == expectedSwarmId, \
params["particleState"]["swarmId"]
assert bestModel.optimizedMetric == 390, bestModel.optimizedMetric
#Find best combo with 3 fields
env["NTA_CONF_PROP_nupic_hypersearch_max_field_branching"] = \
'%d' % (0)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=100,
dummyModel={'iterations':200},
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults["bestModel"]])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = prefix + ('.' + prefix).join([
'attendance', 'daynight', 'visitor_winloss'])
assert params["particleState"]["swarmId"] == expectedSwarmId, \
params["particleState"]["swarmId"]
assert bestModel.optimizedMetric == 406, bestModel.optimizedMetric
return
def testFieldThreshold(self, onCluster=True, env=None, **kwargs):
""" Test minimum field contribution threshold for a field to be included in further sprints
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testFieldThreshold(onCluster=True)
def testFieldContributions(self, onCluster=True, env=None, **kwargs):
""" Try running a simple permutations
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'field_contrib_temporal')
# Test it out
if env is None:
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] = \
'%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
onCluster=onCluster,
env=env,
maxModels=None,
**kwargs)
# Get the field contributions from the hypersearch results dict
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
actualFieldContributions = jobResults['fieldContributions']
print "Actual field contributions:", actualFieldContributions
expectedFieldContributions = {'consumption': 0.0,
'address': 0.0,
'timestamp_timeOfDay': 20.0,
'timestamp_dayOfWeek': 50.0,
'gym': 10.0}
for key, value in expectedFieldContributions.items():
self.assertEqual(actualFieldContributions[key], value,
"actual field contribution from field '%s' does not "
"match the expected value of %f" % (key, value))
return
def testCLAModelV2(self):
""" Try running a simple permutations through a real CLA model
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testCLAModelV2(onCluster=True, maxModels=4)
def testCLAMultistepModel(self):
""" Try running a simple permutations through a real CLA model that
uses multistep
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testCLAMultistepModel(onCluster=True, maxModels=4)
def testLegacyCLAMultistepModel(self):
""" Try running a simple permutations through a real CLA model that
uses multistep
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testLegacyCLAMultistepModel(onCluster=True, maxModels=4)
def testSimpleV2VariableWaits(self):
""" Try running a simple permutations where certain field combinations
take longer to complete, this lets us test that we successfully kill
models in bad swarms that are still running.
"""
self._printTestHeader()
# NTA_TEST_variableWaits and NTA_TEST_numIterations are watched by the
# dummyModelParams() method of the permutations.py file
# NTA_TEST_numIterations
env = dict()
env["NTA_TEST_variableWaits"] ='True'
env["NTA_TEST_numIterations"] = '100'
inst = OneNodeTests('testSimpleV2')
return inst.testSimpleV2(onCluster=True, env=env)
def testOrphanedModel(self, modelRange=(0,2)):
""" Run a worker on a model for a while, then have it exit before the
model finishes. Then, run another worker, which should detect the orphaned
model.
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
# NTA_TEST_numIterations is watched by the dummyModelParams() method of
# the permutations file.
# NTA_TEST_sysExitModelRange is watched by the dummyModelParams() method of
# the permutations file. It tells it to do a sys.exit() after so many
# iterations.
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_TEST_sysExitModelRange"] = '%d,%d' % (modelRange[0], modelRange[1])
env["NTA_CONF_PROP_nupic_hypersearch_modelOrphanIntervalSecs"] = '1'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] \
= '%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=500,
onCluster=True,
env=env,
waitForCompletion=True,
maxNumWorkers=4,
)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 500)
return
def testTwoOrphanedModels(self, modelRange=(0,2)):
""" Test behavior when a worker marks 2 models orphaned at the same time.
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'oneField')
# NTA_TEST_numIterations is watched by the dummyModelParams() method of
# the permutations file.
# NTA_TEST_sysExitModelRange is watched by the dummyModelParams() method of
# the permutations file. It tells it to do a sys.exit() after so many
# iterations.
env = dict()
env["NTA_TEST_numIterations"] = '99'
env["NTA_TEST_delayModelRange"] = '%d,%d' % (modelRange[0], modelRange[1])
env["NTA_CONF_PROP_nupic_hypersearch_modelOrphanIntervalSecs"] = '1'
env["NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow"] \
= '%d' % (g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=100,
onCluster=True,
env=env,
waitForCompletion=True,
maxNumWorkers=4,
)
self.assertEqual(minErrScore, 50)
self.assertLess(len(resultInfos), 100)
return
def testOrphanedModelGen1(self):
""" Run a worker on a model for a while, then have it exit before the
model finishes. Then, run another worker, which should detect the orphaned
model.
"""
self._printTestHeader()
inst = MultiNodeTests(self._testMethodName)
return inst.testOrphanedModel(modelRange=(10,11))
def testOrphanedModelMaxModels(self):
""" Test to make sure that the maxModels parameter doesn't include
orphaned models. Run a test with maxModels set to 2, where one becomes
orphaned. At the end, there should be 3 models in the models table, one
of which will be the new model that adopted the orphaned model
"""
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'dummyV2')
numModels = 5
env = dict()
env["NTA_CONF_PROP_nupic_hypersearch_modelOrphanIntervalSecs"] = '3'
env['NTA_TEST_max_num_models']=str(numModels)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=numModels,
env=env,
onCluster=True,
waitForCompletion=True,
dummyModel={'metricValue': ['25','50'],
'sysExitModelRange': '0, 1',
'iterations': 20,
}
)
cjDB = ClientJobsDAO.get()
self.assertGreaterEqual(len(resultInfos), numModels+1)
completionReasons = [x.completionReason for x in resultInfos]
self.assertGreaterEqual(completionReasons.count(cjDB.CMPL_REASON_EOF), numModels)
self.assertGreaterEqual(completionReasons.count(cjDB.CMPL_REASON_ORPHAN), 1)
def testOrphanedModelConnection(self):
"""Test for the correct behavior when a model uses a different connection id
than what is stored in the db. The correct behavior is for the worker to log
this as a warning and move on to a new model"""
self._printTestHeader()
# -----------------------------------------------------------------------
# Trigger "Using connection from another worker" exception inside
# ModelRunner
# -----------------------------------------------------------------------
expDir = os.path.join(g_myEnv.testSrcExpDir, 'dummy_multi_v2')
numModels = 2
env = dict()
env["NTA_CONF_PROP_nupic_hypersearch_modelOrphanIntervalSecs"] = '1'
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=numModels,
env=env,
onCluster=True,
waitForCompletion=True,
dummyModel={'metricValue': ['25','50'],
'sleepModelRange': '0, 1:5',
'iterations': 20,
}
)
cjDB = ClientJobsDAO.get()
self.assertGreaterEqual(len(resultInfos), numModels,
"%d were run. Expecting %s"%(len(resultInfos), numModels+1))
completionReasons = [x.completionReason for x in resultInfos]
self.assertGreaterEqual(completionReasons.count(cjDB.CMPL_REASON_EOF), numModels)
self.assertGreaterEqual(completionReasons.count(cjDB.CMPL_REASON_ORPHAN), 1)
def testErredModel(self, modelRange=(6,7)):
""" Run a worker on a model for a while, then have it exit before the
model finishes. Then, run another worker, which should detect the orphaned
model.
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testErredModel(onCluster=True)
def testJobFailModel(self):
""" Run a worker on a model for a while, then have it exit before the
model finishes. Then, run another worker, which should detect the orphaned
model.
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testJobFailModel(onCluster=True)
def testTooManyErredModels(self, modelRange=(5,10)):
""" Run a worker on a model for a while, then have it exit before the
model finishes. Then, run another worker, which should detect the orphaned
model.
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testTooManyErredModels(onCluster=True)
def testSpatialClassification(self):
""" Try running a simple permutations
"""
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testSpatialClassification(onCluster=True) #, maxNumWorkers=7)
def testAlwaysInputPredictedField(self):
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testAlwaysInputPredictedField(onCluster=True)
def testFieldThresholdNoPredField(self):
self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testFieldThresholdNoPredField(onCluster=True)
class ModelMaturityTests(ExperimentTestBaseClass):
"""
"""
# AWS tests attribute required for tagging via automatic test discovery via
# nosetests
engineAWSClusterTest=True
def setUp(self):
# Ignore the global hypersearch version setting. Always test hypersearch v2
hsVersion = 2
self.expDir = os.path.join(g_myEnv.testSrcExpDir, 'dummyV%d' %hsVersion)
self.hsImp = "v%d" % hsVersion
self.env = {'NTA_CONF_PROP_nupic_hypersearch_enableModelTermination':'0',
'NTA_CONF_PROP_nupic_hypersearch_enableModelMaturity':'1',
'NTA_CONF_PROP_nupic_hypersearch_maturityMaxSlope':'0.1',
'NTA_CONF_PROP_nupic_hypersearch_enableSwarmTermination':'0',
'NTA_CONF_PROP_nupic_hypersearch_bestModelMinRecords':'0'}
def testMatureInterleaved(self):
""" Test to make sure that the best model continues running even when it has
matured. The 2nd model (constant) will be marked as mature first and will
continue to run till the end. The 2nd model reaches maturity and should
stop before all the records are consumed, and should be the best model
because it has a lower error
"""
self._printTestHeader()
self.expDir = os.path.join(g_myEnv.testSrcExpDir,
'dummy_multi_v%d' % 2)
self.env['NTA_TEST_max_num_models'] = '2'
jobID,_,_,_,_ = self.runPermutations(self.expDir, hsImp=self.hsImp, maxModels=2,
loggingLevel = g_myEnv.options.logLevel,
env = self.env,
onCluster = True,
dummyModel={'metricFunctions':
['lambda x: -10*math.log10(x+1) +100',
'lambda x: 100.0'],
'delay': [2.0,
0.0 ],
'waitTime':[0.05,
0.01],
'iterations':500,
'experimentDirectory':self.expDir,
})
cjDB = ClientJobsDAO.get()
modelIDs, records, completionReasons, matured = \
zip(*self.getModelFields( jobID, ['numRecords',
'completionReason',
'engMatured']))
results = cjDB.jobGetFields(jobID, ['results'])[0]
results = json.loads(results)
self.assertEqual(results['bestModel'], modelIDs[0])
self.assertEqual(records[1], 500)
self.assertTrue(records[0] > 100 and records[0] < 500,
"Model 2 num records: 100 < %d < 500 " % records[1])
self.assertEqual(completionReasons[1], cjDB.CMPL_REASON_EOF)
self.assertEqual(completionReasons[0], cjDB.CMPL_REASON_STOPPED)
self.assertTrue(matured[0], True)
def testConstant(self):
""" Sanity check to make sure that when only 1 model is running, it continues
to run even when it has reached maturity """
self._printTestHeader()
jobID,_,_,_,_ = self.runPermutations(self.expDir, hsImp=self.hsImp, maxModels=1,
loggingLevel = g_myEnv.options.logLevel,
env = self.env,
dummyModel={'metricFunctions':
['lambda x: 100'],
'iterations':350,
'experimentDirectory':self.expDir,
})
cjDB = ClientJobsDAO.get()
modelIDs = cjDB.jobGetModelIDs(jobID)
dbResults = cjDB.modelsGetFields(modelIDs, ['numRecords', 'completionReason',
'engMatured'])
modelIDs = [x[0] for x in dbResults]
records = [x[1][0] for x in dbResults]
completionReasons = [x[1][1] for x in dbResults]
matured = [x[1][2] for x in dbResults]
results = cjDB.jobGetFields(jobID, ['results'])[0]
results = json.loads(results)
self.assertEqual(results['bestModel'], min(modelIDs))
self.assertEqual(records[0], 350)
self.assertEqual(completionReasons[0], cjDB.CMPL_REASON_EOF)
self.assertEqual(matured[0], True)
def getModelFields(self, jobID, fields):
cjDB = ClientJobsDAO.get()
modelIDs = cjDB.jobGetModelIDs(jobID)
modelParams = cjDB.modelsGetFields(modelIDs, ['params']+fields)
modelIDs = [e[0] for e in modelParams]
modelOrders = [json.loads(e[1][0])['structuredParams']['__model_num'] for e in modelParams]
modelFields = []
for f in xrange(len(fields)):
modelFields.append([e[1][f+1] for e in modelParams])
modelInfo = zip(modelOrders, modelIDs, *tuple(modelFields))
modelInfo.sort(key=lambda info:info[0])
return [e[1:] for e in sorted(modelInfo, key=lambda info:info[0])]
class SwarmTerminatorTests(ExperimentTestBaseClass):
"""
"""
# AWS tests attribute required for tagging via automatic test discovery via
# nosetests
engineAWSClusterTest=True
def setUp(self):
self.env = {'NTA_CONF_PROP_nupic_hypersearch_enableModelMaturity':'0',
'NTA_CONF_PROP_nupic_hypersearch_enableModelTermination':'0',
'NTA_CONF_PROP_nupic_hypersearch_enableSwarmTermination':'1',
'NTA_TEST_recordSwarmTerminations':'1'}
def testSimple(self, useCluster=False):
"""Run with one really bad swarm to see if terminator picks it up correctly"""
if not g_myEnv.options.runInProc:
self.skipTest("Skipping One Node test since runInProc is not specified")
self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'swarm_v2')
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=None,
onCluster=useCluster,
env=self.env,
dummyModel={'iterations':200})
cjDB = ClientJobsDAO.get()
jobResultsStr = cjDB.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
terminatedSwarms = jobResults['terminatedSwarms']
swarmMaturityWindow = int(configuration.Configuration.get(
'nupic.hypersearch.swarmMaturityWindow'))
prefix = 'modelParams|sensorParams|encoders|'
for swarm, (generation, scores) in terminatedSwarms.iteritems():
if prefix + 'gym' in swarm.split('.'):
self.assertEqual(generation, swarmMaturityWindow-1)
else:
self.assertEqual(generation, swarmMaturityWindow-1+4)
def testMaturity(self, useCluster=False):
if not g_myEnv.options.runInProc:
self.skipTest("Skipping One Node test since runInProc is not specified")
self._printTestHeader()
self.env['NTA_CONF_PROP_enableSwarmTermination'] = '0'
expDir = os.path.join(g_myEnv.testSrcExpDir, 'swarm_maturity_v2')
(jobID, jobInfo, resultInfos, metricResults, minErrScore) \
= self.runPermutations(expDir,
hsImp='v2',
loggingLevel=g_myEnv.options.logLevel,
maxModels=None,
onCluster=useCluster,
env=self.env,
dummyModel={'iterations':200})
cjDB = ClientJobsDAO.get()
jobResultsStr = cjDB.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
terminatedSwarms = jobResults['terminatedSwarms']
swarmMaturityWindow = int(configuration.Configuration.get(
'nupic.hypersearch.swarmMaturityWindow'))
prefix = 'modelParams|sensorParams|encoders|'
for swarm, (generation, scores) in terminatedSwarms.iteritems():
encoders = swarm.split('.')
if prefix + 'gym' in encoders:
self.assertEqual(generation, swarmMaturityWindow-1 + 3)
elif prefix + 'address' in encoders:
self.assertEqual(generation, swarmMaturityWindow-1)
else:
self.assertEqual(generation, swarmMaturityWindow-1 + 7)
def testSimpleMN(self):
self.testSimple(useCluster=True)
def testMaturityMN(self):
self.testMaturity(useCluster=True)
def getHypersearchWinningModelID(jobID):
"""
Parameters:
-------------------------------------------------------------------
jobID: jobID of successfully-completed Hypersearch job
retval: modelID of the winning model
"""
cjDAO = ClientJobsDAO.get()
jobResults = cjDAO.jobGetFields(jobID, ['results'])[0]
print "Hypersearch job results: %r" % (jobResults,)
jobResults = json.loads(jobResults)
return jobResults['bestModel']
def _executeExternalCmdAndReapStdout(args):
"""
args: Args list as defined for the args parameter in subprocess.Popen()
Returns: result dicionary:
{
'exitStatus':<exit-status-of-external-command>,
'stdoutData':"string",
'stderrData':"string"
}
"""
_debugOut(("_executeExternalCmdAndReapStdout: Starting...\n<%s>") % \
(args,))
p = subprocess.Popen(args,
env=os.environ,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_debugOut(("Process started for <%s>") % (args,))
(stdoutData, stderrData) = p.communicate()
_debugOut(("Process completed for <%s>: exit status=%s, stdoutDataType=%s, " + \
"stdoutData=<%s>, stderrData=<%s>") % \
(args, p.returncode, type(stdoutData), stdoutData, stderrData))
result = dict(
exitStatus = p.returncode,
stdoutData = stdoutData,
stderrData = stderrData,
)
_debugOut(("_executeExternalCmdAndReapStdout for <%s>: result=\n%s") % \
(args, pprint.pformat(result, indent=4)))
return result
def _debugOut(text):
global g_debug
if g_debug:
print text
sys.stdout.flush()
return
def _getTestList():
""" Get the list of tests that can be run from this module"""
suiteNames = [
'OneNodeTests',
'MultiNodeTests',
'ModelMaturityTests',
'SwarmTerminatorTests',
]
testNames = []
for suite in suiteNames:
for f in dir(eval(suite)):
if f.startswith('test'):
testNames.append('%s.%s' % (suite, f))
return testNames
class _ArgParser(object):
"""Class which handles command line arguments and arguments passed to the test
"""
args = []
@classmethod
def _processArgs(cls):
"""
Parse our command-line args/options and strip them from sys.argv
Returns the tuple (parsedOptions, remainingArgs)
"""
helpString = \
"""%prog [options...] [-- unittestoptions...] [suitename.testname | suitename]
Run the Hypersearch unit tests. To see unit test framework options, enter:
python %prog -- --help
Example usages:
python %prog MultiNodeTests
python %prog MultiNodeTests.testOrphanedModel
python %prog -- MultiNodeTests.testOrphanedModel
python %prog -- --failfast
python %prog -- --failfast OneNodeTests.testOrphanedModel
Available suitename.testnames: """
# Update help string
allTests = _getTestList()
for test in allTests:
helpString += "\n %s" % (test)
# ============================================================================
# Process command line arguments
parser = OptionParser(helpString,conflict_handler="resolve")
parser.add_option("--verbosity", default=0, type="int",
help="Verbosity level, either 0, 1, 2, or 3 [default: %default].")
parser.add_option("--runInProc", action="store_true", default=False,
help="Run inProc tests, currently inProc are not being run by default "
" running. [default: %default].")
parser.add_option("--logLevel", action="store", type="int",
default=logging.INFO,
help="override default log level. Pass in an integer value that "
"represents the desired logging level (10=logging.DEBUG, "
"20=logging.INFO, etc.) [default: %default].")
parser.add_option("--hs", dest="hsVersion", default=2, type='int',
help=("Hypersearch version (only 2 supported; 1 was "
"deprecated) [default: %default]."))
return parser.parse_args(args=cls.args)
@classmethod
def parseArgs(cls):
""" Returns the test arguments after parsing
"""
return cls._processArgs()[0]
@classmethod
def consumeArgs(cls):
""" Consumes the test arguments and returns the remaining arguments meant
for unittest.man
"""
return cls._processArgs()[1]
def setUpModule():
print "\nCURRENT DIRECTORY:", os.getcwd()
initLogging(verbose=True)
global g_myEnv
# Setup our environment
g_myEnv = MyTestEnvironment()
if __name__ == '__main__':
# Form the command line for the unit test framework
# Consume test specific arguments and pass remaining to unittest.main
_ArgParser.args = sys.argv[1:]
args = [sys.argv[0]] + _ArgParser.consumeArgs()
# Run the tests if called using python
unittest.main(argv=args)
|
passiweinberger/nupic
|
tests/swarming/nupic/swarming/swarming_test.py
|
Python
|
agpl-3.0
| 101,562
|
/*
* JBILLING CONFIDENTIAL
* _____________________
*
* [2003] - [2012] Enterprise jBilling Software Ltd.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Enterprise jBilling Software.
* The intellectual and technical concepts contained
* herein are proprietary to Enterprise jBilling Software
* and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
package com.sapienter.jbilling.server.provisioning.config;
public class Request implements Comparable<Request> {
private int order = 0;
private String submit = null;
private String rollback = null;
private boolean postResult = false;
private String continueOnType = null;
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getSubmit() {
return submit;
}
public void setSubmit(String submit) {
this.submit = submit;
}
public String getRollback() {
return rollback;
}
public void setRollback(String rollback) {
this.rollback = rollback;
}
public boolean getPostResult() {
return postResult;
}
public void setPostResult(boolean postResult) {
this.postResult = postResult;
}
public String getContinueOnType() {
return continueOnType;
}
public void setContinueOnType(String continueOnType) {
this.continueOnType = continueOnType;
}
public int compareTo(Request other) {
return order - other.order;
}
}
|
liquidJbilling/LT-Jbilling-MsgQ-3.1
|
src/java/com/sapienter/jbilling/server/provisioning/config/Request.java
|
Java
|
agpl-3.0
| 1,677
|
SET @SPID := 400000;
SET @GOID := 400000;
DELETE FROM `creature_spawns` WHERE `id` BETWEEN @SPID+1 AND @SPID+9;
DELETE FROM `gameobject_spawns` WHERE `id` BETWEEN @GOID+1 AND @GOID+58;
CREATE TABLE IF NOT EXISTS `active_event_id` (
`active_event` int(10) unsigned NOT NULL,
`name` text COLLATE latin1_bin NOT NULL,
PRIMARY KEY (`active_event`)
);
DELETE FROM `active_event_id` WHERE `active_event`=36;
|
aikon-com-cn/NoxicDB
|
other/calendar_events/Darkmoon Faire/Elwynn Forest Building/Elwynn Forest Building Despawn.sql
|
SQL
|
agpl-3.0
| 410
|
//#############################################################################
//# #
//# 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.vo.lookups;
import ims.framework.cn.data.TreeModel;
import ims.framework.cn.data.TreeNode;
import ims.vo.LookupInstanceCollection;
import ims.vo.LookupInstVo;
public class PatientProcedureOutcomeCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel
{
private static final long serialVersionUID = 1L;
public void add(PatientProcedureOutcome value)
{
super.add(value);
}
public int indexOf(PatientProcedureOutcome instance)
{
return super.indexOf(instance);
}
public boolean contains(PatientProcedureOutcome instance)
{
return indexOf(instance) >= 0;
}
public PatientProcedureOutcome get(int index)
{
return (PatientProcedureOutcome)super.getIndex(index);
}
public void remove(PatientProcedureOutcome instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public Object clone()
{
PatientProcedureOutcomeCollection newCol = new PatientProcedureOutcomeCollection();
PatientProcedureOutcome item;
for (int i = 0; i < super.size(); i++)
{
item = this.get(i);
newCol.add(new PatientProcedureOutcome(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder()));
}
for (int i = 0; i < newCol.size(); i++)
{
item = newCol.get(i);
if (item.getParent() != null)
{
int parentIndex = this.indexOf(item.getParent());
if(parentIndex >= 0)
item.setParent(newCol.get(parentIndex));
else
item.setParent((PatientProcedureOutcome)item.getParent().clone());
}
}
return newCol;
}
public PatientProcedureOutcome getInstance(int instanceId)
{
return (PatientProcedureOutcome)super.getInstanceById(instanceId);
}
public TreeNode[] getRootNodes()
{
LookupInstVo[] roots = super.getRoots();
TreeNode[] nodes = new TreeNode[roots.length];
System.arraycopy(roots, 0, nodes, 0, roots.length);
return nodes;
}
public PatientProcedureOutcome[] toArray()
{
PatientProcedureOutcome[] arr = new PatientProcedureOutcome[this.size()];
super.toArray(arr);
return arr;
}
public static PatientProcedureOutcomeCollection buildFromBeanCollection(java.util.Collection beans)
{
PatientProcedureOutcomeCollection coll = new PatientProcedureOutcomeCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while(iter.hasNext())
{
coll.add(PatientProcedureOutcome.buildLookup((ims.vo.LookupInstanceBean)iter.next()));
}
return coll;
}
public static PatientProcedureOutcomeCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans)
{
PatientProcedureOutcomeCollection coll = new PatientProcedureOutcomeCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(PatientProcedureOutcome.buildLookup(beans[x]));
}
return coll;
}
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/ValueObjects/src/ims/clinical/vo/lookups/PatientProcedureOutcomeCollection.java
|
Java
|
agpl-3.0
| 4,676
|
package com.telefonica.claudia.slm.recovery;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import com.telefonica.claudia.slm.common.PersistentObject;
import com.telefonica.claudia.slm.naming.DirectoryEntry;
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public abstract class OperationLog implements PersistentObject {
@Id
@GeneratedValue
protected long internalId;
/**
* Identifier of the operation type.
*/
protected String opType;
/**
* List of subjects of the operation.
*/
@OneToMany(fetch=FetchType.EAGER)
protected Set<Subject> subjects = new HashSet<Subject>();
/**
* Current status of the operation. Subclasses may add new types of status.
*/
protected String status;
public final static String STATE_INIT="init";
public final static String STATE_FAILED="failed";
public final static String STATE_SUCCESS="success";
public final static String STATE_WAITING="waiting";
@OneToMany(mappedBy="parent", cascade=CascadeType.MERGE)
protected List<OperationLog> operationList = new ArrayList<OperationLog>();
@ManyToOne
protected OperationLog parent;
//--------------------------------------------------------------------------------
public void setWaiting() {
this.status= STATE_WAITING;
}
public void rollback() {
this.status= STATE_FAILED;
if (parent!=null)
this.parent.rollback();
}
public void commit() {
if (this.status!= STATE_FAILED)
this.status= STATE_SUCCESS;
}
public void addOp(OperationLog op) {
operationList.add(op);
op.setParent(this);
}
public void setOpType(String opType) {
this.opType = opType;
}
public String getOpType() {
return opType;
}
public <T extends DirectoryEntry & PersistentObject > Subject addSubject(T subject) {
Subject sub = new Subject();
sub.setClassName(subject.getClass().getCanonicalName());
sub.setFqn(subject.getFQN().toString());
sub.setId(subject.getObjectId());
subjects.add(sub);
return sub;
}
public String getStatus() {
return status;
}
public long getObjectId() {
return internalId;
}
public void setParent(OperationLog parent) {
this.parent = parent;
}
public OperationLog getParent() {
return parent;
}
public Set<Subject> getSubjects() {
return subjects;
}
public List<OperationLog> getOperations() {
return operationList;
}
}
|
StratusLab/claudia
|
claudia-model/src/main/java/com/telefonica/claudia/slm/recovery/OperationLog.java
|
Java
|
agpl-3.0
| 2,703
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import logging
import os
import signal
import socket
import time
import traceback
from datetime import datetime
from multiprocessing import Process
from os.path import abspath
from os.path import dirname
from os.path import expanduser
from os.path import join
from os.path import realpath
import mock
import pyotp
import requests
import tbselenium.common as cm
from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.remote_connection import LOGGER
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
from sqlalchemy.exc import IntegrityError
from tbselenium.tbdriver import TorBrowserDriver
import journalist_app
import source_app
import tests.utils.env as env
from db import db
from models import Journalist
from sdconfig import config
os.environ["SECUREDROP_ENV"] = "test"
FUNCTIONAL_TEST_DIR = abspath(dirname(__file__))
LOGFILE_PATH = abspath(join(FUNCTIONAL_TEST_DIR, "firefox.log"))
FILES_DIR = abspath(join(dirname(realpath(__file__)), "../..", "tests/files"))
FIREFOX_PATH = "/usr/bin/firefox/firefox"
TBB_PATH = abspath(join(expanduser("~"), ".local/tbb/tor-browser_en-US/"))
os.environ["TBB_PATH"] = TBB_PATH
TBBRC = join(TBB_PATH, "Browser/TorBrowser/Data/Tor/torrc")
LOGGER.setLevel(logging.WARNING)
# https://stackoverflow.com/a/34795883/837471
class alert_is_not_present(object):
""" Expect an alert to not be present."""
def __call__(self, driver):
try:
alert = driver.switch_to.alert
alert.text
return False
except NoAlertPresentException:
return True
class FunctionalTest(object):
use_firefox = False
driver = None
accept_languages = None
_firefox_driver = None
_torbrowser_driver = None
gpg = None
new_totp = None
timeout = 10
secret_message = "These documents outline a major government invasion of privacy."
def _unused_port(self):
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port
def _create_torbrowser_driver(self):
logging.info("Creating TorBrowserDriver")
log_file = open(LOGFILE_PATH, "a")
log_file.write("\n\n[%s] Running Functional Tests\n" % str(datetime.now()))
log_file.flush()
# Don't use Tor when reading from localhost, and turn off private
# browsing. We need to turn off private browsing because we won't be
# able to access the browser's cookies in private browsing mode. Since
# we use session cookies in SD anyway (in private browsing mode all
# cookies are set as session cookies), this should not affect session
# lifetime.
pref_dict = {
"network.proxy.no_proxies_on": "127.0.0.1",
"browser.privatebrowsing.autostart": False,
}
if self.accept_languages is not None:
pref_dict["intl.accept_languages"] = self.accept_languages
self._torbrowser_driver = TorBrowserDriver(
TBB_PATH, tor_cfg=cm.USE_RUNNING_TOR, pref_dict=pref_dict, tbb_logfile_path=LOGFILE_PATH
)
logging.info("Created Tor Browser driver")
def _create_firefox_driver(self, profile=None):
logging.info("Creating Firefox driver")
if profile is None:
profile = webdriver.FirefoxProfile()
if self.accept_languages is not None:
profile.set_preference("intl.accept_languages", self.accept_languages)
profile.update_preferences()
self._firefox_driver = webdriver.Firefox(
firefox_binary=FIREFOX_PATH, firefox_profile=profile
)
self._firefox_driver.set_window_position(0, 0)
self._firefox_driver.set_window_size(1024, 768)
self._firefox_driver.implicitly_wait(self.timeout)
logging.info("Created Firefox driver")
def disable_javascript(self):
self.driver.profile.set_preference("javascript.enabled", False)
def enable_javascript(self):
self.driver.profile.set_preference("javascript.enabled", True)
def switch_to_firefox_driver(self):
self.driver = self._firefox_driver
def switch_to_torbrowser_driver(self):
self.driver = self._torbrowser_driver
def setup(self, session_expiration=30):
env.create_directories()
self.gpg = env.init_gpg()
self.__context = journalist_app.create_app(config).app_context()
self.__context.push()
# Patch the two-factor verification to avoid intermittent errors
self.patcher = mock.patch("models.Journalist.verify_token")
self.mock_journalist_verify_token = self.patcher.start()
self.mock_journalist_verify_token.return_value = True
self.patcher2 = mock.patch("source_app.main.get_entropy_estimate")
self.mock_get_entropy_estimate = self.patcher2.start()
self.mock_get_entropy_estimate.return_value = 8192
signal.signal(signal.SIGUSR1, lambda _, s: traceback.print_stack(s))
env.create_directories()
db.create_all()
# Add our test user
try:
valid_password = "correct horse battery staple profanity oil chewy"
user = Journalist(username="journalist", password=valid_password, is_admin=True)
user.otp_secret = "JHCOGO7VCER3EJ4L"
db.session.add(user)
db.session.commit()
except IntegrityError:
logging.error("Test user already added")
db.session.rollback()
# This user is required for our tests cases to login
self.admin_user = {
"name": "journalist",
"password": ("correct horse battery staple" " profanity oil chewy"),
"secret": "JHCOGO7VCER3EJ4L",
}
self.admin_user["totp"] = pyotp.TOTP(self.admin_user["secret"])
source_port = self._unused_port()
journalist_port = self._unused_port()
self.source_location = "http://127.0.0.1:%d" % source_port
self.journalist_location = "http://127.0.0.1:%d" % journalist_port
# Allow custom session expiration lengths
self.session_expiration = session_expiration
self.source_app = source_app.create_app(config)
self.journalist_app = journalist_app.create_app(config)
def start_source_server(app):
config.SESSION_EXPIRATION_MINUTES = self.session_expiration
app.run(port=source_port, debug=True, use_reloader=False, threaded=True)
def start_journalist_server(app):
app.run(port=journalist_port, debug=True, use_reloader=False, threaded=True)
self.source_process = Process(target=lambda: start_source_server(self.source_app))
self.journalist_process = Process(
target=lambda: start_journalist_server(self.journalist_app)
)
self.source_process.start()
self.journalist_process.start()
for tick in range(30):
try:
requests.get(self.source_location, timeout=1)
requests.get(self.journalist_location, timeout=1)
except Exception:
time.sleep(0.5)
else:
break
self._create_torbrowser_driver()
self._create_firefox_driver()
if self.use_firefox:
self.switch_to_firefox_driver()
else:
self.switch_to_torbrowser_driver()
# Polls the DOM to wait for elements. To read more about why
# this is necessary:
#
# http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-page-load-after-a-click.html
#
# A value of 5 is known to not be enough in some cases, when
# the machine hosting the tests is slow, reason why it was
# raised to 10. Setting the value to 60 or more would surely
# cover even the slowest of machine. However it also means
# that a test failing to find the desired element in the DOM
# will only report failure after 60 seconds which is painful
# for quickly debuging.
#
self.driver.implicitly_wait(self.timeout)
def wait_for_source_key(self, source_name):
filesystem_id = self.source_app.crypto_util.hash_codename(source_name)
def key_available(filesystem_id):
assert self.source_app.crypto_util.getkey(filesystem_id)
self.wait_for(lambda: key_available(filesystem_id), timeout=60)
def teardown(self):
if self._torbrowser_driver:
self._torbrowser_driver.quit()
if self._firefox_driver:
self._firefox_driver.quit()
self.patcher.stop()
env.teardown()
self.source_process.terminate()
self.journalist_process.terminate()
self.__context.pop()
def create_new_totp(self, secret):
self.new_totp = pyotp.TOTP(secret)
def wait_for(self, function_with_assertion, timeout=None):
"""Polling wait for an arbitrary assertion."""
# Thanks to
# http://chimera.labs.oreilly.com/books/1234000000754/ch20.html#_a_common_selenium_problem_race_conditions
if timeout is None:
timeout = self.timeout
start_time = time.time()
while time.time() - start_time < timeout:
try:
return function_with_assertion()
except (AssertionError, WebDriverException):
time.sleep(0.1)
# one more try, which will raise any errors if they are outstanding
return function_with_assertion()
def safe_click_by_id(self, element_id):
WebDriverWait(self.driver, self.timeout).until(
expected_conditions.element_to_be_clickable((By.ID, element_id))
)
el = self.wait_for(lambda: self.driver.find_element_by_id(element_id))
el.location_once_scrolled_into_view
ActionChains(self.driver).move_to_element(el).click().perform()
def safe_click_by_css_selector(self, selector):
WebDriverWait(self.driver, self.timeout).until(
expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, selector))
)
el = self.wait_for(lambda: self.driver.find_element_by_css_selector(selector))
el.location_once_scrolled_into_view
ActionChains(self.driver).move_to_element(el).click().perform()
def safe_click_all_by_css_selector(self, selector, root=None):
if root is None:
root = self.driver
els = self.wait_for(lambda: root.find_elements_by_css_selector(selector))
for el in els:
el.location_once_scrolled_into_view
self.wait_for(lambda: el.is_enabled() and el.is_displayed())
ActionChains(self.driver).move_to_element(el).click().perform()
def _alert_wait(self, timeout=None):
if timeout is None:
timeout = self.timeout
WebDriverWait(self.driver, timeout).until(
expected_conditions.alert_is_present(), "Timed out waiting for confirmation popup."
)
def _alert_accept(self):
self.driver.switch_to.alert.accept()
WebDriverWait(self.driver, self.timeout).until(
alert_is_not_present(), "Timed out waiting for confirmation popup to disappear."
)
def _alert_dismiss(self):
self.driver.switch_to.alert.dismiss()
WebDriverWait(self.driver, self.timeout).until(
alert_is_not_present(), "Timed out waiting for confirmation popup to disappear."
)
|
ehartsuyker/securedrop
|
securedrop/tests/functional/functional_test.py
|
Python
|
agpl-3.0
| 11,846
|
<?php
/*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio 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.
*
* Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
namespace Pydio\Auth\Core;
use Exception;
use Pydio\Core\Model\Context;
use Pydio\Core\PluginFramework\CoreInstanceProvider;
use Pydio\Core\Services\ConfService;
use Pydio\Core\PluginFramework\Plugin;
use Pydio\Core\PluginFramework\PluginsService;
defined('AJXP_EXEC') or die('Access not allowed');
/**
* Config loader overrider
* @package AjaXplorer_Plugins
* @subpackage Core
*/
class CoreAuthLoader extends Plugin implements CoreInstanceProvider
{
/**
* @var AbstractAuthDriver
*/
protected static $authStorageImpl;
/**
* Return this plugin configs, merged with its associated "core" configs.
* @return array
*/
public function getConfigs()
{
$configs = parent::getConfigs();
$configs["ALLOW_GUEST_BROWSING"] = !isSet($_SERVER["HTTP_AJXP_FORCE_LOGIN"]) && ($configs["ALLOW_GUEST_BROWSING"] === "true" || $configs["ALLOW_GUEST_BROWSING"] === true || intval($configs["ALLOW_GUEST_BROWSING"]) == 1);
// FORCE CASE INSENSITIVY FOR SQL BASED DRIVERS
if (isSet($configs["MASTER_INSTANCE_CONFIG"]) && is_array($configs["MASTER_INSTANCE_CONFIG"]) && isSet($configs["MASTER_INSTANCE_CONFIG"]["instance_name"]) && $configs["MASTER_INSTANCE_CONFIG"]["instance_name"] == "auth.sql") {
$configs["CASE_SENSITIVE"] = false;
}
if (isSet($configs["SLAVE_INSTANCE_CONFIG"]) && !empty($configs["SLAVE_INSTANCE_CONFIG"]) && isset($configs["SLAVE_INSTANCE_CONFIG"]["instance_name"]) && $configs["SLAVE_INSTANCE_CONFIG"]["instance_name"] == "auth.sql") {
$configs["CASE_SENSITIVE"] = false;
}
return $configs;
}
/**
* @param PluginsService|null $pluginsServiceInstance
* @return null|AbstractAuthDriver|Plugin
* @throws Exception
*/
public function getImplementation($pluginsServiceInstance = null)
{
if ($pluginsServiceInstance === null) {
$pluginsServiceInstance = PluginsService::getInstance(Context::emptyContext());
}
if (!isSet(self::$authStorageImpl)) {
if (!isSet($this->pluginConf["MASTER_INSTANCE_CONFIG"])) {
throw new Exception("Please set up at least one MASTER_INSTANCE_CONFIG in core.auth options");
}
$masterName = is_array($this->pluginConf["MASTER_INSTANCE_CONFIG"]) ? $this->pluginConf["MASTER_INSTANCE_CONFIG"]["instance_name"] : $this->pluginConf["MASTER_INSTANCE_CONFIG"];
if (is_array($this->pluginConf["SLAVE_INSTANCE_CONFIG"]) && $this->pluginConf["SLAVE_INSTANCE_CONFIG"]["instance_name"] !== $masterName) {
$slaveName = is_array($this->pluginConf["SLAVE_INSTANCE_CONFIG"]) ? $this->pluginConf["SLAVE_INSTANCE_CONFIG"]["instance_name"] : $this->pluginConf["SLAVE_INSTANCE_CONFIG"];
}
if (!empty($slaveName) && !empty($this->pluginConf["MULTI_MODE"])) {
$masterName = str_replace("auth.", "", $masterName);
$slaveName = str_replace("auth.", "", $slaveName);
// Manually set up a multi config
$userBase = $this->pluginConf["MULTI_USER_BASE_DRIVER"];
if ($userBase == "master") $baseName = $masterName;
else if ($userBase == "slave") $baseName = $slaveName;
else $baseName = "";
$mLabel = "";
$sLabel = "";
$separator = "";
$cacheMasters = true;
if (isSet($this->pluginConf["MULTI_MODE"]) && !isSet($this->pluginConf["MULTI_MODE"]["instance_name"])) {
$this->pluginConf["MULTI_MODE"]["instance_name"] = $this->pluginConf["MULTI_MODE"]["group_switch_value"];
}
if ($this->pluginConf["MULTI_MODE"]["instance_name"] == "USER_CHOICE") {
$mLabel = $this->pluginConf["MULTI_MODE"]["MULTI_MASTER_LABEL"];
$sLabel = $this->pluginConf["MULTI_MODE"]["MULTI_SLAVE_LABEL"];
$separator = $this->pluginConf["MULTI_MODE"]["MULTI_USER_ID_SEPARATOR"];
} else {
$cacheMasters = $this->pluginConf["MULTI_MODE"]["CACHE_MASTER_USERS_TO_SLAVE"];
}
$newOptions = array(
"instance_name" => "auth.multi",
"MODE" => $this->pluginConf["MULTI_MODE"]["instance_name"],
"MASTER_DRIVER" => $masterName,
"USER_BASE_DRIVER" => $baseName,
"USER_ID_SEPARATOR" => $separator,
"CACHE_MASTER_USERS_TO_SLAVE" => $cacheMasters,
"DRIVERS" => array(
$masterName => array(
"NAME" => $masterName,
"LABEL" => $mLabel,
"OPTIONS" => $this->pluginConf["MASTER_INSTANCE_CONFIG"]
),
$slaveName => array(
"NAME" => $slaveName,
"LABEL" => $sLabel,
"OPTIONS" => $this->pluginConf["SLAVE_INSTANCE_CONFIG"]
),
)
);
// MERGE BASIC AUTH OPTIONS FROM MASTER
$masterMainAuthOptions = array();
$keys = array("AUTOCREATE_AJXPUSER", "LOGIN_REDIRECT", "AJXP_ADMIN_LOGIN");
if (is_array($this->pluginConf["MASTER_INSTANCE_CONFIG"])) {
foreach ($keys as $key) {
if (isSet($this->pluginConf["MASTER_INSTANCE_CONFIG"][$key])) {
$masterMainAuthOptions[$key] = $this->pluginConf["MASTER_INSTANCE_CONFIG"][$key];
}
}
}
$newOptions = array_merge($newOptions, $masterMainAuthOptions);
self::$authStorageImpl = ConfService::instanciatePluginFromGlobalParams($newOptions, "Pydio\\Auth\\Core\\AbstractAuthDriver", $pluginsServiceInstance);
} else {
self::$authStorageImpl = ConfService::instanciatePluginFromGlobalParams($this->pluginConf["MASTER_INSTANCE_CONFIG"], "Pydio\\Auth\\Core\\AbstractAuthDriver", $pluginsServiceInstance);
}
}
return self::$authStorageImpl;
}
}
|
huzergackl/pydio-core
|
core/src/plugins/core.auth/CoreAuthLoader.php
|
PHP
|
agpl-3.0
| 7,149
|
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package utils_test
import (
"errors"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/juju/feature"
"github.com/juju/juju/testing"
"github.com/juju/juju/utils"
)
type logSuite struct {
testing.BaseSuite
}
var _ = gc.Suite(&logSuite{})
func (*logSuite) TestFlagNotSet(c *gc.C) {
err := errors.New("test error")
err2 := utils.LoggedErrorStack(err)
c.Assert(err, gc.Equals, err2)
c.Assert(c.GetTestLog(), gc.Equals, "")
}
func (s *logSuite) TestFlagSet(c *gc.C) {
s.SetFeatureFlags(feature.LogErrorStack)
err := errors.New("test error")
err2 := utils.LoggedErrorStack(err)
c.Assert(err, gc.Equals, err2)
expected := "ERROR juju.utils error stack:\ntest error"
c.Assert(c.GetTestLog(), jc.Contains, expected)
}
|
cmars/juju
|
utils/logging_test.go
|
GO
|
agpl-3.0
| 854
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.lookupmultiselectioncomponent;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
}
}
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/Core/src/ims/core/forms/lookupmultiselectioncomponent/BaseAccessLogic.java
|
Java
|
agpl-3.0
| 3,946
|
// DATA_TEMPLATE: dom_data
oTest.fnStart( "oLanguage.sLengthMenu" );
$(document).ready( function () {
/* Check the default */
var oTable = $('#example').dataTable();
var oSettings = oTable.fnSettings();
oTest.fnTest(
"Menu language is 'Show _MENU_ entries' by default",
null,
function () { return oSettings.oLanguage.sLengthMenu == "Show _MENU_ entries"; }
);
oTest.fnTest(
"_MENU_ macro is replaced by select menu in DOM",
null,
function () { return $('select', oSettings.aanFeatures.l[0]).length == 1 }
);
oTest.fnTest(
"A label input is used",
null,
function () { return $('label', oSettings.aanFeatures.l[0]).length == 1 }
);
oTest.fnTest(
"Default is put into DOM",
null,
function () {
var anChildren = $('label',oSettings.aanFeatures.l[0])[0].childNodes;
var bReturn =
anChildren[0].nodeValue == "Show " &&
anChildren[2].nodeValue == " entries";
return bReturn;
}
);
oTest.fnTest(
"Menu length language can be defined - no _MENU_ macro",
function () {
oSession.fnRestore();
oTable = $('#example').dataTable( {
"oLanguage": {
"sLengthMenu": "unit test"
}
} );
oSettings = oTable.fnSettings();
},
function () { return oSettings.oLanguage.sLengthMenu == "unit test"; }
);
oTest.fnTest(
"Menu length language definition is in the DOM",
null,
function () {
return $('label', oSettings.aanFeatures.l[0]).text() == "unit test";
}
);
oTest.fnTest(
"Menu length language can be defined - with _MENU_ macro",
function () {
oSession.fnRestore();
oTable = $('#example').dataTable( {
"oLanguage": {
"sLengthMenu": "unit _MENU_ test"
}
} );
oSettings = oTable.fnSettings();
},
function () {
var anChildren = $('label',oSettings.aanFeatures.l[0])[0].childNodes;
var bReturn =
anChildren[0].nodeValue == "unit " &&
anChildren[2].nodeValue == " test";
return bReturn;
}
);
oTest.fnTest(
"Only the _MENU_ macro",
function () {
oSession.fnRestore();
oTable = $('#example').dataTable( {
"oLanguage": {
"sLengthMenu": "_MENU_"
}
} );
oSettings = oTable.fnSettings();
},
function () {
var anChildren = oSettings.aanFeatures.l[0].childNodes;
var bReturn =
anChildren.length == 1 &&
$('select', oSettings.aanFeatures.l[0]).length == 1;
return bReturn;
}
);
oTest.fnComplete();
} );
|
lyan6/genenetwork2
|
wqflask/wqflask/static/new/packages/DataTables/unit_testing/tests_onhold/1_dom/oLanguage.sLengthMenu.js
|
JavaScript
|
agpl-3.0
| 2,401
|
/*
* Copyright (C) 2018 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas 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/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import {Button} from '@instructure/ui-buttons'
import {IconFeedbackLine} from '@instructure/ui-icons'
import {ScreenReaderContent} from '@instructure/ui-a11y'
import I18n from 'i18n!edit_rubricCommentButton'
const CommentButton = ({onClick}) => (
<div>
<Button variant="icon" icon={<IconFeedbackLine />} margin="0 x-small 0 0" onClick={onClick}>
<ScreenReaderContent>{I18n.t('Add Additional Comments')}</ScreenReaderContent>
</Button>
</div>
)
CommentButton.propTypes = {
onClick: PropTypes.func.isRequired
}
export default CommentButton
|
djbender/canvas-lms
|
app/jsx/rubrics/CommentButton.js
|
JavaScript
|
agpl-3.0
| 1,320
|
<?php
class page_socialshareModule_page_uninstall extends page_componentBase_page_uninstall{}
|
xavoctechnocratspvtltd/schoolERP
|
epan-components/socialshareModule/page/uninstall.php
|
PHP
|
agpl-3.0
| 95
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.forms.notes;
public final class FormInfo extends ims.framework.FormInfo
{
private static final long serialVersionUID = 1L;
public FormInfo(Integer formId)
{
super(formId);
}
public String getNamespaceName()
{
return "Clinical";
}
public String getFormName()
{
return "Notes";
}
public int getWidth()
{
return 560;
}
public int getHeight()
{
return 288;
}
public String[] getContextVariables()
{
return new String[] { "_cv_Clinical.HospitalAtNightNotes", "_cv_Clinical.RemoveFromHospitalAtNight" };
}
public String getLocalVariablesPrefix()
{
return "_lv_Clinical.Notes.__internal_x_context__" + String.valueOf(getFormId());
}
public ims.framework.FormInfo[] getComponentsFormInfo()
{
ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[1];
componentsInfo[0] = new ims.core.forms.authoringinfo.FormInfo(102228);
return componentsInfo;
}
public String getImagePath()
{
return "";
}
}
|
IMS-MAXIMS/openMAXIMS
|
Source Library/openmaxims_workspace/Clinical/src/ims/clinical/forms/notes/FormInfo.java
|
Java
|
agpl-3.0
| 3,115
|
//#############################################################################
//# #
//# 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.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseSurgicalOPNotesGeneralDetailsCCImpl extends DomainImpl implements ims.clinical.domain.SurgicalOPNotesGeneralDetailsCC, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validategetSurgicalOpNotesGeneralDetails(ims.core.admin.vo.CareContextRefVo careContextRef)
{
if(careContextRef == null)
throw new ims.domain.exceptions.DomainRuntimeException("The parameter 'careContextRef' of type 'ims.core.admin.vo.CareContextRefVo' cannot be null.");
}
@SuppressWarnings("unused")
public void validatesaveSurgicalOPNotesGeneralDetail(ims.clinical.vo.SurgicalOperationNotesGeneralDetailsVo surgicalOpVo)
{
if(surgicalOpVo == null)
throw new ims.domain.exceptions.DomainRuntimeException("The parameter 'surgicalOpVo' of type 'ims.clinical.vo.SurgicalOperationNotesGeneralDetailsVo' cannot be null.");
}
@SuppressWarnings("unused")
public void validatelistHCPS(ims.core.vo.lookups.HcpDisType type, String nameFilter)
{
}
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/Clinical/src/ims/clinical/domain/base/impl/BaseSurgicalOPNotesGeneralDetailsCCImpl.java
|
Java
|
agpl-3.0
| 2,831
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>AW21 Test.6.4.3 Passed 01</title>
</head>
<body>
<div>
<p class="test-detail">
<span>Does each identical link of type clickable area have the same purpose and target?</span>
</p>
<map id="fake-map1">
<area href="fake-link.html" alt="cliquez ici"/>
</map>
<map id="fake-map2">
<area href="fake-link.html"
alt="cliquez ici"/>
</map>
<p class="test-explanation">Passed : The page contains only two identical clickable area without context and with the same target</p>
</div>
</body>
</html>
|
Tanaguru/Tanaguru
|
rules/accessiweb2.1-testcases/src/main/resources/testcases/AW21/Aw21Rule06043/AW21.Test.06.04.03-1Passed-01.html
|
HTML
|
agpl-3.0
| 957
|
# -*- encoding: utf-8 -*-
from openerp.osv import osv, fields
class LeadToChangeRequestWizard(osv.TransientModel):
"""
wizard to convert a Lead into a Change Request and move the Mail Thread
"""
_name = "crm.lead2cr.wizard"
_inherit = 'crm.partner.binding'
_columns = {
"lead_id": fields.many2one(
"crm.lead", "Lead", domain=[("type", "=", "lead")]
),
# "project_id": fields.many2one("project.project", "Project"),
"change_category_id": fields.many2one(
"change.management.category", "Change Category"
),
}
_defaults = {
"lead_id": lambda self, cr, uid, context=None: context.get('active_id')
}
def action_lead_to_change_request(self, cr, uid, ids, context=None):
# get the wizards and models
wizards = self.browse(cr, uid, ids, context=context)
lead_obj = self.pool["crm.lead"]
cr_obj = self.pool["change.management.change"]
attachment_obj = self.pool['ir.attachment']
for wizard in wizards:
# get the lead to transform
lead = wizard.lead_id
partner = self._find_matching_partner(cr, uid, context=context)
if not partner and (lead.partner_name or lead.contact_name):
partner_ids = lead_obj.handle_partner_assignation(
cr, uid, [lead.id], context=context
)
partner = partner_ids[lead.id]
# create new change request
vals = {
"description": lead.name,
"description_event": lead.description,
"email_from": lead.email_from,
"project_id": lead.project_id.id,
"stakeholder_id": partner,
"author_id": uid,
"change_category_id": wizard.change_category_id.id,
}
change_id = cr_obj.create(cr, uid, vals, context=None)
change = cr_obj.browse(cr, uid, change_id, context=None)
# move the mail thread
lead_obj.message_change_thread(
cr, uid, lead.id, change_id,
"change.management.change", context=context
)
# Move attachments
attachment_ids = attachment_obj.search(
cr, uid,
[('res_model', '=', 'crm.lead'), ('res_id', '=', lead.id)],
context=context
)
attachment_obj.write(
cr, uid, attachment_ids,
{'res_model': 'change.management.change', 'res_id': change_id},
context=context
)
# Archive the lead
lead_obj.write(
cr, uid, [lead.id], {'active': False}, context=context)
# delete the lead
# lead_obj.unlink(cr, uid, [lead.id], context=None)
# return the action to go to the form view of the new CR
view_id = self.pool.get('ir.ui.view').search(
cr, uid,
[
('model', '=', 'change.management.change'),
('name', '=', 'change_form_view')
]
)
return {
'name': 'CR created',
'view_type': 'form',
'view_mode': 'form',
'view_id': view_id,
'res_model': 'change.management.change',
'type': 'ir.actions.act_window',
'res_id': change_id,
'context': context
}
|
mohamedhagag/community-addons
|
crm_change_request/models/change_request.py
|
Python
|
agpl-3.0
| 3,485
|
<script type="text/javascript">
$(document).ready(function ()
{
$('table.classifications_edit').find('.info').click(function()
{
if($('.tree').is(":hidden"))
{
$.get('<?php echo url_for('catalogue/tree?table=lithostratigraphy&id='.$litho->Parent->getId()) ; ?>',function (html){
$('.tree').html(html).slideDown();
});
}
$('.tree').slideUp();
});
});
</script>
<?php include_partial('widgets/list', array('widgets' => $widget_list, 'category' => 'catalogue_lithostratigraphy','eid'=> $form->getObject()->getId(), 'view' => true)); ?>
<?php slot('title', __('View Lithostratigraphic unit')); ?>
<div class="page">
<h1><?php echo __('View Lithostratigraphic unit');?></h1>
<div class="table_view">
<table class="classifications_edit">
<tbody>
<tr>
<th><?php echo $form['name']->renderLabel() ?></th>
<td>
<?php echo $litho->getName(); ?>
</td>
</tr>
<tr>
<th><?php echo $form['local_naming']->renderLabel() ?></th>
<td>
<?php echo ($litho->getLocalNaming()) ? image_tag('checkbox_checked.png', array('alt'=>$litho->getLocalNaming())) : image_tag('checkbox_unchecked.png', array('alt'=>$litho->getLocalNaming()));?>
</td>
</tr>
<tr>
<th><?php echo $form['level_ref']->renderLabel() ?></th>
<td>
<?php echo $litho->Level->getLevelName() ?>
</td>
</tr>
<tr>
<th><?php echo $form['status']->renderLabel() ?></th>
<td>
<?php echo $litho->getStatus() ?>
</td>
</tr>
<tr>
<th><?php echo $form['parent_ref']->renderLabel() ?></th>
<td>
<?php if ($litho->getParentRef() && $litho->Parent->getName() != "-") : ?>
<?php echo link_to(__($litho->Parent->getName()), 'lithostratigraphy/view?id='.$litho->Parent->getId(), array('id' => $litho->Parent->getId())) ?>
<?php echo image_tag('info.png',"title=info class=info");?>
<div class="tree">
</div>
<?php else : ?>
-
<?php endif ; ?>
</td>
</tr>
<tr>
<th><?php echo __("Colour") ?></th>
<td>
<span class='round_color' style="background-color:<?php echo $litho->getColor() ?>"> </span>
</td>
</tr>
<tr>
<td colspan="2"><?php echo image_tag('magnifier.gif');?> <?php echo link_to(__('Search related specimens'),'specimensearch/search', array('class'=>'link_to_search'));?>
<script type="text/javascript">
$(document).ready(function (){
search_data = <?php echo json_encode(array('specimen_search_filters[litho_item_ref]' => $litho->getId(), 'specimen_search_filters[litho_relation]' => 'equal' ));?>;
$('.link_to_search').click(function (event){
event.preventDefault();
postToUrl($(this).attr('href'), search_data);
});
});
</script></td>
</tr>
<?php if($sf_user->isAtLeast(Users::ENCODER)):?>
<tr><td colspan="2"><?php echo image_tag('edit.png');?> <?php echo link_to(__('Edit this item'),'lithostratigraphy/edit?id='.$litho->getId());?></td></tr>
<?php endif;?>
</tbody>
</table>
</div>
<div class="view_mode">
<?php include_partial('widgets/screen', array(
'widgets' => $widgets,
'category' => 'cataloguewidgetview',
'columns' => 1,
'options' => array('eid' => $form->getObject()->getId(), 'table' => 'lithostratigraphy', 'view' => true)
)); ?>
</div>
</div>
|
eMerzh/Darwin
|
apps/backend/modules/lithostratigraphy/templates/viewSuccess.php
|
PHP
|
agpl-3.0
| 3,493
|
---
layout: page
title: Creative Commons DMCA Notice & Takedown Procedure
date: 2007-05-17 11:47:44.000000000 -04:00
categories: []
tags: []
status: publish
type: page
published: true
meta:
single_col: '1'
_edit_last: '47'
_wp_page_template: default
author:
login: alex
email: webmaster+alex@creativecommons.org
display_name: Alex Roberts
first_name: Alex
last_name: Roberts
---
<p>Creative Commons abides by the federal <a href="http://www.copyright.gov/legislation/dmca.pdf">Digital Millennium Copyright Act (DMCA)</a> by responding to notices of alleged infringement that comply with the DMCA and other applicable laws. As part of our response, we may remove or disable access to material residing on a site that is controlled or operated by Creative Commons (such as <a href="http://creativecommons.org/">creativecommons.org</a> or <a href="http://sciencecommons.org/">sciencecommons.org</a>) that is claimed to be infringing, in which case we will make a good-faith attempt to contact the person who submitted the affected material so that they may make a counter notification, also in accordance with the DMCA.</p>
<p>Creative Commons does not control content hosted on third party websites, and cannot remove content from sites it does not own or control. If you are the copyright owner of content hosted on a third party site, and you have not authorized the use of your content, please contact the administrator of that website directly to have the content removed.</p>
<p>Before serving either a Notice of Infringing Material or Counter-Notification, you may wish to contact a lawyer to better understand your rights and obligations under the DMCA and other applicable laws. The following notice requirements are intended to comply with Creative Commons' rights and obligations under the DMCA and, in particular, section 512(c), and do not constitute legal advice.</p>
<p><strong>Notice of Infringing Material</strong></p>
<p>To file a notice of infringing material on a site owned or controlled by Creative Commons (such as <a href="http://creativecommons.org/">creativecommons.org</a> or <a href="http://sciencecommons.org/">sciencecommons.org</a>), please provide a notification containing the following details:</p>
<ol>
<li>Reasonably sufficient details to enable us to identify the work claimed to be infringed or, if multiple works are claimed to be infringed, a representative list of such works (for example: title, author, any registration or tracking number, URL);</li>
<li>Reasonably sufficient detail to enable us to identify and locate the material that is claimed to be infringing (for example a link to the page that contains the material);</li>
<li>Your contact information so that we can contact you (for example, your address, telephone number, email address);</li>
<li>A statement that you have a good faith belief that the use of the material identified in (2) is not authorized by the copyright owner, its agent, or the law;</li>
<li>A statement, under penalty of perjury, that the information in the notification is accurate and that you are authorized to act on behalf of the owner of the exclusive right that is alleged to be infringed.</li>
<li>Your physical or electronic signature.</li>
</ol>
<p>Then send this notice to:</p>
<p>By Mail:</p>
<p><strong>DMCA Agent: Valeria Cavazos</strong><br />
444 Castro Street, Suite 900<br />
Mountain View, CA 94041</p>
<p>By Fax:</p>
<p><strong>Attn: DMCA Agent, Creative Commons</strong><br />
+1 650.965.1605</p>
<p>By Email:</p>
<p>Email: <a href="mailto:dmca@creativecommons.org">dmca@creativecommons.org</a></p>
<h2>Counter-Notification</h2>
<p>If material that you have posted to a site controlled or operated by Creative Commons (such as <a href="http://creativecommons.org/">creativecommons.org</a>, <a href="http://sciencecommons.org/">sciencecommons.org</a>) has been taken down, you may file a counter-notification that contains the following details:</p>
<ol>
<li>Identification of the material that has been removed or to which access has been disabled and the location at which the material appeared before it was removed or disabled;</li>
<li>A statement, under penalty of perjury, that you have a good faith belief that the material was removed or disabled as a result of mistake or misidentification of the material in question;</li>
<li>Your name, address and telephone number;</li>
<li>A statement that you consent to the jurisdiction of the Federal District Court for judicial district in which your address is located or, if your address is outside of the USA, for any judicial district in which Creative Commons may be found and that you will accept service of process from the person who submitted a notice in compliance with the section (c)(1)(C) of the DMCA, as generally described above;</li>
<li>Your physical or electronic signature.</li>
</ol>
<p>Then send this notice to:</p>
<p>By Mail:</p>
<p><strong>DMCA Agent: Valeria Cavazos</strong><br />
444 Castro Street, Suite 900<br />
Mountain View, CA 94041</p>
<p>By Fax:</p>
<p><strong>Attn: DMCA Agent, Creative Commons</strong><br />
+1 650.965.1605</p>
<p>Email: <a href="mailto:dmca@creativecommons.org">dmca@creativecommons.org</a></p>
<p>You may be able to find examples of counter-notifications at <a href="http://www.chillingeffects.org/dmca/counter512.pdf">www.chillingeffects.org/dmca/counter512.pdf</a>. Please note, however, that this is no substitute for legal advice and you should obtain legal advice to better understand your rights and obligations under the DMCA and applicable laws.</p>
|
creativecommons/www2015
|
_source/_pages/dmca.html
|
HTML
|
agpl-3.0
| 5,580
|
class AddBuildErrorMessage < ActiveRecord::Migration
def change
add_column :builds, :error_message, :text
end
end
|
performanceci/performanceci-core
|
db/migrate/20140224222116_add_build_error_message.rb
|
Ruby
|
agpl-3.0
| 122
|
/****************************************************************
* *
* Copyright 2001,2014 Fidelity Information Services, Inc *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
const static readonly int error_ansi[] = {
0, /* ACK */
0, /* BREAKZST */
0, /* BADACCMTHD */
0, /* BADJPIPARAM */
0, /* BADSYIPARAM */
0, /* BITMAPSBAD */
0, /* BREAK */
0, /* BREAKDEA */
0, /* BREAKZBA */
0, /* STATCNT */
0, /* BTFAIL */
0, /* MUPRECFLLCK */
0, /* CMD */
0, /* COLON */
0, /* COMMA */
0, /* COMMAORRPAREXP */
0, /* COMMENT */
0, /* CTRAP */
0, /* CTRLC */
0, /* CTRLY */
0, /* DBCCERR */
0, /* DUPTOKEN */
0, /* DBJNLNOTMATCH */
0, /* DBFILERR */
0, /* DBNOTGDS */
0, /* DBOPNERR */
0, /* DBRDERR */
0, /* CCEDUMPNOW */
0, /* DEVPARINAP */
0, /* RECORDSTAT */
0, /* NOTGBL */
0, /* DEVPARPROT */
0, /* PREMATEOF */
0, /* GVINVALID */
0, /* DEVPARTOOBIG */
0, /* DEVPARUNK */
0, /* DEVPARVALREQ */
0, /* DEVPARMNEG */
0, /* DSEBLKRDFAIL */
0, /* DSEFAIL */
0, /* NOTALLREPLON */
0, /* BADLKIPARAM */
0, /* JNLREADBOF */
0, /* DVIKEYBAD */
0, /* ENQ */
0, /* EQUAL */
0, /* ERRORSUMMARY */
0, /* ERRWEXC */
0, /* ERRWIOEXC */
0, /* ERRWZBRK */
0, /* ERRWZTRAP */
0, /* NUMUNXEOR */
0, /* EXPR */
0, /* STRUNXEOR */
0, /* JNLEXTEND */
0, /* FCHARMAXARGS */
0, /* FCNSVNEXPECTED */
2, /* FNARGINC */
0, /* JNLACCESS */
44, /* TRANSNOSTART */
0, /* FNUMARG */
0, /* FOROFLOW */
0, /* YDIRTSZ */
0, /* JNLSUCCESS */
29, /* GBLNAME */
0, /* GBLOFLOW */
0, /* CORRUPT */
0, /* GTMCHECK */
0, /* GVDATAFAIL */
0, /* EORNOTFND */
0, /* GVGETFAIL */
0, /* GVIS */
0, /* GVKILLFAIL */
1, /* GVNAKED */
0, /* GVNEXTARG */
0, /* GVORDERFAIL */
0, /* GVPUTFAIL */
0, /* PATTABSYNTAX */
0, /* GVSUBOFLOW */
7, /* GVUNDEF */
0, /* TRANSNEST */
0, /* INDEXTRACHARS */
0, /* CORRUPTNODE */
0, /* INDRMAXLEN */
0, /* INSFFBCNT */
0, /* INTEGERRS */
0, /* INVCMD */
0, /* INVFCN */
0, /* INVOBJ */
8, /* INVSVN */
0, /* IOEOF */
0, /* IONOTOPEN */
0, /* MUPIPINFO */
0, /* IVTIME */
0, /* JOBFAIL */
13, /* JOBLABOFF */
0, /* JOBPARNOVAL */
0, /* JOBPARNUM */
0, /* JOBPARSTR */
0, /* JOBPARUNK */
0, /* JOBPARVALREQ */
0, /* JUSTFRACT */
0, /* KEY2BIG */
0, /* LABELEXPECTED */
13, /* LABELMISSING */
13, /* LABELUNKNOWN */
9, /* DIVZERO */
0, /* LKNAMEXPECTED */
0, /* JNLRDERR */
25, /* LOADRUNNING */
0, /* LPARENMISSING */
0, /* LSEXPECTED */
0, /* LVORDERARG */
0, /* MAXFORARGS */
0, /* TRANSMINUS */
0, /* MAXNRSUBSCRIPTS */
75, /* MAXSTRLEN */
0, /* JNLDBERR */
0, /* JNLFILOPN */
0, /* MBXRDONLY */
0, /* JNLINVALID */
0, /* MBXWRTONLY */
0, /* MEMORY */
70, /* MTBLKTOOBIG */
70, /* MTBLKTOOSM */
70, /* MTFIXRECSZ */
0, /* MTIS */
0, /* MTRDBADBLK */
62, /* MTRDONLY */
0, /* MTRDTHENWRT */
71, /* MTRECGTRBLK */
72, /* MTRECTOOBIG */
72, /* MTRECTOOSM */
0, /* JNLTMQUAL3 */
57, /* MULTLAB */
0, /* BLKCNT */
0, /* CCEDUMPOFF */
0, /* NOPLACE */
0, /* JNLCLOSE */
0, /* NOTPRINCIO */
0, /* NOTTOEOFONPUT */
0, /* NOZBRK */
0, /* NULSUBSC */
92, /* NUMOFLOW */
0, /* PARFILSPC */
0, /* PATCLASS */
10, /* PATCODE */
0, /* PATLIT */
0, /* PATMAXLEN */
0, /* LPARENREQD */
10, /* PATUPPERLIM */
0, /* PCONDEXPECTED */
0, /* PRCNAMLEN */
3, /* RANDARGNEG */
0, /* DBPRIVERR */
75, /* REC2BIG */
0, /* RHMISSING */
62, /* DEVICEREADONLY */
0, /* COLLDATAEXISTS */
88, /* ROUTINEUNKNOWN */
0, /* RPARENMISSING */
0, /* RTNNAME */
0, /* VIEWGVN */
0, /* RTSLOC */
0, /* RWARG */
0, /* RWFORMAT */
0, /* JNLWRTDEFER */
4, /* SELECTFALSE */
0, /* SPOREOL */
0, /* SRCLIN */
0, /* SRCLOC */
0, /* SRCLOCUNKNOWN */
0, /* STACKCRIT */
0, /* STACKOFLOW */
0, /* STACKUNDERFLO */
0, /* STRINGOFLOW */
0, /* SVNOSET */
0, /* VIEWFN */
0, /* TERMASTQUOTA */
5, /* TEXTARG */
0, /* TMPSTOREMAX */
0, /* VIEWCMD */
0, /* JNI */
0, /* TXTSRCFMT */
0, /* UIDMSG */
0, /* UIDSND */
6, /* UNDEF */
0, /* UNIMPLOP */
39, /* VAREXPECTED */
0, /* VARRECBLKSZ */
0, /* MAXARGCNT */
0, /* GTMSECSHRSEMGET */
0, /* VIEWARGCNT */
0, /* GTMSECSHRDMNSTARTED */
0, /* ZATTACHERR */
0, /* ZDATEFMT */
0, /* ZEDFILSPEC */
75, /* ZFILENMTOOLONG */
0, /* ZFILKEYBAD */
0, /* ZFILNMBAD */
0, /* ZGOTOLTZERO */
0, /* ZGOTOTOOBIG */
0, /* ZLINKFILE */
0, /* ZPARSETYPE */
0, /* ZPARSFLDBAD */
0, /* ZPIDBADARG */
0, /* ZPRIVARGBAD */
0, /* ZPRIVSYNTAXERR */
13, /* ZPRTLABNOTFND */
0, /* VIEWAMBIG */
0, /* VIEWNOTFOUND */
0, /* ZSETPRVARGBAD */
0, /* INVSPECREC */
0, /* ZSETPRVSYNTAX */
0, /* ZSRCHSTRMCT */
0, /* VERSION */
0, /* MUNOTALLSEC */
0, /* MUSECDEL */
0, /* MUSECNOTDEL */
0, /* RPARENREQD */
26, /* ZGBLDIRACC */
0, /* GVNAKEDEXTNM */
0, /* EXTGBLDEL */
0, /* DSEWCINITCON */
0, /* LASTFILCMPLD */
0, /* NOEXCNOZTRAP */
0, /* UNSDCLASS */
0, /* UNSDDTYPE */
0, /* ZCUNKTYPE */
0, /* ZCUNKMECH */
0, /* ZCUNKQUAL */
0, /* JNLDBTNNOMATCH */
0, /* ZCALLTABLE */
58, /* ZCARGMSMTCH */
58, /* ZCCONMSMTCH */
0, /* ZCOPT0 */
0, /* ZCSTATUS */
0, /* ZCUSRRTN */
0, /* ZCPOSOVR */
0, /* ZCINPUTREQ */
0, /* JNLTNOUTOFSEQ */
0, /* ACTRANGE */
0, /* ZCCONVERT */
0, /* ZCRTENOTF */
0, /* GVRUNDOWN */
0, /* LKRUNDOWN */
0, /* IORUNDOWN */
0, /* FILENOTFND */
0, /* MUFILRNDWNFL */
0, /* JNLTMQUAL1 */
0, /* FORCEDHALT */
0, /* LOADEOF */
0, /* WILLEXPIRE */
0, /* LOADEDBG */
0, /* LABELONLY */
0, /* MUREORGFAIL */
0, /* GVZPREVFAIL */
21, /* MULTFORMPARM */
16, /* QUITARGUSE */
0, /* NAMEEXPECTED */
11, /* FALLINTOFLST */
16, /* NOTEXTRINSIC */
0, /* GTMSECSHRREMSEMFAIL */
20, /* FMLLSTMISSING */
58, /* ACTLSTTOOLONG */
0, /* ACTOFFSET */
0, /* MAXACTARG */
0, /* GTMSECSHRREMSEM */
0, /* JNLTMQUAL2 */
0, /* GDINVALID */
0, /* ASSERT */
0, /* MUFILRNDWNSUC */
0, /* LOADEDSZ */
16, /* QUITARGLST */
17, /* QUITARGREQD */
0, /* CRITRESET */
0, /* UNKNOWNFOREX */
0, /* FSEXP */
0, /* WILDCARD */
0, /* DIRONLY */
0, /* FILEPARSE */
0, /* QUALEXP */
0, /* BADQUAL */
0, /* QUALVAL */
0, /* ZROSYNTAX */
0, /* COMPILEQUALS */
0, /* ZLNOOBJECT */
0, /* ZLMODULE */
0, /* DBBLEVMX */
0, /* DBBLEVMN */
0, /* DBBSIZMN */
0, /* DBBSIZMX */
0, /* DBRSIZMN */
0, /* DBRSIZMX */
0, /* DBCMPNZRO */
0, /* DBSTARSIZ */
0, /* DBSTARCMP */
0, /* DBCMPMX */
0, /* DBKEYMX */
0, /* DBKEYMN */
0, /* DBCMPBAD */
0, /* DBKEYORD */
0, /* DBPTRNOTPOS */
0, /* DBPTRMX */
0, /* DBPTRMAP */
0, /* IFBADPARM */
0, /* IFNOTINIT */
0, /* GTMSECSHRSOCKET */
0, /* LOADBGSZ */
0, /* LOADFMT */
0, /* LOADFILERR */
0, /* NOREGION */
0, /* PATLOAD */
0, /* EXTRACTFILERR */
0, /* FREEZE */
0, /* NOSELECT */
0, /* EXTRFAIL */
0, /* LDBINFMT */
0, /* NOPREVLINK */
0, /* CCEDUMPON */
0, /* CCEDMPQUALREQ */
0, /* CCEDBDUMP */
0, /* CCEDBNODUMP */
0, /* CCPMBX */
0, /* REQRUNDOWN */
0, /* CCPINTQUE */
0, /* CCPBADMSG */
0, /* CNOTONSYS */
0, /* CCPNAME */
0, /* CCPNOTFND */
0, /* OPRCCPSTOP */
0, /* SELECTSYNTAX */
0, /* LOADABORT */
0, /* FNOTONSYS */
0, /* AMBISYIPARAM */
0, /* PREVJNLNOEOF */
0, /* LKSECINIT */
0, /* MTDOSLAB */
0, /* MTDOSFOR */
0, /* MTINVLAB */
0, /* TXTSRCMAT */
0, /* CCENOGROUP */
0, /* BADDBVER */
0, /* LINKVERSION */
0, /* TOTALBLKMAX */
0, /* LOADCTRLY */
0, /* CLSTCONFLICT */
0, /* SRCNAM */
0, /* LCKGONE */
0, /* SUB2LONG */
0, /* EXTRACTCTRLY */
0, /* CCENOWORLD */
0, /* GVQUERYFAIL */
0, /* LCKSCANCELLED */
0, /* INVNETFILNM */
0, /* NETDBOPNERR */
0, /* BADSRVRNETMSG */
0, /* BADGTMNETMSG */
0, /* SERVERERR */
0, /* NETFAIL */
0, /* NETLCKFAIL */
0, /* TTINVFILTER */
0, /* MTANSILAB */
0, /* MTANSIFOR */
0, /* BADTRNPARAM */
0, /* DSEONLYBGMM */
0, /* DSEINVLCLUSFN */
18, /* RDFLTOOSHORT */
0, /* TIMRBADVAL */
0, /* CCENOSYSLCK */
0, /* CCPGRP */
0, /* UNSOLCNTERR */
0, /* BACKUPCTRL */
0, /* NOCCPPID */
0, /* CCPJNLOPNERR */
0, /* LCKSGONE */
0, /* ZLKIDBADARG */
0, /* DBFILOPERR */
0, /* CCERDERR */
0, /* CCEDBCL */
0, /* CCEDBNTCL */
0, /* CCEWRTERR */
0, /* CCEBADFN */
0, /* CCERDTIMOUT */
0, /* CCPSIGCONT */
0, /* CCEBGONLY */
0, /* CCENOCCP */
0, /* CCECCPPID */
0, /* CCECLSTPRCS */
0, /* ZSHOWBADFUNC */
0, /* NOTALLJNLEN */
0, /* ZSHOWGLOSMALL */
0, /* NOLBRSRC */
0, /* INVZSTEP */
0, /* ZSTEPARG */
0, /* INVSTRLEN */
0, /* RECCNT */
0, /* TEXT */
0, /* ZWRSPONE */
0, /* FILEDEL */
0, /* JNLBADLABEL */
0, /* JNLREADEOF */
0, /* JNLRECFMT */
0, /* BLKTOODEEP */
0, /* NESTFORMP */
0, /* BINHDR */
0, /* GOQPREC */
0, /* LDGOQFMT */
0, /* BEGINST */
0, /* INVMVXSZ */
0, /* JNLWRTNOWWRTR */
0, /* GTMSECSHRSHMCONCPROC */
0, /* JNLINVALLOC */
0, /* JNLINVEXT */
0, /* MUPCLIERR */
0, /* JNLTMQUAL4 */
0, /* GTMSECSHRREMSHM */
0, /* GTMSECSHRREMFILE */
0, /* MUNODBNAME */
0, /* FILECREATE */
0, /* FILENOTCREATE */
0, /* JNLPROCSTUCK */
0, /* INVGLOBALQUAL */
0, /* COLLARGLONG */
0, /* NOPINI */
0, /* DBNOCRE */
0, /* JNLSPACELOW */
0, /* DBCOMMITCLNUP */
0, /* BFRQUALREQ */
0, /* REQDVIEWPARM */
0, /* COLLFNMISSING */
0, /* JNLACTINCMPLT */
0, /* NCTCOLLDIFF */
0, /* DLRCUNXEOR */
0, /* DLRCTOOBIG */
0, /* WCERRNOTCHG */
0, /* WCWRNNOTCHG */
0, /* ZCWRONGDESC */
0, /* MUTNWARN */
0, /* GTMSECSHRUPDDBHDR */
0, /* LCKSTIMOUT */
0, /* CTLMNEMAXLEN */
0, /* CTLMNEXPECTED */
0, /* USRIOINIT */
0, /* CRITSEMFAIL */
0, /* TERMWRITE */
0, /* COLLTYPVERSION */
0, /* LVNULLSUBS */
0, /* GVREPLERR */
0, /* MTIOERR */
72, /* RMWIDTHPOS */
13, /* OFFSETINV */
0, /* JOBPARTOOLONG */
0, /* JOBARGMISSING */
0, /* RUNPARAMERR */
0, /* FNNAMENEG */
0, /* ORDER2 */
0, /* MUNOUPGRD */
0, /* REORGCTRLY */
0, /* TSTRTPARM */
0, /* TRIGNAMENF */
0, /* TRIGZBREAKREM */
44, /* TLVLZERO */
27, /* TRESTNOT */
41, /* TPLOCK */
42, /* TPQUIT */
0, /* TPFAIL */
0, /* TPRETRY */
0, /* TPTOODEEP */
0, /* ZDEFACTIVE */
0, /* ZDEFOFLOW */
0, /* MUPRESTERR */
0, /* MUBCKNODIR */
0, /* TRANS2BIG */
0, /* INVBITLEN */
0, /* INVBITSTR */
0, /* INVBITPOS */
0, /* PARNORMAL */
0, /* PARBUFSM */
72, /* RMWIDTHTOOBIG */
0, /* PATTABNOTFND */
0, /* OBJFILERR */
0, /* SRCFILERR */
95, /* NEGFRACPWR */
0, /* MTNOSKIP */
0, /* CETOOMANY */
0, /* CEUSRERROR */
0, /* CEBIGSKIP */
0, /* CETOOLONG */
0, /* CENOINDIR */
0, /* COLLATIONUNDEF */
0, /* RBWRNNOTCHG */
0, /* GTMSECSHRSRVF */
0, /* FREEZECTRL */
0, /* JNLFLUSH */
0, /* CCPSIGDMP */
0, /* NOPRINCIO */
0, /* INVPORTSPEC */
0, /* INVADDRSPEC */
78, /* UNUSEDMSG677 */
0, /* UNUSEDMSG678 */
80, /* SOCKWAIT */
81, /* SOCKACPT */
80, /* SOCKINIT */
81, /* OPENCONN */
0, /* DEVNOTIMP */
0, /* JNLEXTR */
0, /* DBREMOTE */
0, /* JNLREQUIRED */
0, /* TPMIXUP */
0, /* HTOFLOW */
72, /* RMNOBIGRECORD */
0, /* DBBMSIZE */
0, /* DBBMBARE */
0, /* DBBMINV */
0, /* DBBMMSTR */
0, /* DBROOTBURN */
0, /* REPLSTATEERR */
0, /* VMSMEMORY */
0, /* DBDIRTSUBSC */
0, /* TIMEROVFL */
0, /* GTMASSERT */
0, /* DBFHEADERR4 */
0, /* DBADDRANGE */
0, /* DBQUELINK */
0, /* DBCRERR */
0, /* MUSTANDALONE */
0, /* MUNOACTION */
0, /* RMBIGSHARE */
0, /* TPRESTART */
0, /* SOCKWRITE */
0, /* DBCNTRLERR */
0, /* NOTERMENV */
0, /* NOTERMENTRY */
0, /* NOTERMINFODB */
0, /* INVACCMETHOD */
0, /* JNLOPNERR */
0, /* JNLRECTYPE */
0, /* JNLTRANSGTR */
0, /* JNLTRANSLSS */
0, /* JNLWRERR */
0, /* FILEIDMATCH */
0, /* EXTSRCLIN */
0, /* EXTSRCLOC */
0, /* BIGNOACL */
0, /* ERRCALL */
0, /* ZCCTENV */
0, /* ZCCTOPN */
0, /* ZCCTNULLF */
0, /* ZCUNAVAIL */
0, /* ZCENTNAME */
0, /* ZCCOLON */
0, /* ZCRTNTYP */
0, /* ZCRCALLNAME */
0, /* ZCRPARMNAME */
0, /* ZCUNTYPE */
0, /* ZCMLTSTATUS */
0, /* ZCSTATUSRET */
0, /* ZCMAXPARAM */
0, /* ZCCSQRBR */
0, /* ZCPREALLNUMEX */
0, /* ZCPREALLVALPAR */
0, /* VERMISMATCH */
0, /* JNLCNTRL */
0, /* TRIGNAMBAD */
0, /* BUFRDTIMEOUT */
0, /* INVALIDRIP */
0, /* BLKSIZ512 */
0, /* MUTEXERR */
0, /* JNLVSIZE */
0, /* MUTEXLCKALERT */
0, /* MUTEXFRCDTERM */
0, /* GTMSECSHR */
0, /* GTMSECSHRSRVFID */
0, /* GTMSECSHRSRVFIL */
0, /* FREEBLKSLOW */
0, /* PROTNOTSUP */
0, /* DELIMSIZNA */
0, /* INVCTLMNE */
0, /* SOCKLISTEN */
0, /* LQLENGTHNA */
0, /* ADDRTOOLONG */
0, /* GTMSECSHRGETSEMFAIL */
0, /* CPBEYALLOC */
0, /* DBRDONLY */
0, /* DUPTN */
0, /* TRESTLOC */
0, /* REPLPOOLINST */
0, /* ZCVECTORINDX */
0, /* REPLNOTON */
0, /* JNLMOVED */
0, /* EXTRFMT */
0, /* CALLERID */
0, /* KRNLKILL */
0, /* MEMORYRECURSIVE */
0, /* FREEZEID */
0, /* BLKWRITERR */
0, /* STOPTIMEOUT */
0, /* UNUSEDMSG776 */
0, /* BCKUPBUFLUSH */
0, /* NOFORKCORE */
0, /* JNLREAD */
0, /* JNLMINALIGN */
0, /* JOBSTARTCMDFAIL */
0, /* JNLPOOLSETUP */
0, /* JNLSTATEOFF */
0, /* RECVPOOLSETUP */
0, /* REPLCOMM */
0, /* NOREPLCTDREG */
0, /* REPLINFO */
0, /* REPLWARN */
0, /* REPLERR */
0, /* JNLNMBKNOTPRCD */
0, /* REPLFILIOERR */
0, /* REPLBRKNTRANS */
0, /* TTWIDTHTOOBIG */
0, /* REPLLOGOPN */
0, /* REPLFILTER */
0, /* GBLMODFAIL */
0, /* TTLENGTHTOOBIG */
0, /* TPTIMEOUT */
0, /* DEFEREVENT */
0, /* JNLFILNOTCHG */
0, /* EVENTLOGERR */
0, /* UPDATEFILEOPEN */
0, /* JNLBADRECFMT */
0, /* NULLCOLLDIFF */
0, /* MUKILLIP */
0, /* JNLRDONLY */
0, /* ANCOMPTINC */
0, /* ABNCOMPTINC */
0, /* RECLOAD */
0, /* SOCKNOTFND */
0, /* CURRSOCKOFR */
79, /* SOCKETEXIST */
76, /* LISTENPASSBND */
0, /* DBCLNUPINFO */
0, /* MUNODWNGRD */
0, /* REPLTRANS2BIG */
0, /* RDFLTOOLONG */
0, /* MUNOFINISH */
0, /* DBFILEXT */
0, /* JNLFSYNCERR */
0, /* FSYNCTIMOUT */
0, /* ZCPREALLVALINV */
0, /* NEWJNLFILECREAT */
0, /* DSKSPACEFLOW */
0, /* GVINCRFAIL */
0, /* ISOLATIONSTSCHN */
0, /* REPLGBL2LONG */
0, /* TRACEON */
0, /* TOOMANYCLIENTS */
0, /* NOEXCLUDE */
0, /* GVINCRISOLATION */
0, /* EXCLUDEREORG */
0, /* REORGINC */
0, /* ASC2EBCDICCONV */
0, /* GTMSECSHRSTART */
0, /* DBVERPERFWARN1 */
0, /* FILEIDGBLSEC */
0, /* GBLSECNOTGDS */
0, /* BADGBLSECVER */
0, /* RECSIZENOTEVEN */
0, /* BUFFLUFAILED */
0, /* MUQUALINCOMP */
0, /* DISTPATHMAX */
0, /* FILEOPENFAIL */
0, /* IMAGENAME */
0, /* GTMSECSHRPERM */
0, /* GTMDISTUNDEF */
0, /* SYSCALL */
0, /* MAXGTMPATH */
0, /* TROLLBK2DEEP */
0, /* INVROLLBKLVL */
0, /* OLDBINEXTRACT */
0, /* ACOMPTBINC */
0, /* NOTREPLICATED */
0, /* DBPREMATEOF */
0, /* KILLBYSIG */
0, /* KILLBYSIGUINFO */
0, /* KILLBYSIGSINFO1 */
0, /* KILLBYSIGSINFO2 */
0, /* SIGILLOPC */
0, /* SIGILLOPN */
0, /* SIGILLADR */
0, /* SIGILLTRP */
0, /* SIGPRVOPC */
0, /* SIGPRVREG */
0, /* SIGCOPROC */
0, /* SIGBADSTK */
0, /* SIGADRALN */
0, /* SIGADRERR */
0, /* SIGOBJERR */
0, /* SIGINTDIV */
0, /* SIGINTOVF */
0, /* SIGFLTDIV */
0, /* SIGFLTOVF */
0, /* SIGFLTUND */
0, /* SIGFLTRES */
0, /* SIGFLTINV */
0, /* SIGMAPERR */
0, /* SIGACCERR */
0, /* TRNLOGFAIL */
0, /* INVDBGLVL */
0, /* DBMAXNRSUBS */
0, /* GTMSECSHRSCKSEL */
0, /* GTMSECSHRTMOUT */
0, /* GTMSECSHRRECVF */
0, /* GTMSECSHRSENDF */
0, /* SIZENOTVALID8 */
0, /* GTMSECSHROPCMP */
0, /* GTMSECSHRSUIDF */
0, /* GTMSECSHRSGIDF */
0, /* GTMSECSHRSSIDF */
0, /* GTMSECSHRFORKF */
0, /* DBFSYNCERR */
0, /* SECONDAHEAD */
0, /* SCNDDBNOUPD */
0, /* MUINFOUINT4 */
0, /* NLMISMATCHCALC */
0, /* RELINKCTLFULL */
0, /* UNUSEDMSG899 */
0, /* DBBADNSUB */
0, /* DBBADKYNM */
0, /* DBBADPNTR */
0, /* DBBNPNTR */
0, /* DBINCLVL */
0, /* DBBFSTAT */
0, /* DBBDBALLOC */
0, /* DBMRKFREE */
0, /* DBMRKBUSY */
0, /* DBBSIZZRO */
0, /* DBSZGT64K */
0, /* DBNOTMLTP */
0, /* DBTNTOOLG */
0, /* DBBPLMLT512 */
0, /* DBBPLMGT2K */
0, /* MUINFOUINT8 */
0, /* DBBPLNOT512 */
0, /* MUINFOSTR */
0, /* DBUNDACCMT */
0, /* DBTNNEQ */
0, /* MUPGRDSUCC */
0, /* DBDSRDFMTCHNG */
0, /* DBFGTBC */
0, /* DBFSTBC */
0, /* DBFSTHEAD */
0, /* DBCREINCOMP */
0, /* DBFLCORRP */
0, /* DBHEADINV */
0, /* DBINCRVER */
0, /* DBINVGBL */
0, /* DBKEYGTIND */
0, /* DBGTDBMAX */
0, /* DBKGTALLW */
0, /* DBLTSIBL */
0, /* DBLRCINVSZ */
0, /* MUREUPDWNGRDEND */
0, /* DBLOCMBINC */
0, /* DBLVLINC */
0, /* DBMBSIZMX */
0, /* DBMBSIZMN */
0, /* DBMBTNSIZMX */
0, /* DBMBMINCFRE */
0, /* DBMBPINCFL */
0, /* DBMBPFLDLBM */
0, /* DBMBPFLINT */
0, /* DBMBPFLDIS */
0, /* DBMBPFRDLBM */
0, /* DBMBPFRINT */
0, /* DBMAXKEYEXC */
0, /* DBMXRSEXCMIN */
0, /* UNUSEDMSG950 */
0, /* DBREADBM */
0, /* DBCOMPTOOLRG */
0, /* DBVERPERFWARN2 */
0, /* DBRBNTOOLRG */
0, /* DBRBNLBMN */
0, /* DBRBNNEG */
0, /* DBRLEVTOOHI */
0, /* DBRLEVLTONE */
0, /* DBSVBNMIN */
0, /* DBTTLBLK0 */
0, /* DBNOTDB */
0, /* DBTOTBLK */
0, /* DBTN */
0, /* DBNOREGION */
0, /* DBTNRESETINC */
0, /* DBTNLTCTN */
0, /* DBTNRESET */
0, /* MUTEXRSRCCLNUP */
0, /* SEMWT2LONG */
0, /* REPLINSTOPEN */
0, /* REPLINSTCLOSE */
0, /* JOBSETUP */
0, /* DBCRERR8 */
0, /* NUMPROCESSORS */
0, /* DBADDRANGE8 */
0, /* RNDWNSEMFAIL */
0, /* GTMSECSHRSHUTDN */
0, /* NOSPACECRE */
0, /* LOWSPACECRE */
0, /* WAITDSKSPACE */
0, /* OUTOFSPACE */
0, /* JNLPVTINFO */
0, /* NOSPACEEXT */
0, /* WCBLOCKED */
0, /* REPLJNLCLOSED */
0, /* RENAMEFAIL */
0, /* FILERENAME */
0, /* JNLBUFINFO */
0, /* SDSEEKERR */
0, /* LOCALSOCKREQ */
0, /* TPNOTACID */
0, /* JNLSETDATA2LONG */
0, /* JNLNEWREC */
0, /* REPLFTOKSEM */
0, /* SOCKNOTPASSED */
0, /* EXTRIOERR */
0, /* EXTRCLOSEERR */
0, /* CONNSOCKREQ */
0, /* REPLEXITERR */
0, /* MUDESTROYSUC */
0, /* DBRNDWN */
0, /* MUDESTROYFAIL */
0, /* NOTALLDBOPN */
0, /* MUSELFBKUP */
0, /* DBDANGER */
0, /* TRUNCATEFAIL */
0, /* TCGETATTR */
0, /* TCSETATTR */
0, /* IOWRITERR */
0, /* REPLINSTWRITE */
0, /* DBBADFREEBLKCTR */
0, /* REQ2RESUME */
0, /* TIMERHANDLER */
0, /* FREEMEMORY */
0, /* MUREPLSECDEL */
0, /* MUREPLSECNOTDEL */
0, /* MUJPOOLRNDWNSUC */
0, /* MURPOOLRNDWNSUC */
0, /* MUJPOOLRNDWNFL */
0, /* MURPOOLRNDWNFL */
0, /* MUREPLPOOL */
0, /* REPLACCSEM */
0, /* JNLFLUSHNOPROG */
0, /* REPLINSTCREATE */
0, /* SUSPENDING */
0, /* SOCKBFNOTEMPTY */
0, /* ILLESOCKBFSIZE */
0, /* NOSOCKETINDEV */
0, /* SETSOCKOPTERR */
0, /* GETSOCKOPTERR */
0, /* NOSUCHPROC */
0, /* DSENOFINISH */
0, /* LKENOFINISH */
0, /* NOCHLEFT */
0, /* MULOGNAMEDEF */
0, /* BUFOWNERSTUCK */
0, /* ACTIVATEFAIL */
0, /* DBRNDWNWRN */
0, /* DLLNOOPEN */
0, /* DLLNORTN */
0, /* DLLNOCLOSE */
0, /* FILTERNOTALIVE */
0, /* FILTERCOMM */
0, /* FILTERBADCONV */
0, /* PRIMARYISROOT */
0, /* GVQUERYGETFAIL */
0, /* DBCREC2BIGINBLK */
19, /* MERGEDESC */
0, /* MERGEINCOMPL */
0, /* DBNAMEMISMATCH */
0, /* DBIDMISMATCH */
0, /* DEVOPENFAIL */
0, /* IPCNOTDEL */
0, /* XCVOIDRET */
0, /* MURAIMGFAIL */
0, /* REPLINSTUNDEF */
0, /* REPLINSTACC */
0, /* NOJNLPOOL */
0, /* NORECVPOOL */
0, /* FTOKERR */
0, /* REPLREQRUNDOWN */
0, /* BLKCNTEDITFAIL */
0, /* SEMREMOVED */
0, /* REPLINSTFMT */
0, /* SEMKEYINUSE */
0, /* XTRNTRANSERR */
0, /* XTRNTRANSDLL */
0, /* XTRNRETVAL */
0, /* XTRNRETSTR */
101, /* INVECODEVAL */
0, /* SETECODE */
0, /* INVSTACODE */
0, /* REPEATERROR */
90, /* NOCANONICNAME */
0, /* NOSUBSCRIPT */
0, /* SYSTEMVALUE */
0, /* SIZENOTVALID4 */
0, /* STRNOTVALID */
0, /* CREDNOTPASSED */
0, /* ERRWETRAP */
0, /* TRACINGON */
0, /* CITABENV */
0, /* CITABOPN */
0, /* CIENTNAME */
0, /* CIRTNTYP */
0, /* CIRCALLNAME */
0, /* CIRPARMNAME */
0, /* CIDIRECTIVE */
0, /* CIPARTYPE */
0, /* CIUNTYPE */
0, /* CINOENTRY */
0, /* JNLINVSWITCHLMT */
0, /* SETZDIR */
40, /* JOBACTREF */
0, /* ECLOSTMID */
0, /* ZFF2MANY */
0, /* JNLFSYNCLSTCK */
0, /* DELIMWIDTH */
0, /* DBBMLCORRUPT */
0, /* DLCKAVOIDANCE */
0, /* WRITERSTUCK */
0, /* PATNOTFOUND */
0, /* INVZDIRFORM */
0, /* ZDIROUTOFSYNC */
0, /* GBLNOEXIST */
0, /* MAXBTLEVEL */
35, /* INVMNEMCSPC */
0, /* JNLALIGNSZCHG */
0, /* SEFCTNEEDSFULLB */
0, /* GVFAILCORE */
0, /* DBCDBNOCERTIFY */
0, /* DBFRZRESETSUC */
0, /* JNLFILEXTERR */
0, /* JOBEXAMDONE */
0, /* JOBEXAMFAIL */
0, /* JOBINTRRQST */
0, /* ERRWZINTR */
0, /* CLIERR */
0, /* REPLNOBEFORE */
0, /* REPLJNLCNFLCT */
0, /* JNLDISABLE */
0, /* FILEEXISTS */
0, /* JNLSTATE */
0, /* REPLSTATE */
0, /* JNLCREATE */
0, /* JNLNOCREATE */
0, /* JNLFNF */
0, /* PREVJNLLINKCUT */
0, /* PREVJNLLINKSET */
0, /* FILENAMETOOLONG */
0, /* REQRECOV */
0, /* JNLTRANS2BIG */
0, /* JNLSWITCHTOOSM */
0, /* JNLSWITCHSZCHG */
0, /* NOTRNDMACC */
0, /* TMPFILENOCRE */
0, /* SHRMEMEXHAUSTED */
0, /* JNLSENDOPER */
0, /* DDPSUBSNUL */
0, /* DDPNOCONNECT */
0, /* DDPCONGEST */
0, /* DDPSHUTDOWN */
0, /* DDPTOOMANYPROCS */
0, /* DDPBADRESPONSE */
0, /* DDPINVCKT */
0, /* DDPVOLSETCONFIG */
0, /* DDPCONFGOOD */
0, /* DDPCONFIGNORE */
0, /* DDPCONFINCOMPL */
0, /* DDPCONFBADVOL */
0, /* DDPCONFBADUCI */
0, /* DDPCONFBADGLD */
0, /* DDPRECSIZNOTNUM */
0, /* DDPOUTMSG2BIG */
0, /* DDPNOSERVER */
0, /* MUTEXRELEASED */
0, /* JNLCRESTATUS */
0, /* ZBREAKFAIL */
0, /* DLLVERSION */
0, /* INVZROENT */
0, /* DDPLOGERR */
0, /* GETSOCKNAMERR */
0, /* INVGTMEXIT */
0, /* CIMAXPARAM */
0, /* CITPNESTED */
0, /* CIMAXLEVELS */
0, /* JOBINTRRETHROW */
0, /* STARFILE */
0, /* NOSTARFILE */
0, /* MUJNLSTAT */
0, /* JNLTPNEST */
0, /* REPLOFFJNLON */
0, /* FILEDELFAIL */
0, /* INVQUALTIME */
0, /* NOTPOSITIVE */
0, /* INVREDIRQUAL */
0, /* INVERRORLIM */
0, /* INVIDQUAL */
0, /* INVTRNSQUAL */
0, /* JNLNOBIJBACK */
0, /* SETREG2RESYNC */
0, /* JNLALIGNTOOSM */
0, /* JNLFILEOPNERR */
0, /* JNLFILECLOSERR */
0, /* REPLSTATEOFF */
0, /* MUJNLPREVGEN */
0, /* MUPJNLINTERRUPT */
0, /* ROLLBKINTERRUPT */
0, /* RLBKJNSEQ */
0, /* REPLRECFMT */
0, /* PRIMARYNOTROOT */
0, /* DBFRZRESETFL */
0, /* JNLCYCLE */
0, /* JNLPREVRECOV */
0, /* RESOLVESEQNO */
0, /* BOVTNGTEOVTN */
0, /* BOVTMGTEOVTM */
0, /* BEGSEQGTENDSEQ */
0, /* DBADDRALIGN */
0, /* DBWCVERIFYSTART */
0, /* DBWCVERIFYEND */
0, /* MUPIPSIG */
0, /* HTSHRINKFAIL */
0, /* STPEXPFAIL */
0, /* DBBTUWRNG */
0, /* DBBTUFIXED */
0, /* DBMAXREC2BIG */
0, /* DBCSCNNOTCMPLT */
0, /* DBCBADFILE */
0, /* DBCNOEXTND */
0, /* DBCINTEGERR */
0, /* DBMINRESBYTES */
0, /* DBCNOTSAMEDB */
0, /* DBCDBCERTIFIED */
0, /* DBCMODBLK2BIG */
0, /* DBCREC2BIG */
0, /* DBCCMDFAIL */
0, /* DBCKILLIP */
0, /* DBCNOFINISH */
0, /* DYNUPGRDFAIL */
0, /* MMNODYNDWNGRD */
0, /* MMNODYNUPGRD */
0, /* MUDWNGRDNRDY */
0, /* MUDWNGRDTN */
0, /* MUDWNGRDNOTPOS */
0, /* MUUPGRDNRDY */
0, /* TNWARN */
0, /* TNTOOLARGE */
0, /* SHMPLRECOV */
0, /* MUNOSTRMBKUP */
0, /* EPOCHTNHI */
0, /* CHNGTPRSLVTM */
0, /* JNLUNXPCTERR */
0, /* OMISERVHANG */
0, /* RSVDBYTE2HIGH */
0, /* BKUPTMPFILOPEN */
0, /* BKUPTMPFILWRITE */
0, /* VMSMEMORY2 */
0, /* LOADBGSZ2 */
0, /* LOADEDSZ2 */
0, /* REPLINSTMISMTCH */
0, /* REPLINSTREAD */
0, /* REPLINSTDBMATCH */
0, /* REPLINSTNMSAME */
0, /* REPLINSTNMUNDEF */
0, /* REPLINSTNMLEN */
0, /* REPLINSTNOHIST */
0, /* REPLINSTSECLEN */
0, /* REPLINSTSECMTCH */
0, /* REPLINSTSECNONE */
0, /* REPLINSTSECUNDF */
0, /* REPLINSTSEQORD */
0, /* REPLINSTSTNDALN */
0, /* REPLREQROLLBACK */
0, /* REQROLLBACK */
0, /* INVOBJFILE */
0, /* SRCSRVEXISTS */
0, /* SRCSRVNOTEXIST */
0, /* SRCSRVTOOMANY */
0, /* JNLPOOLBADSLOT */
0, /* NOENDIANCVT */
0, /* ENDIANCVT */
0, /* DBENDIAN */
0, /* BADCHSET */
0, /* BADCASECODE */
0, /* BADCHAR */
0, /* DLRCILLEGAL */
0, /* NONUTF8LOCALE */
0, /* INVDLRCVAL */
0, /* DBMISALIGN */
0, /* LOADINVCHSET */
0, /* DLLCHSETM */
0, /* DLLCHSETUTF8 */
0, /* BOMMISMATCH */
0, /* WIDTHTOOSMALL */
80, /* SOCKMAX */
0, /* PADCHARINVALID */
0, /* ZCNOPREALLOUTPAR */
0, /* SVNEXPECTED */
0, /* SVNONEW */
0, /* ZINTDIRECT */
0, /* ZINTRECURSEIO */
0, /* MRTMAXEXCEEDED */
0, /* JNLCLOSED */
0, /* RLBKNOBIMG */
0, /* RLBKJNLNOBIMG */
0, /* RLBKLOSTTNONLY */
0, /* KILLBYSIGSINFO3 */
0, /* GTMSECSHRTMPPATH */
0, /* GTMERREXIT */
0, /* INVMEMRESRV */
0, /* OPCOMMISSED */
0, /* COMMITWAITSTUCK */
0, /* COMMITWAITPID */
0, /* UPDREPLSTATEOFF */
0, /* LITNONGRAPH */
0, /* DBFHEADERR8 */
0, /* MMBEFOREJNL */
0, /* MMNOBFORRPL */
0, /* KILLABANDONED */
0, /* BACKUPKILLIP */
0, /* LOGTOOLONG */
0, /* NOALIASLIST */
0, /* ALIASEXPECTED */
0, /* VIEWLVN */
0, /* DZWRNOPAREN */
0, /* DZWRNOALIAS */
0, /* FREEZEERR */
0, /* CLOSEFAIL */
0, /* CRYPTINIT */
0, /* CRYPTOPFAILED */
0, /* CRYPTDLNOOPEN */
0, /* CRYPTNOV4 */
0, /* CRYPTNOMM */
0, /* CRYPTJNLWRONGHASH */
0, /* CRYPTKEYFETCHFAILED */
0, /* CRYPTKEYFETCHFAILEDNF */
0, /* CRYPTHASHGENFAILED */
0, /* UNUSEDMSG1319 */
0, /* BADTAG */
0, /* ICUVERLT36 */
0, /* ICUSYMNOTFOUND */
0, /* STUCKACT */
0, /* CALLINAFTERXIT */
0, /* LOCKSPACEFULL */
0, /* IOERROR */
0, /* MAXSSREACHED */
0, /* SNAPSHOTNOV4 */
0, /* SSV4NOALLOW */
0, /* SSTMPDIRSTAT */
0, /* SSTMPCREATE */
0, /* JNLFILEDUP */
0, /* SSPREMATEOF */
0, /* SSFILOPERR */
0, /* REGSSFAIL */
0, /* SSSHMCLNUPFAIL */
0, /* SSFILCLNUPFAIL */
0, /* SETINTRIGONLY */
0, /* MAXTRIGNEST */
0, /* TRIGCOMPFAIL */
0, /* NOZTRAPINTRIG */
0, /* ZTWORMHOLE2BIG */
0, /* JNLENDIANLITTLE */
0, /* JNLENDIANBIG */
0, /* TRIGINVCHSET */
0, /* TRIGREPLSTATE */
0, /* GVDATAGETFAIL */
0, /* TRIG2NOTRIG */
0, /* ZGOTOINVLVL */
0, /* TRIGTCOMMIT */
0, /* TRIGTLVLCHNG */
0, /* TRIGNAMEUNIQ */
0, /* ZTRIGINVACT */
0, /* INDRCOMPFAIL */
0, /* QUITALSINV */
0, /* PROCTERM */
0, /* SRCLNNTDSP */
0, /* ARROWNTDSP */
0, /* TRIGDEFBAD */
0, /* TRIGSUBSCRANGE */
0, /* TRIGDATAIGNORE */
0, /* TRIGIS */
0, /* TCOMMITDISALLOW */
0, /* SSATTACHSHM */
0, /* TRIGDEFNOSYNC */
0, /* TRESTMAX */
0, /* ZLINKBYPASS */
0, /* GBLEXPECTED */
0, /* GVZTRIGFAIL */
0, /* MUUSERLBK */
0, /* SETINSETTRIGONLY */
0, /* DZTRIGINTRIG */
0, /* UNUSEDMSG1373 */
0, /* BOOLSIDEFFECT */
0, /* DBBADUPGRDSTATE */
0, /* WRITEWAITPID */
0, /* ZGOCALLOUTIN */
0, /* REPLNOXENDIAN */
0, /* REPLXENDIANFAIL */
0, /* ZGOTOINVLVL2 */
0, /* GTMSECSHRCHDIRF */
0, /* JNLORDBFLU */
0, /* ZCCLNUPRTNMISNG */
0, /* ZCINVALIDKEYWORD */
0, /* UNUSEDMSG1385 */
0, /* DBSHMNAMEDIFF */
0, /* SHMREMOVED */
0, /* DEVICEWRITEONLY */
0, /* ICUERROR */
0, /* ZDATEBADDATE */
0, /* ZDATEBADTIME */
0, /* COREINPROGRESS */
0, /* MAXSEMGETRETRY */
0, /* JNLNOREPL */
0, /* JNLRECINCMPL */
0, /* JNLALLOCGROW */
0, /* INVTRCGRP */
0, /* MUINFOUINT6 */
0, /* NOLOCKMATCH */
0, /* BADREGION */
0, /* LOCKSPACEUSE */
0, /* JIUNHNDINT */
0, /* GTMASSERT2 */
0, /* ZTRIGNOTRW */
0, /* TRIGMODREGNOTRW */
0, /* INSNOTJOINED */
0, /* INSROLECHANGE */
0, /* INSUNKNOWN */
0, /* NORESYNCSUPPLONLY */
0, /* NORESYNCUPDATERONLY */
0, /* NOSUPPLSUPPL */
0, /* REPL2OLD */
0, /* EXTRFILEXISTS */
0, /* MUUSERECOV */
0, /* SECNOTSUPPLEMENTARY */
0, /* SUPRCVRNEEDSSUPSRC */
0, /* PEERPIDMISMATCH */
0, /* SETITIMERFAILED */
0, /* UPDSYNC2MTINS */
0, /* UPDSYNCINSTFILE */
0, /* REUSEINSTNAME */
0, /* RCVRMANYSTRMS */
0, /* RSYNCSTRMVAL */
0, /* RLBKSTRMSEQ */
0, /* RESOLVESEQSTRM */
0, /* REPLINSTDBSTRM */
0, /* RESUMESTRMNUM */
0, /* ORLBKSTART */
0, /* ORLBKTERMNTD */
0, /* ORLBKCMPLT */
0, /* ORLBKNOSTP */
0, /* ORLBKFRZPROG */
0, /* ORLBKFRZOVER */
0, /* ORLBKNOV4BLK */
0, /* DBROLLEDBACK */
0, /* DSEWCREINIT */
0, /* MURNDWNOVRD */
0, /* REPLONLNRLBK */
0, /* SRVLCKWT2LNG */
0, /* IGNBMPMRKFREE */
0, /* PERMGENFAIL */
0, /* PERMGENDIAG */
0, /* MUTRUNC1ATIME */
0, /* MUTRUNCBACKINPROG */
0, /* MUTRUNCERROR */
0, /* MUTRUNCFAIL */
0, /* MUTRUNCNOSPACE */
0, /* MUTRUNCNOTBG */
0, /* MUTRUNCNOV4 */
0, /* MUTRUNCPERCENT */
0, /* MUTRUNCSSINPROG */
0, /* MUTRUNCSUCCESS */
0, /* RSYNCSTRMSUPPLONLY */
0, /* STRMNUMIS */
0, /* STRMNUMMISMTCH1 */
0, /* STRMNUMMISMTCH2 */
0, /* STRMSEQMISMTCH */
0, /* LOCKSPACEINFO */
0, /* JRTNULLFAIL */
0, /* LOCKSUB2LONG */
0, /* RESRCWAIT */
0, /* RESRCINTRLCKBYPAS */
0, /* DBFHEADERRANY */
0, /* REPLINSTFROZEN */
0, /* REPLINSTFREEZECOMMENT */
0, /* REPLINSTUNFROZEN */
0, /* DSKNOSPCAVAIL */
0, /* DSKNOSPCBLOCKED */
0, /* DSKSPCAVAILABLE */
0, /* ENOSPCQIODEFER */
0, /* CUSTOMFILOPERR */
0, /* CUSTERRNOTFND */
0, /* CUSTERRSYNTAX */
0, /* ORLBKINPROG */
0, /* DBSPANGLOINCMP */
0, /* DBSPANCHUNKORD */
0, /* DBDATAMX */
0, /* DBIOERR */
0, /* INITORRESUME */
0, /* GTMSECSHRNOARG0 */
0, /* GTMSECSHRISNOT */
0, /* GTMSECSHRBADDIR */
0, /* JNLBUFFREGUPD */
0, /* JNLBUFFDBUPD */
0, /* LOCKINCR2HIGH */
0, /* LOCKIS */
0, /* LDSPANGLOINCMP */
0, /* MUFILRNDWNFL2 */
0, /* MUINSTFROZEN */
0, /* MUINSTUNFROZEN */
0, /* GTMEISDIR */
0, /* SPCLZMSG */
0, /* MUNOTALLINTEG */
0, /* BKUPRUNNING */
0, /* MUSIZEINVARG */
0, /* MUSIZEFAIL */
0, /* SIDEEFFECTEVAL */
0, /* CRYPTINIT2 */
0, /* CRYPTDLNOOPEN2 */
0, /* CRYPTBADCONFIG */
0, /* DBCOLLREQ */
0, /* SETEXTRENV */
0, /* NOTALLDBRNDWN */
0, /* TPRESTNESTERR */
0, /* JNLFILRDOPN */
0, /* SEQNUMSEARCHTIMEOUT */
0, /* FTOKKEY */
0, /* SEMID */
0, /* JNLQIOSALVAGE */
0, /* FAKENOSPCLEARED */
0, /* MMFILETOOLARGE */
0, /* BADZPEEKARG */
0, /* BADZPEEKRANGE */
0, /* BADZPEEKFMT */
0, /* DBMBMINCFREFIXED */
0, /* NULLENTRYREF */
0, /* ZPEEKNORPLINFO */
0, /* MMREGNOACCESS */
0, /* MALLOCMAXUNIX */
0, /* MALLOCMAXVMS */
0, /* HOSTCONFLICT */
0, /* GETADDRINFO */
0, /* GETNAMEINFO */
0, /* SOCKBIND */
0, /* INSTFRZDEFER */
0, /* REGOPENRETRY */
0, /* REGOPENFAIL */
0, /* REPLINSTNOSHM */
0, /* DEVPARMTOOSMALL */
0, /* REMOTEDBNOSPGBL */
0, /* NCTCOLLSPGBL */
0, /* ACTCOLLMISMTCH */
0, /* GBLNOMAPTOREG */
0, /* ISSPANGBL */
0, /* TPNOSUPPORT */
0, /* GVSUBSERR */
0, /* UNUSEDMSG1539 */
0, /* FILTERTIMEDOUT */
0, /* TLSDLLNOOPEN */
0, /* TLSINIT */
0, /* TLSCONVSOCK */
0, /* TLSHANDSHAKE */
0, /* TLSCONNINFO */
0, /* TLSIOERROR */
0, /* TLSRENEGOTIATE */
0, /* REPLNOTLS */
0, /* COLTRANSSTR2LONG */
0, /* SOCKPASS */
0, /* SOCKACCEPT */
0, /* NOSOCKHANDLE */
0, /* TRIGLOADFAIL */
0, /* SOCKPASSDATAMIX */
0, /* NOGTCMDB */
0, /* NOUSERDB */
0, /* DSENOTOPEN */
0, /* ZSOCKETATTR */
0, /* ZSOCKETNOTSOCK */
0, /* CHSETALREADY */
0, /* DSEMAXBLKSAV */
0, /* BLKINVALID */
0, /* CANTBITMAP */
0, /* AIMGBLKFAIL */
0, /* GTMDISTUNVERIF */
0, /* CRYPTNOAPPEND */
0, /* CRYPTNOSEEK */
0, /* CRYPTNOTRUNC */
0, /* CRYPTNOKEYSPEC */
0, /* CRYPTNOOVERRIDE */
0, /* CRYPTKEYTOOBIG */
0, /* CRYPTBADWRTPOS */
13, /* LABELNOTFND */
0, /* RELINKCTLERR */
0, /* INVLINKTMPDIR */
0, /* NOEDITOR */
0, /* UPDPROC */
0, /* HLPPROC */
0, /* REPLNOHASHTREC */
0, /* REMOTEDBNOTRIG */
0, /* NEEDTRIGUPGRD */
0, /* REQRLNKCTLRNDWN */
0, /* RLNKCTLRNDWNSUC */
0, /* RLNKCTLRNDWNFL */
0, /* MPROFRUNDOWN */
0, /* ZPEEKNOJNLINFO */
0, /* TLSPARAM */
0, /* RLNKRECLATCH */
0, /* RLNKSHMLATCH */
0, /* JOBLVN2LONG */
};
|
CoherentLogic/fis-gtm-netbsd
|
sr_x86_64/merrors_ansi.h
|
C
|
agpl-3.0
| 35,297
|
<?php
/**
* @package plugins.scheduledTask
* @subpackage lib.objectTaskEngine
*/
class KObjectTaskConvertEntryFlavorsEngine extends KObjectTaskEntryEngineBase
{
/**
* @param KalturaBaseEntry $object
*/
function processObject($object)
{
/** @var KalturaConvertEntryFlavorsObjectTask $objectTask */
$objectTask = $this->getObjectTask();
$entryId = $object->id;
$reconvert = $objectTask->reconvert;
$client = $this->getClient();
$flavorParamsIds = explode(',', $objectTask->flavorParamsIds);
foreach($flavorParamsIds as $flavorParamsId)
{
try
{
$flavorAssetFilter = new KalturaFlavorAssetFilter();
$flavorAssetFilter->entryIdEqual = $entryId;
$flavorAssetFilter->flavorParamsIdEqual = $flavorParamsId;
$flavorAssetFilter->statusEqual = KalturaFlavorAssetStatus::READY;
$flavorAssetResponse = $client->flavorAsset->listAction($flavorAssetFilter);
if (!count($flavorAssetResponse->objects) || $reconvert)
$client->flavorAsset->convert($entryId, $flavorParamsId);
}
catch(Exception $ex)
{
KalturaLog::err(sprintf('Failed to convert entry id %s with flavor params id %s', $entryId, $flavorParamsId));
KalturaLog::err($ex);
}
}
}
}
|
kaltura/server
|
plugins/scheduled_task/lib/object_task_engine/KObjectTaskConvertEntryFlavorsEngine.php
|
PHP
|
agpl-3.0
| 1,210
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.adtadmissiondetailscomponent;
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;
protected void fireCustomControlValueChanged()
{
super.fireValueChanged();
}
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 cmbAdmittedCountyComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.ntpf.vo.lookups.County value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.ntpf.vo.lookups.County value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.ntpf.vo.lookups.County value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.ntpf.vo.lookups.County value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.ntpf.vo.lookups.County value)
{
return super.control.removeRow(value);
}
public ims.ntpf.vo.lookups.County getValue()
{
return (ims.ntpf.vo.lookups.County)super.control.getValue();
}
public void setValue(ims.ntpf.vo.lookups.County value)
{
super.control.setValue(value);
}
}
public static class cmbReferrerCountyComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.ntpf.vo.lookups.County value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.ntpf.vo.lookups.County value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.ntpf.vo.lookups.County value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.ntpf.vo.lookups.County value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.ntpf.vo.lookups.County value)
{
return super.control.removeRow(value);
}
public ims.ntpf.vo.lookups.County getValue()
{
return (ims.ntpf.vo.lookups.County)super.control.getValue();
}
public void setValue(ims.ntpf.vo.lookups.County value)
{
super.control.setValue(value);
}
}
public static class cmbAdmittedFromComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.core.vo.lookups.ExternalResourceType value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.core.vo.lookups.ExternalResourceType value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.core.vo.lookups.ExternalResourceType value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.core.vo.lookups.ExternalResourceType 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.lookups.ExternalResourceType value)
{
return super.control.removeRow(value);
}
public ims.core.vo.lookups.ExternalResourceType getValue()
{
return (ims.core.vo.lookups.ExternalResourceType)super.control.getValue();
}
public void setValue(ims.core.vo.lookups.ExternalResourceType value)
{
super.control.setValue(value);
}
}
public static class cmbAdmissionWardComboBox 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 cmbReferredFromComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.core.vo.lookups.ExternalResourceType value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.core.vo.lookups.ExternalResourceType value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.core.vo.lookups.ExternalResourceType value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.core.vo.lookups.ExternalResourceType 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.lookups.ExternalResourceType value)
{
return super.control.removeRow(value);
}
public ims.core.vo.lookups.ExternalResourceType getValue()
{
return (ims.core.vo.lookups.ExternalResourceType)super.control.getValue();
}
public void setValue(ims.core.vo.lookups.ExternalResourceType value)
{
super.control.setValue(value);
}
}
public static class cmbSpecialtyComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.core.vo.lookups.Specialty value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.core.vo.lookups.Specialty value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.core.vo.lookups.Specialty value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.core.vo.lookups.Specialty 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.lookups.Specialty value)
{
return super.control.removeRow(value);
}
public ims.core.vo.lookups.Specialty getValue()
{
return (ims.core.vo.lookups.Specialty)super.control.getValue();
}
public void setValue(ims.core.vo.lookups.Specialty value)
{
super.control.setValue(value);
}
}
public static class cmbAdmissionTypeComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.core.vo.lookups.AdmissionType value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.core.vo.lookups.AdmissionType value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.core.vo.lookups.AdmissionType value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.core.vo.lookups.AdmissionType 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.lookups.AdmissionType value)
{
return super.control.removeRow(value);
}
public ims.core.vo.lookups.AdmissionType getValue()
{
return (ims.core.vo.lookups.AdmissionType)super.control.getValue();
}
public void setValue(ims.core.vo.lookups.AdmissionType value)
{
super.control.setValue(value);
}
}
private void validateContext(ims.framework.Context context)
{
if(context == null)
return;
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.core.vo.EpisodeofCareShortVo.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.EpisodeofCareShortVo' of the global context variable 'Core.EpisodeofCareShort' is not supported.");
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.");
}
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(824, 590);
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));
// Custom Controls
ims.framework.CustomComponent instance1 = factory.getEmptyCustomComponent();
RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 144, 72, 240, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ims.framework.FormUiLogic m_ccAdmittingConsultantForm = loader.loadComponent(102256, appForm, startControlID * 10 + 1000, anchoringHelper1.getSize(), instance1, startTabIndex.intValue() + 3, skipContextValidation);
//ims.framework.Control m_ccAdmittingConsultantControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(144), new Integer(72), new Integer(240), new Integer(20), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT, new Integer(startTabIndex.intValue() + 3), m_ccAdmittingConsultantForm, instance1 } );
ims.framework.Control m_ccAdmittingConsultantControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT, new Integer(startTabIndex.intValue() + 3), m_ccAdmittingConsultantForm, instance1, Boolean.FALSE } );
super.addControl(m_ccAdmittingConsultantControl);
Menu[] menus1 = m_ccAdmittingConsultantForm.getForm().getRegisteredMenus();
for(int x = 0; x < menus1.length; x++)
{
form.registerMenu(menus1[x]);
}
// Label Controls
RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 424, 150, 38, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "From:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 424, 266, 90, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Telephone No.:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 424, 137, 105, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Address Admitted", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 424, 74, 93, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Admitted From:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 424, 42, 79, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Bed Number:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 424, 10, 101, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Admission Ward:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 8, 138, 91, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1008), new Integer(anchoringHelper8.getX()), new Integer(anchoringHelper8.getY()), new Integer(anchoringHelper8.getWidth()), new Integer(anchoringHelper8.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Referred From:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 8, 74, 130, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1009), 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, "Admitting Consultant:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper10 = new RuntimeAnchoring(designSize, runtimeSize, 8, 330, 126, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1010), new Integer(anchoringHelper10.getX()), new Integer(anchoringHelper10.getY()), new Integer(anchoringHelper10.getWidth()), new Integer(anchoringHelper10.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Referrer Contact No.:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper11 = new RuntimeAnchoring(designSize, runtimeSize, 8, 170, 99, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1011), new Integer(anchoringHelper11.getX()), new Integer(anchoringHelper11.getY()), new Integer(anchoringHelper11.getWidth()), new Integer(anchoringHelper11.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Referrer Details:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper12 = new RuntimeAnchoring(designSize, runtimeSize, 8, 106, 60, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1012), new Integer(anchoringHelper12.getX()), new Integer(anchoringHelper12.getY()), new Integer(anchoringHelper12.getWidth()), new Integer(anchoringHelper12.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Specialty:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper13 = new RuntimeAnchoring(designSize, runtimeSize, 8, 42, 97, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1013), new Integer(anchoringHelper13.getX()), new Integer(anchoringHelper13.getY()), new Integer(anchoringHelper13.getWidth()), new Integer(anchoringHelper13.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Admission Type:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper14 = new RuntimeAnchoring(designSize, runtimeSize, 8, 10, 131, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1014), new Integer(anchoringHelper14.getX()), new Integer(anchoringHelper14.getY()), new Integer(anchoringHelper14.getWidth()), new Integer(anchoringHelper14.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Admission Date/Time:", new Integer(1), null, new Integer(0)}));
// Button Controls
RuntimeAnchoring anchoringHelper15 = new RuntimeAnchoring(designSize, runtimeSize, 8, 558, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1015), new Integer(anchoringHelper15.getX()), new Integer(anchoringHelper15.getY()), new Integer(anchoringHelper15.getWidth()), new Integer(anchoringHelper15.getHeight()), new Integer(startTabIndex.intValue() + 24), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "New", Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper16 = new RuntimeAnchoring(designSize, runtimeSize, 8, 558, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1016), new Integer(anchoringHelper16.getX()), new Integer(anchoringHelper16.getY()), new Integer(anchoringHelper16.getWidth()), new Integer(anchoringHelper16.getHeight()), new Integer(startTabIndex.intValue() + 25), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Edit", Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper17 = new RuntimeAnchoring(designSize, runtimeSize, 741, 558, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1017), new Integer(anchoringHelper17.getX()), new Integer(anchoringHelper17.getY()), new Integer(anchoringHelper17.getWidth()), new Integer(anchoringHelper17.getHeight()), new Integer(startTabIndex.intValue() + 27), 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 }));
RuntimeAnchoring anchoringHelper18 = new RuntimeAnchoring(designSize, runtimeSize, 661, 558, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1018), new Integer(anchoringHelper18.getX()), new Integer(anchoringHelper18.getY()), new Integer(anchoringHelper18.getWidth()), new Integer(anchoringHelper18.getHeight()), new Integer(startTabIndex.intValue() + 26), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Save", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
// TextBox Controls
RuntimeAnchoring anchoringHelper19 = new RuntimeAnchoring(designSize, runtimeSize, 546, 104, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1019), new Integer(anchoringHelper19.getX()), new Integer(anchoringHelper19.getY()), new Integer(anchoringHelper19.getWidth()), new Integer(anchoringHelper19.getHeight()), new Integer(startTabIndex.intValue() + 18), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.FALSE, new Integer(70), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper20 = new RuntimeAnchoring(designSize, runtimeSize, 546, 136, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1020), new Integer(anchoringHelper20.getX()), new Integer(anchoringHelper20.getY()), new Integer(anchoringHelper20.getWidth()), new Integer(anchoringHelper20.getHeight()), new Integer(startTabIndex.intValue() + 19), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.FALSE, new Integer(40), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper21 = new RuntimeAnchoring(designSize, runtimeSize, 546, 168, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1021), new Integer(anchoringHelper21.getX()), new Integer(anchoringHelper21.getY()), new Integer(anchoringHelper21.getWidth()), new Integer(anchoringHelper21.getHeight()), new Integer(startTabIndex.intValue() + 20), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.FALSE, new Integer(40), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper22 = new RuntimeAnchoring(designSize, runtimeSize, 546, 200, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1022), new Integer(anchoringHelper22.getX()), new Integer(anchoringHelper22.getY()), new Integer(anchoringHelper22.getWidth()), new Integer(anchoringHelper22.getHeight()), new Integer(startTabIndex.intValue() + 21), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.FALSE, new Integer(40), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper23 = new RuntimeAnchoring(designSize, runtimeSize, 546, 264, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1023), new Integer(anchoringHelper23.getX()), new Integer(anchoringHelper23.getY()), new Integer(anchoringHelper23.getWidth()), new Integer(anchoringHelper23.getHeight()), new Integer(startTabIndex.intValue() + 23), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.FALSE, new Integer(30), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper24 = new RuntimeAnchoring(designSize, runtimeSize, 143, 168, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1024), new Integer(anchoringHelper24.getX()), new Integer(anchoringHelper24.getY()), new Integer(anchoringHelper24.getWidth()), new Integer(anchoringHelper24.getHeight()), new Integer(startTabIndex.intValue() + 8), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(50), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper25 = new RuntimeAnchoring(designSize, runtimeSize, 143, 328, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1025), new Integer(anchoringHelper25.getX()), new Integer(anchoringHelper25.getY()), new Integer(anchoringHelper25.getWidth()), new Integer(anchoringHelper25.getHeight()), new Integer(startTabIndex.intValue() + 13), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(20), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper26 = new RuntimeAnchoring(designSize, runtimeSize, 143, 200, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1026), new Integer(anchoringHelper26.getX()), new Integer(anchoringHelper26.getY()), new Integer(anchoringHelper26.getWidth()), new Integer(anchoringHelper26.getHeight()), new Integer(startTabIndex.intValue() + 9), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(50), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper27 = new RuntimeAnchoring(designSize, runtimeSize, 143, 232, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1027), new Integer(anchoringHelper27.getX()), new Integer(anchoringHelper27.getY()), new Integer(anchoringHelper27.getWidth()), new Integer(anchoringHelper27.getHeight()), new Integer(startTabIndex.intValue() + 10), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(50), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper28 = new RuntimeAnchoring(designSize, runtimeSize, 143, 264, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1028), new Integer(anchoringHelper28.getX()), new Integer(anchoringHelper28.getY()), new Integer(anchoringHelper28.getWidth()), new Integer(anchoringHelper28.getHeight()), new Integer(startTabIndex.intValue() + 11), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(50), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
// Date Time Controls
RuntimeAnchoring anchoringHelper29 = new RuntimeAnchoring(designSize, runtimeSize, 143, 8, 193, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(DateTimeControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1029), new Integer(anchoringHelper29.getX()), new Integer(anchoringHelper29.getY()), new Integer(anchoringHelper29.getWidth()), new Integer(anchoringHelper29.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.TRUE, null}));
// ComboBox Controls
RuntimeAnchoring anchoringHelper30 = new RuntimeAnchoring(designSize, runtimeSize, 546, 232, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
ComboBox m_cmbAdmittedCountyTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1030), new Integer(anchoringHelper30.getX()), new Integer(anchoringHelper30.getY()), new Integer(anchoringHelper30.getWidth()), new Integer(anchoringHelper30.getHeight()), new Integer(startTabIndex.intValue() + 22), 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_cmbAdmittedCountyTemp);
cmbAdmittedCountyComboBox cmbAdmittedCounty = (cmbAdmittedCountyComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbAdmittedCountyComboBox.class, m_cmbAdmittedCountyTemp);
super.addComboBox(cmbAdmittedCounty);
RuntimeAnchoring anchoringHelper31 = new RuntimeAnchoring(designSize, runtimeSize, 143, 296, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbReferrerCountyTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1031), new Integer(anchoringHelper31.getX()), new Integer(anchoringHelper31.getY()), new Integer(anchoringHelper31.getWidth()), new Integer(anchoringHelper31.getHeight()), new Integer(startTabIndex.intValue() + 12), 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_cmbReferrerCountyTemp);
cmbReferrerCountyComboBox cmbReferrerCounty = (cmbReferrerCountyComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbReferrerCountyComboBox.class, m_cmbReferrerCountyTemp);
super.addComboBox(cmbReferrerCounty);
RuntimeAnchoring anchoringHelper32 = new RuntimeAnchoring(designSize, runtimeSize, 546, 72, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
ComboBox m_cmbAdmittedFromTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1032), new Integer(anchoringHelper32.getX()), new Integer(anchoringHelper32.getY()), new Integer(anchoringHelper32.getWidth()), new Integer(anchoringHelper32.getHeight()), new Integer(startTabIndex.intValue() + 16), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)});
addControl(m_cmbAdmittedFromTemp);
cmbAdmittedFromComboBox cmbAdmittedFrom = (cmbAdmittedFromComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbAdmittedFromComboBox.class, m_cmbAdmittedFromTemp);
super.addComboBox(cmbAdmittedFrom);
RuntimeAnchoring anchoringHelper33 = new RuntimeAnchoring(designSize, runtimeSize, 546, 8, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
ComboBox m_cmbAdmissionWardTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1033), new Integer(anchoringHelper33.getX()), new Integer(anchoringHelper33.getY()), new Integer(anchoringHelper33.getWidth()), new Integer(anchoringHelper33.getHeight()), new Integer(startTabIndex.intValue() + 14), 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_cmbAdmissionWardTemp);
cmbAdmissionWardComboBox cmbAdmissionWard = (cmbAdmissionWardComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbAdmissionWardComboBox.class, m_cmbAdmissionWardTemp);
super.addComboBox(cmbAdmissionWard);
RuntimeAnchoring anchoringHelper34 = new RuntimeAnchoring(designSize, runtimeSize, 143, 136, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbReferredFromTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1034), new Integer(anchoringHelper34.getX()), new Integer(anchoringHelper34.getY()), new Integer(anchoringHelper34.getWidth()), new Integer(anchoringHelper34.getHeight()), new Integer(startTabIndex.intValue() + 6), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)});
addControl(m_cmbReferredFromTemp);
cmbReferredFromComboBox cmbReferredFrom = (cmbReferredFromComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbReferredFromComboBox.class, m_cmbReferredFromTemp);
super.addComboBox(cmbReferredFrom);
RuntimeAnchoring anchoringHelper35 = new RuntimeAnchoring(designSize, runtimeSize, 143, 104, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbSpecialtyTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1035), new Integer(anchoringHelper35.getX()), new Integer(anchoringHelper35.getY()), new Integer(anchoringHelper35.getWidth()), new Integer(anchoringHelper35.getHeight()), new Integer(startTabIndex.intValue() + 5), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)});
addControl(m_cmbSpecialtyTemp);
cmbSpecialtyComboBox cmbSpecialty = (cmbSpecialtyComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbSpecialtyComboBox.class, m_cmbSpecialtyTemp);
super.addComboBox(cmbSpecialty);
RuntimeAnchoring anchoringHelper36 = new RuntimeAnchoring(designSize, runtimeSize, 143, 40, 225, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbAdmissionTypeTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1036), new Integer(anchoringHelper36.getX()), new Integer(anchoringHelper36.getY()), new Integer(anchoringHelper36.getWidth()), new Integer(anchoringHelper36.getHeight()), new Integer(startTabIndex.intValue() + 2), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)});
addControl(m_cmbAdmissionTypeTemp);
cmbAdmissionTypeComboBox cmbAdmissionType = (cmbAdmissionTypeComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbAdmissionTypeComboBox.class, m_cmbAdmissionTypeTemp);
super.addComboBox(cmbAdmissionType);
// IntBox Controls
RuntimeAnchoring anchoringHelper37 = new RuntimeAnchoring(designSize, runtimeSize, 546, 40, 87, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(IntBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1037), new Integer(anchoringHelper37.getX()), new Integer(anchoringHelper37.getY()), new Integer(anchoringHelper37.getWidth()), new Integer(anchoringHelper37.getHeight()), new Integer(startTabIndex.intValue() + 15), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, new Integer(9)}));
// Image Buttons Controls
RuntimeAnchoring anchoringHelper38 = new RuntimeAnchoring(designSize, runtimeSize, 783, 72, 21, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1038), new Integer(anchoringHelper38.getX()), new Integer(anchoringHelper38.getY()), new Integer(anchoringHelper38.getWidth()), new Integer(anchoringHelper38.getHeight()), new Integer(startTabIndex.intValue() + 17), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.FindEnabled16, this.getImages().Core.FindDisabled16, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null}));
RuntimeAnchoring anchoringHelper39 = new RuntimeAnchoring(designSize, runtimeSize, 381, 136, 21, 21, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(ImageButton.class, new Object[] { control, new Integer(startControlID.intValue() + 1039), new Integer(anchoringHelper39.getX()), new Integer(anchoringHelper39.getY()), new Integer(anchoringHelper39.getWidth()), new Integer(anchoringHelper39.getHeight()), new Integer(startTabIndex.intValue() + 7), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, this.getImages().Core.FindEnabled16, this.getImages().Core.FindDisabled16, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null}));
}
public Forms getForms()
{
return (Forms)super.getFormReferences();
}
public Images getImages()
{
return (Images)super.getImageReferences();
}
public ims.core.forms.mosquery.IComponent ccAdmittingConsultant()
{
return (ims.core.forms.mosquery.IComponent)((ims.framework.cn.controls.CustomComponent)super.getControl(0)).getLogic();
}
public void setccAdmittingConsultantValueChangedEvent(ims.framework.delegates.ValueChanged delegate)
{
((CustomComponent)super.getControl(0)).setValueChangedEvent(delegate);
}
public void setccAdmittingConsultantVisible(boolean value)
{
((ims.framework.Control)super.getControl(0)).setVisible(value);
}
public boolean isccAdmittingConsultantVisible()
{
return ((ims.framework.Control)super.getControl(0)).isVisible();
}
public void setccAdmittingConsultantEnabled(boolean value)
{
((ims.framework.Control)super.getControl(0)).setEnabled(value);
}
public boolean isccAdmittingConsultantEnabled()
{
return ((ims.framework.Control)super.getControl(0)).isEnabled();
}
public Label lblTelephoneNr()
{
return (Label)super.getControl(2);
}
public Label lblAdressAdmittedFrom()
{
return (Label)super.getControl(3);
}
public Label lblAdmittedFrom()
{
return (Label)super.getControl(4);
}
public Label lblBedNumber()
{
return (Label)super.getControl(5);
}
public Label lblAdmissionWard()
{
return (Label)super.getControl(6);
}
public Label lblReferredFrom()
{
return (Label)super.getControl(7);
}
public Label lblAdmittingConsultant()
{
return (Label)super.getControl(8);
}
public Label lblReferrerContactNr()
{
return (Label)super.getControl(9);
}
public Label lblReferrerDetails()
{
return (Label)super.getControl(10);
}
public Label lblSpecialty()
{
return (Label)super.getControl(11);
}
public Label lblAdmissionType()
{
return (Label)super.getControl(12);
}
public Label lblAdmissionDateTime()
{
return (Label)super.getControl(13);
}
public Button btnNew()
{
return (Button)super.getControl(14);
}
public Button btnEdit()
{
return (Button)super.getControl(15);
}
public Button btnCancel()
{
return (Button)super.getControl(16);
}
public Button btnSave()
{
return (Button)super.getControl(17);
}
public TextBox txtAdmittedFromName()
{
return (TextBox)super.getControl(18);
}
public TextBox txtAdrAdmittedFromLine1()
{
return (TextBox)super.getControl(19);
}
public TextBox txtAdrAdmittedFromLine2()
{
return (TextBox)super.getControl(20);
}
public TextBox txtAdrAdmittedFromLine3()
{
return (TextBox)super.getControl(21);
}
public TextBox txtTelephoneNr()
{
return (TextBox)super.getControl(22);
}
public TextBox txtReferrerNameOrganisation()
{
return (TextBox)super.getControl(23);
}
public TextBox txtReferrerContactNr()
{
return (TextBox)super.getControl(24);
}
public TextBox txtReferrerAdr1()
{
return (TextBox)super.getControl(25);
}
public TextBox txtReferrerAdr2()
{
return (TextBox)super.getControl(26);
}
public TextBox txtReferrerAdr3()
{
return (TextBox)super.getControl(27);
}
public DateTimeControl dtimAdmissionDateTime()
{
return (DateTimeControl)super.getControl(28);
}
public cmbAdmittedCountyComboBox cmbAdmittedCounty()
{
return (cmbAdmittedCountyComboBox)super.getComboBox(0);
}
public cmbReferrerCountyComboBox cmbReferrerCounty()
{
return (cmbReferrerCountyComboBox)super.getComboBox(1);
}
public cmbAdmittedFromComboBox cmbAdmittedFrom()
{
return (cmbAdmittedFromComboBox)super.getComboBox(2);
}
public cmbAdmissionWardComboBox cmbAdmissionWard()
{
return (cmbAdmissionWardComboBox)super.getComboBox(3);
}
public cmbReferredFromComboBox cmbReferredFrom()
{
return (cmbReferredFromComboBox)super.getComboBox(4);
}
public cmbSpecialtyComboBox cmbSpecialty()
{
return (cmbSpecialtyComboBox)super.getComboBox(5);
}
public cmbAdmissionTypeComboBox cmbAdmissionType()
{
return (cmbAdmissionTypeComboBox)super.getComboBox(6);
}
public IntBox intBedNumber()
{
return (IntBox)super.getControl(36);
}
public ImageButton imbAdmittedFromSearch()
{
return (ImageButton)super.getControl(37);
}
public ImageButton imbReferredFromSearch()
{
return (ImageButton)super.getControl(38);
}
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()
{
Core = new CoreForms();
}
public final class CoreForms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private CoreForms()
{
ExternalResourceSearch = new LocalFormName(102412);
}
public final FormName ExternalResourceSearch;
}
public CoreForms Core;
}
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()
{
Core = new CoreImages();
}
public final class CoreImages implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private CoreImages()
{
FindEnabled24 = new ImageHelper(102175, "Images/Core/Find_24.png", new Integer(24), new Integer(24));
FindEnabled16 = new ImageHelper(102164, "Images/Core/Find.gif", new Integer(16), new Integer(16));
FindDisabled24 = new ImageHelper(102172, "Images/Core/FindDisabled_24.png", new Integer(24), new Integer(24));
FindDisabled16 = new ImageHelper(102165, "Images/Core/FindDisabled16.gif", new Integer(16), new Integer(16));
}
public final ims.framework.utils.Image FindEnabled24;
public final ims.framework.utils.Image FindEnabled16;
public final ims.framework.utils.Image FindDisabled24;
public final ims.framework.utils.Image FindDisabled16;
}
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_Patient = new ims.framework.ContextVariable("Patient", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier + "");
cxl_CareContext = new ims.framework.ContextVariable("CareContext", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier + "");
cxl_EpisodeOfCare = new ims.framework.ContextVariable("EpisodeOfCare", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier + "");
cxl_CurrentAdmissionDetail = new ims.framework.ContextVariable("CurrentAdmissionDetail", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier + "");
cxl_SelectedEvent = new ims.framework.ContextVariable("SelectedEvent", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedEvent_" + componentIdentifier + "");
cxl_SelectedExternalResourceForReferredFrom = new ims.framework.ContextVariable("SelectedExternalResourceForReferredFrom", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForReferredFrom_" + componentIdentifier + "");
cxl_SelectedExternalResourceForAdmittedFrom = new ims.framework.ContextVariable("SelectedExternalResourceForAdmittedFrom", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForAdmittedFrom_" + componentIdentifier + "");
cxl_CurrentInpatientEpisode = new ims.framework.ContextVariable("CurrentInpatientEpisode", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier + "");
cxl_CareSpell = new ims.framework.ContextVariable("CareSpell", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareSpell_" + componentIdentifier + "");
cxl_listEpisodesOfCare = new ims.framework.ContextVariable("listEpisodesOfCare", prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__listEpisodesOfCare_" + componentIdentifier + "");
}
public boolean getPatientIsNotNull()
{
return !cxl_Patient.getValueIsNull(context);
}
public ims.core.vo.PatientShort getPatient()
{
return (ims.core.vo.PatientShort)cxl_Patient.getValue(context);
}
public void setPatient(ims.core.vo.PatientShort value)
{
cxl_Patient.setValue(context, value);
}
private ims.framework.ContextVariable cxl_Patient = null;
public boolean getCareContextIsNotNull()
{
return !cxl_CareContext.getValueIsNull(context);
}
public ims.core.vo.CareContextVo getCareContext()
{
return (ims.core.vo.CareContextVo)cxl_CareContext.getValue(context);
}
public void setCareContext(ims.core.vo.CareContextVo value)
{
cxl_CareContext.setValue(context, value);
}
private ims.framework.ContextVariable cxl_CareContext = null;
public boolean getEpisodeOfCareIsNotNull()
{
return !cxl_EpisodeOfCare.getValueIsNull(context);
}
public ims.core.vo.EpisodeofCareVo getEpisodeOfCare()
{
return (ims.core.vo.EpisodeofCareVo)cxl_EpisodeOfCare.getValue(context);
}
public void setEpisodeOfCare(ims.core.vo.EpisodeofCareVo value)
{
cxl_EpisodeOfCare.setValue(context, value);
}
private ims.framework.ContextVariable cxl_EpisodeOfCare = null;
public boolean getCurrentAdmissionDetailIsNotNull()
{
return !cxl_CurrentAdmissionDetail.getValueIsNull(context);
}
public ims.core.vo.AdmissionDetailVo getCurrentAdmissionDetail()
{
return (ims.core.vo.AdmissionDetailVo)cxl_CurrentAdmissionDetail.getValue(context);
}
public void setCurrentAdmissionDetail(ims.core.vo.AdmissionDetailVo value)
{
cxl_CurrentAdmissionDetail.setValue(context, value);
}
private ims.framework.ContextVariable cxl_CurrentAdmissionDetail = null;
public boolean getSelectedEventIsNotNull()
{
return !cxl_SelectedEvent.getValueIsNull(context);
}
public ims.core.vo.enums.ADTAdmissionDetailEvent getSelectedEvent()
{
return (ims.core.vo.enums.ADTAdmissionDetailEvent)cxl_SelectedEvent.getValue(context);
}
public void setSelectedEvent(ims.core.vo.enums.ADTAdmissionDetailEvent value)
{
cxl_SelectedEvent.setValue(context, value);
}
private ims.framework.ContextVariable cxl_SelectedEvent = null;
public boolean getSelectedExternalResourceForReferredFromIsNotNull()
{
return !cxl_SelectedExternalResourceForReferredFrom.getValueIsNull(context);
}
public ims.core.vo.ExternalResourceVo getSelectedExternalResourceForReferredFrom()
{
return (ims.core.vo.ExternalResourceVo)cxl_SelectedExternalResourceForReferredFrom.getValue(context);
}
public void setSelectedExternalResourceForReferredFrom(ims.core.vo.ExternalResourceVo value)
{
cxl_SelectedExternalResourceForReferredFrom.setValue(context, value);
}
private ims.framework.ContextVariable cxl_SelectedExternalResourceForReferredFrom = null;
public boolean getSelectedExternalResourceForAdmittedFromIsNotNull()
{
return !cxl_SelectedExternalResourceForAdmittedFrom.getValueIsNull(context);
}
public ims.core.vo.ExternalResourceVo getSelectedExternalResourceForAdmittedFrom()
{
return (ims.core.vo.ExternalResourceVo)cxl_SelectedExternalResourceForAdmittedFrom.getValue(context);
}
public void setSelectedExternalResourceForAdmittedFrom(ims.core.vo.ExternalResourceVo value)
{
cxl_SelectedExternalResourceForAdmittedFrom.setValue(context, value);
}
private ims.framework.ContextVariable cxl_SelectedExternalResourceForAdmittedFrom = null;
public boolean getCurrentInpatientEpisodeIsNotNull()
{
return !cxl_CurrentInpatientEpisode.getValueIsNull(context);
}
public ims.core.vo.InpatientEpisodeVo getCurrentInpatientEpisode()
{
return (ims.core.vo.InpatientEpisodeVo)cxl_CurrentInpatientEpisode.getValue(context);
}
public void setCurrentInpatientEpisode(ims.core.vo.InpatientEpisodeVo value)
{
cxl_CurrentInpatientEpisode.setValue(context, value);
}
private ims.framework.ContextVariable cxl_CurrentInpatientEpisode = null;
public boolean getCareSpellIsNotNull()
{
return !cxl_CareSpell.getValueIsNull(context);
}
public ims.core.vo.CareSpellVo getCareSpell()
{
return (ims.core.vo.CareSpellVo)cxl_CareSpell.getValue(context);
}
public void setCareSpell(ims.core.vo.CareSpellVo value)
{
cxl_CareSpell.setValue(context, value);
}
private ims.framework.ContextVariable cxl_CareSpell = null;
public boolean getlistEpisodesOfCareIsNotNull()
{
return !cxl_listEpisodesOfCare.getValueIsNull(context);
}
public ims.core.vo.EpisodeofCareShortVoCollection getlistEpisodesOfCare()
{
return (ims.core.vo.EpisodeofCareShortVoCollection)cxl_listEpisodesOfCare.getValue(context);
}
public void setlistEpisodesOfCare(ims.core.vo.EpisodeofCareShortVoCollection value)
{
cxl_listEpisodesOfCare.setValue(context, value);
}
private ims.framework.ContextVariable cxl_listEpisodesOfCare = null;
}
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[233];
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.PatientShort", "BO-1001100000-DEMENTIABREACHDATETIME", "DementiaBreachDateTime");
fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DEMENTIAWORKLISTSTATUS", "DementiaWorklistStatus");
fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MRNSTATUS", "MRNStatus");
fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-HASSCANNEDCASENOTEFOLDERS", "HasScannedCaseNoteFolders");
fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISCONFIDENTIAL", "IsConfidential");
fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFBIRTH", "TimeOfBirth");
fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-PATIENTCATEGORY", "PatientCategory");
fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient");
fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex");
fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob");
fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact");
fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty");
fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType");
fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime");
fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime");
fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext");
fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated");
fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp");
fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType");
fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive");
fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP");
fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician");
fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPAENDOSCOPIST", "IsHCPaEndoscopist");
fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext");
fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context");
fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital");
fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate");
fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime");
fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime");
fields[42] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType");
fields[43] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP");
fields[44] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare");
fields[45] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell");
fields[46] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty");
fields[47] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship");
fields[48] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate");
fields[49] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate");
fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote");
fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType");
fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline");
fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact");
fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote");
fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview");
fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[58] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime");
fields[59] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected");
fields[60] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed");
fields[61] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote");
fields[62] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime");
fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport");
fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext");
fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[66] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-ID", "ID_NAESReferral");
fields[67] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-DATEREFERRALRECEIVED", "DateReferralReceived");
fields[68] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-DATEOFSURGERY", "DateOfSurgery");
fields[69] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRINGHOSPITAL", "ReferringHospital");
fields[70] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRINGDOCTOR", "ReferringDoctor");
fields[71] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERRALREASON", "ReferralReason");
fields[72] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-SECONDARYSURGERY", "SecondarySurgery");
fields[73] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-UNDERLYINGREASON", "UnderlyingReason");
fields[74] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-AFFECTEDEYE", "AffectedEye");
fields[75] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-IMPLANT", "Implant");
fields[76] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-IMPLANTTYPE", "ImplantType");
fields[77] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-INTERPRETERREQUIRED", "InterpreterRequired");
fields[78] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-LANGUAGE", "Language");
fields[79] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-LANGUAGEIFOTHER", "LanguageIfOther");
fields[80] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-REFERREDBY", "ReferredBy");
fields[81] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-_6WEEKKPI", "SixWeekKPI");
fields[82] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-_3WEEKKPI", "ThreeWeekKPI");
fields[83] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-PREFERREDCLINIC", "PreferredClinic");
fields[84] = new ims.framework.ReportField(this.context, "_cvp_Naes.Referral", "BO-1097100004-NOTES", "Notes");
fields[85] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState");
fields[86] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission");
fields[87] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus");
fields[88] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode");
fields[89] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate");
fields[90] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[91] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview");
fields[92] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[93] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[94] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext");
fields[95] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[96] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-NOTETYPE", "NoteType");
fields[97] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-FORREVIEW", "ForReview");
fields[98] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientClinicalNotesSearchCriteria", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[99] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-ID", "ID_ObservationForm");
fields[100] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-FORMTYPE", "FormType");
fields[101] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DETAILS", "Details");
fields[102] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DATETIMESTART", "DateTimeStart");
fields[103] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-DATETIMESTOP", "DateTimeStop");
fields[104] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-ISSTOPPED", "IsStopped");
fields[105] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-CARECONTEXT", "CareContext");
fields[106] = new ims.framework.ReportField(this.context, "_cvp_Nursing.ObservationFormsSearchCriteria", "BO-1011100002-CLINICALCONTACT", "ClinicalContact");
fields[107] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-ID", "ID_MedicationOverview");
fields[108] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-TYPE", "Type");
fields[109] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesAdmSearchCriteia", "BO-1072100034-CARECONTEXT", "CareContext");
fields[110] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview");
fields[111] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-TYPE", "Type");
fields[112] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesDisSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext");
fields[113] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview");
fields[114] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-TYPE", "Type");
fields[115] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesOPDSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext");
fields[116] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-ID", "ID_MedicationOverview");
fields[117] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-TYPE", "Type");
fields[118] = new ims.framework.ReportField(this.context, "_cvp_Clinical.MedMultipleDosesPatSearchCriteria", "BO-1072100034-CARECONTEXT", "CareContext");
fields[119] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ID", "ID_Urinalysis");
fields[120] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NOABNORMALITYDETECTED", "NoAbnormalityDetected");
fields[121] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-LEUCOCYTES", "Leucocytes");
fields[122] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-PROTEIN", "Protein");
fields[123] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-BLOOD", "Blood");
fields[124] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-KETONES", "Ketones");
fields[125] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ASCORBICACID", "AscorbicAcid");
fields[126] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-GLUCOSE", "Glucose");
fields[127] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-BILIRUBIN", "Bilirubin");
fields[128] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-UROBILINOGEN", "Urobilinogen");
fields[129] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NITRATE", "Nitrate");
fields[130] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-PH", "PH");
fields[131] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-SPECIFICGRAVITY", "SpecificGravity");
fields[132] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-NOSAMPLE", "NoSample");
fields[133] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-ISACTIVE", "IsActive");
fields[134] = new ims.framework.ReportField(this.context, "_cvp_Core.UrinalysisSearchCriteria", "BO-1022100012-CARECONTEXT", "CareContext");
fields[135] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-ID", "ID_Patient");
fields[136] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-SEX", "Sex");
fields[137] = new ims.framework.ReportField(this.context, "_cvp_Core.PDSPatientFilterSearchCriteria", "BO-1001100000-DOB", "Dob");
fields[138] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-ID", "ID_Patient");
fields[139] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-SEX", "Sex");
fields[140] = new ims.framework.ReportField(this.context, "_cvp_Core.LocalPatientFilterSearchCriteria", "BO-1001100000-DOB", "Dob");
fields[141] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent");
fields[142] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails");
fields[143] = new ims.framework.ReportField(this.context, "_cvp_RefMan.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral");
fields[144] = new ims.framework.ReportField(this.context, "_cv_Core.ExternalResourceSelected", "BO-1005100008-ID", "ID_ExternalResource");
fields[145] = new ims.framework.ReportField(this.context, "_cv_Core.ExternalResourceSelected", "BO-1005100008-EXTERNALRESOURCETYPE", "ExternalResourceType");
fields[146] = new ims.framework.ReportField(this.context, "_cv_Core.ExternalResourceSelected", "BO-1005100008-HCPTYPE", "HCPType");
fields[147] = new ims.framework.ReportField(this.context, "_cv_Core.ExternalResourceSelected", "BO-1005100008-RESOURCESTATUS", "ResourceStatus");
fields[148] = new ims.framework.ReportField(this.context, "_cv_Core.ExternalResourceSelected", "BO-1005100008-RESOURCENAME", "Resourcename");
fields[149] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-ID", "ID_Patient");
fields[150] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-SEX", "Sex");
fields[151] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-DOB", "Dob");
fields[152] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-DOD", "Dod");
fields[153] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-RELIGION", "Religion");
fields[154] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-ISACTIVE", "IsActive");
fields[155] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-ETHNICORIGIN", "EthnicOrigin");
fields[156] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-MARITALSTATUS", "MaritalStatus");
fields[157] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-SCN", "SCN");
fields[158] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation");
fields[159] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-TIMEOFDEATH", "TimeOfDeath");
fields[160] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient");
fields[161] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant");
fields[162] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-DEMENTIABREACHDATETIME", "DementiaBreachDateTime");
fields[163] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-DEMENTIAWORKLISTSTATUS", "DementiaWorklistStatus");
fields[164] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-MRNSTATUS", "MRNStatus");
fields[165] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-HASSCANNEDCASENOTEFOLDERS", "HasScannedCaseNoteFolders");
fields[166] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-ISCONFIDENTIAL", "IsConfidential");
fields[167] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-TIMEOFBIRTH", "TimeOfBirth");
fields[168] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__Patient_" + componentIdentifier, "BO-1001100000-PATIENTCATEGORY", "PatientCategory");
fields[169] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-ID", "ID_CareContext");
fields[170] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-CONTEXT", "Context");
fields[171] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital");
fields[172] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate");
fields[173] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-STARTDATETIME", "StartDateTime");
fields[174] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-ENDDATETIME", "EndDateTime");
fields[175] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-LOCATIONTYPE", "LocationType");
fields[176] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP");
fields[177] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-BEDNUMBER", "BedNumber");
fields[178] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareContext_" + componentIdentifier, "BO-1004100019-DISCHARGEREASON", "DischargeReason");
fields[179] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier, "BO-1004100018-ID", "ID_EpisodeOfCare");
fields[180] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier, "BO-1004100018-CARESPELL", "CareSpell");
fields[181] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier, "BO-1004100018-SPECIALTY", "Specialty");
fields[182] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier, "BO-1004100018-RELATIONSHIP", "Relationship");
fields[183] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier, "BO-1004100018-STARTDATE", "StartDate");
fields[184] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier, "BO-1004100018-ENDDATE", "EndDate");
fields[185] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__EpisodeOfCare_" + componentIdentifier, "BO-1004100018-CURRENTREFERRAL", "CurrentReferral");
fields[186] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-ID", "ID_AdmissionDetail");
fields[187] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-ADMISSIONDATETIME", "AdmissionDateTime");
fields[188] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-BED", "Bed");
fields[189] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-SPECIALTY", "Specialty");
fields[190] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-WARDTYPE", "WardType");
fields[191] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-METHODOFADMISSION", "MethodOfAdmission");
fields[192] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-SOURCEOFADMISSION", "SourceOfAdmission");
fields[193] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-REASONFORADMISSION", "ReasonForAdmission");
fields[194] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-ESTDISCHARGEDATE", "EstDischargeDate");
fields[195] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-ISCHAPLAINREQUIRED", "IsChaplainRequired");
fields[196] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-PATIENTSTATUS", "PatientStatus");
fields[197] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-UPDATECFL", "UpdateCFL");
fields[198] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-ANTICIPATEDSTAY", "AnticipatedStay");
fields[199] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-CASEFOLDERCOMMENTS", "CaseFolderComments");
fields[200] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-EXTENDEDLENGTHOFSTAYREASON", "ExtendedLengthOfStayReason");
fields[201] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-MEDICALLYFITFORDISCHARGE", "MedicallyFitForDischarge");
fields[202] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-PATIENTREQUIRESTRANSPORT", "PatientRequiresTransport");
fields[203] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-ABLETOGODISCHARGELOUNGE", "AbleToGoDischargeLounge");
fields[204] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-REASONCANNOTGODISCHARGELOUNGE", "ReasonCannotGoDischargeLounge");
fields[205] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-SELFADMITPATIENT", "SelfAdmitPatient");
fields[206] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentAdmissionDetail_" + componentIdentifier, "BO-1014100008-SOURCEOFEMERGENCYREFERRAL", "SourceOfEmergencyReferral");
fields[207] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForReferredFrom_" + componentIdentifier, "BO-1005100008-ID", "ID_ExternalResource");
fields[208] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForReferredFrom_" + componentIdentifier, "BO-1005100008-EXTERNALRESOURCETYPE", "ExternalResourceType");
fields[209] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForReferredFrom_" + componentIdentifier, "BO-1005100008-HCPTYPE", "HCPType");
fields[210] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForReferredFrom_" + componentIdentifier, "BO-1005100008-RESOURCESTATUS", "ResourceStatus");
fields[211] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForReferredFrom_" + componentIdentifier, "BO-1005100008-RESOURCENAME", "Resourcename");
fields[212] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForAdmittedFrom_" + componentIdentifier, "BO-1005100008-ID", "ID_ExternalResource");
fields[213] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForAdmittedFrom_" + componentIdentifier, "BO-1005100008-EXTERNALRESOURCETYPE", "ExternalResourceType");
fields[214] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForAdmittedFrom_" + componentIdentifier, "BO-1005100008-HCPTYPE", "HCPType");
fields[215] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForAdmittedFrom_" + componentIdentifier, "BO-1005100008-RESOURCESTATUS", "ResourceStatus");
fields[216] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__SelectedExternalResourceForAdmittedFrom_" + componentIdentifier, "BO-1005100008-RESOURCENAME", "Resourcename");
fields[217] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-ID", "ID_InpatientEpisode");
fields[218] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-ISONLEAVE", "IsOnLeave");
fields[219] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-COMMENTS", "Comments");
fields[220] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-ADMISSIONDATETIME", "AdmissionDateTime");
fields[221] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate");
fields[222] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-BEDNO", "BedNo");
fields[223] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-ADMISSIONTYPE", "AdmissionType");
fields[224] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-ISMATERNITYINPATIENT", "IsMaternityInpatient");
fields[225] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-REASONFORADMISSION", "ReasonForAdmission");
fields[226] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-WARDTYPE", "WardType");
fields[227] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-READMISSIONTYPE", "ReadmissionType");
fields[228] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CurrentInpatientEpisode_" + componentIdentifier, "BO-1014100000-DISCHARGEREADYDATE", "DischargeReadyDate");
fields[229] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareSpell_" + componentIdentifier, "BO-1004100017-ID", "ID_CareSpell");
fields[230] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareSpell_" + componentIdentifier, "BO-1004100017-STARTDATE", "StartDate");
fields[231] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareSpell_" + componentIdentifier, "BO-1004100017-ENDDATE", "EndDate");
fields[232] = new ims.framework.ReportField(this.context, prefix + "_lv_Core.ADTAdmissionDetailsComponent.__internal_x_context__CareSpell_" + componentIdentifier, "BO-1004100017-PATIENT", "Patient");
return fields;
}
protected Context context = null;
protected ims.framework.FormInfo formInfo;
protected String componentIdentifier;
}
public String getUniqueIdentifier()
{
return formInfo.getLocalVariablesPrefix() + formInfo.getNamespaceName() + formInfo.getFormName() + formInfo.getFormId() + "_" + this.componentIdentifier;
}
private Context context = null;
private ims.framework.FormInfo formInfo = null;
private String componentIdentifier;
private GlobalContext globalContext = null;
private IReportField[] reportFields = null;
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/Core/src/ims/core/forms/adtadmissiondetailscomponent/GenForm.java
|
Java
|
agpl-3.0
| 100,934
|
# -*- coding: utf-8 -*-
{
'name': "website_register_b2b",
'summary': """
Registration form for site purchases """,
'description': """
Registration form for site purchases
""",
'author': "Alexsandro Haag <alex@hgsoft.com.br>, HGSOFT",
'website': "http://www.hgsoft.com.br",
'category': 'Website',
'version': '10.0.1',
'depends': ['base','website_sale'],
'data': [
'views/register.xml',
],
'installable': True,
'auto_install': False,
}
|
alexsandrohaag/odoo-website-addons
|
website_register_b2b/__manifest__.py
|
Python
|
agpl-3.0
| 514
|
// Generated by CoffeeScript 1.8.0
var AppManager, ControllerClient, HttpClient, MemoryManager, async, fs, singleton;
fs = require('fs');
async = require('async');
HttpClient = require("request-json").JsonClient;
ControllerClient = require('cozy-clients').ControllerClient;
MemoryManager = require('./memory').MemoryManager;
AppManager = (function() {
var status2XX;
status2XX = function(res) {
if (!res) {
return false;
}
return res.statusCode / 100 === 2;
};
function AppManager() {
this.proxyClient = new HttpClient("http://localhost:9104/");
this.client = new ControllerClient({
token: this.getAuthController()
});
this.memoryManager = new MemoryManager();
this.queue = async.queue(this.processBlockingActions.bind(this), 1);
}
AppManager.prototype.processBlockingActions = function(action, done) {
var app, callback, method, msg, processor;
method = action.method, app = action.app, callback = action.callback;
processor = this[method];
if (processor != null) {
return processor.call(this, app, function(err, result) {
callback.call(null, err, result);
return done();
});
} else {
msg = "Cannot process action. Method '" + method + "' doesn't exist";
console.log(msg);
callback.call(null, msg);
return done();
}
};
AppManager.prototype.getAuthController = function() {
var err, token;
if (process.env.NODE_ENV === 'production') {
try {
token = process.env.TOKEN;
return token;
} catch (_error) {
err = _error;
console.log(err.message);
console.log(err.stack);
return null;
}
} else {
return "";
}
};
AppManager.prototype.checkMemory = function(callback) {
return this.memoryManager.isEnoughMemory((function(_this) {
return function(err, enoughMemory) {
if (!enoughMemory) {
if (err == null) {
err = 'Not enough Memory';
}
}
return callback.call(_this, err);
};
})(this));
};
AppManager.prototype.resetProxy = function(callback) {
console.info("Request for proxy reseting...");
return this.proxyClient.get("routes/reset", function(err, res, body) {
if (!status2XX(res)) {
if (err == null) {
err = new Error("Something went wrong on proxy side when reseting routes");
}
}
if (err) {
console.log("Error reseting routes");
console.log(err.message);
console.log(err.stack);
return callback(err);
} else {
console.info("Proxy successfully reseted.");
return callback(null);
}
});
};
AppManager.prototype.installApp = function(app, callback) {
var method;
method = 'processInstall';
return this.queue.push({
method: method,
app: app,
callback: callback
});
};
AppManager.prototype.processInstall = function(app, callback) {
var manifest;
manifest = app.getHaibuDescriptor();
console.info("Request controller for spawning " + app.name + "...");
console.info("with manifest : ");
console.info(JSON.stringify(manifest));
return this.checkMemory((function(_this) {
return function(err) {
if (err) {
return callback(err);
}
return _this.client.start(manifest, function(err, res, body) {
if (!status2XX(res)) {
if (err == null) {
err = body.error;
}
}
if (err) {
console.log("Error spawning app: " + app.name);
return callback(err);
} else {
console.info("Successfully spawned app: " + app.name);
return callback(null, body);
}
});
};
})(this));
};
AppManager.prototype.updateApp = function(app, callback) {
var method;
method = 'processUpdate';
return this.queue.push({
method: method,
app: app,
callback: callback
});
};
AppManager.prototype.processUpdate = function(app, callback) {
var manifest;
manifest = app.getHaibuDescriptor();
console.info("Request controller for updating " + app.name + "...");
return this.checkMemory((function(_this) {
return function(err) {
if (err) {
return callback(err);
}
return _this.client.lightUpdate(manifest, function(err, res, body) {
if (!status2XX(res)) {
if (err == null) {
err = new Error(body.error.message);
}
}
if (err) {
console.log("Error updating app: " + app.name);
console.log(err.stack);
return callback(err);
} else {
console.info("Successfully updated app: " + app.name);
return callback(null, body);
}
});
};
})(this));
};
AppManager.prototype.uninstallApp = function(app, callback) {
var method;
method = 'processUninstall';
return this.queue.push({
method: method,
app: app,
callback: callback
});
};
AppManager.prototype.processUninstall = function(app, callback) {
var manifest;
if (app != null) {
manifest = app.getHaibuDescriptor();
console.info("Request controller for cleaning " + app.name + "...");
return this.client.clean(manifest, (function(_this) {
return function(err, res, body) {
var errMsg;
if (!status2XX(res)) {
if (err == null) {
err = body.error;
}
}
errMsg = 'application not installed';
if ((err != null) && (err.indexOf != null) && err.indexOf(errMsg) === -1) {
err = new Error(err);
console.log("Error cleaning app: " + app.name);
console.log(err.message);
console.log(err.stack);
return callback(err);
} else {
if (err) {
console.log("[Warning] " + err);
}
console.info("Successfully cleaning app: " + app.name);
return callback(null);
}
};
})(this));
} else {
return callback(null);
}
};
AppManager.prototype.start = function(app, callback) {
var manifest;
manifest = app.getHaibuDescriptor();
console.info("Request controller for starting " + app.name + "...");
return this.client.stop(app.slug, (function(_this) {
return function(err, res, body) {
return _this.checkMemory(function(err) {
if (err) {
return callback(err);
}
return this.client.start(manifest, (function(_this) {
return function(err, res, body) {
if (!status2XX(res)) {
if (err == null) {
err = new Error(body.error.message);
}
}
if (err) {
console.log("Error starting app: " + app.name);
console.log(err.message);
console.log(err.stack);
return callback(err);
} else {
console.info("Successfully starting app: " + app.name);
return callback(null, res.body);
}
};
})(this));
});
};
})(this));
};
AppManager.prototype.stop = function(app, callback) {
var manifest;
manifest = app.getHaibuDescriptor();
console.info("Request controller for stopping " + app.name + "...");
return this.client.stop(app.slug, (function(_this) {
return function(err, res, body) {
if (!status2XX(res)) {
if (err == null) {
err = body.error;
}
}
if (err && err.indexOf('application not started') === -1) {
err = new Error(err);
console.log("Error stopping app: " + app.name);
console.log(err.message);
console.log(err.stack);
return callback(err);
} else {
if (err) {
console.log("[Warning] " + err);
}
console.info("Successfully stopping app: " + app.name);
return callback(null);
}
};
})(this));
};
AppManager.prototype.updateStack = function(callback) {
console.info("Request controller for updating stack...");
return this.client.updateStack(function(err, res, body) {
if (!status2XX(res)) {
if (err == null) {
err = new Error(body.error.message);
}
}
if (err) {
console.log("Error updating stack");
console.log(err.stack);
return callback(err);
} else {
console.info("Successfully updated stack");
return callback(null, body);
}
});
};
AppManager.prototype.restartController = function(callback) {
console.info("Request controller for restarting stack...");
return this.client.restartController(function(err, res, body) {
if (!status2XX(res)) {
if (err == null) {
err = new Error(body.error.message);
}
}
if (err) {
console.log("Error reboot stack");
console.log(err.stack);
return callback(err);
} else {
console.info("Successfully reboot stack");
return callback(null, body);
}
});
};
return AppManager;
})();
module.exports.AppManager = AppManager;
singleton = new AppManager();
module.exports.get = function() {
return singleton;
};
|
m4dz/cozy-home
|
build/server/lib/paas.js
|
JavaScript
|
agpl-3.0
| 9,553
|
module.exports = {
plugins: {
"postcss-import": {},
tailwindcss: {},
autoprefixer: {},
}
}
|
PanoptikumIO/pan
|
assets/postcss.config.js
|
JavaScript
|
agpl-3.0
| 107
|
//#############################################################################
//# #
//# 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.admin.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseApplicationUsersImpl extends DomainImpl implements ims.admin.domain.ApplicationUsers, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatelistMos(String mosSurname, String mosForename)
{
}
@SuppressWarnings("unused")
public void validatesaveAppUser(ims.admin.vo.AppUserVo appUserItem, Boolean replicateToDTO, ims.core.vo.MemberOfStaffShortVo memberOfStaffOld)
{
}
@SuppressWarnings("unused")
public void validatelistAppUsers(ims.admin.vo.AppUserShortVo appUserFilter)
{
}
@SuppressWarnings("unused")
public void validategetAppUser(ims.admin.vo.AppUserShortVo appUserVo)
{
}
@SuppressWarnings("unused")
public void validategetEmailData(ims.core.configuration.vo.AppUserRefVo appUser)
{
}
@SuppressWarnings("unused")
public void validategetDtoAppUserByName(String name)
{
if(name == null)
throw new ims.domain.exceptions.DomainRuntimeException("The parameter 'name' of type 'String' cannot be null.");
}
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/Admin/src/ims/admin/domain/base/impl/BaseApplicationUsersImpl.java
|
Java
|
agpl-3.0
| 2,851
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:25
*
*/
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cristian Belciug
*/
public class EDTransferForTrackingVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.EDTransferForTrackingVo copy(ims.emergency.vo.EDTransferForTrackingVo valueObjectDest, ims.emergency.vo.EDTransferForTrackingVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_EDTransfer(valueObjectSrc.getID_EDTransfer());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// AcceptedDateTime
valueObjectDest.setAcceptedDateTime(valueObjectSrc.getAcceptedDateTime());
// NotAccepted
valueObjectDest.setNotAccepted(valueObjectSrc.getNotAccepted());
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 #createEDTransferForTrackingVoCollectionFromEDTransfer(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.EDTransfer objects.
*/
public static ims.emergency.vo.EDTransferForTrackingVoCollection createEDTransferForTrackingVoCollectionFromEDTransfer(java.util.Set domainObjectSet)
{
return createEDTransferForTrackingVoCollectionFromEDTransfer(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.emergency.domain.objects.EDTransfer objects.
*/
public static ims.emergency.vo.EDTransferForTrackingVoCollection createEDTransferForTrackingVoCollectionFromEDTransfer(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.EDTransferForTrackingVoCollection voList = new ims.emergency.vo.EDTransferForTrackingVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.EDTransfer domainObject = (ims.emergency.domain.objects.EDTransfer) iterator.next();
ims.emergency.vo.EDTransferForTrackingVo 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.emergency.domain.objects.EDTransfer objects.
*/
public static ims.emergency.vo.EDTransferForTrackingVoCollection createEDTransferForTrackingVoCollectionFromEDTransfer(java.util.List domainObjectList)
{
return createEDTransferForTrackingVoCollectionFromEDTransfer(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.emergency.domain.objects.EDTransfer objects.
*/
public static ims.emergency.vo.EDTransferForTrackingVoCollection createEDTransferForTrackingVoCollectionFromEDTransfer(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.EDTransferForTrackingVoCollection voList = new ims.emergency.vo.EDTransferForTrackingVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.EDTransfer domainObject = (ims.emergency.domain.objects.EDTransfer) domainObjectList.get(i);
ims.emergency.vo.EDTransferForTrackingVo 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.emergency.domain.objects.EDTransfer 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 extractEDTransferSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDTransferForTrackingVoCollection voCollection)
{
return extractEDTransferSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractEDTransferSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDTransferForTrackingVoCollection 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.emergency.vo.EDTransferForTrackingVo vo = voCollection.get(i);
ims.emergency.domain.objects.EDTransfer domainObject = EDTransferForTrackingVoAssembler.extractEDTransfer(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.emergency.domain.objects.EDTransfer 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 extractEDTransferList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDTransferForTrackingVoCollection voCollection)
{
return extractEDTransferList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractEDTransferList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDTransferForTrackingVoCollection 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.emergency.vo.EDTransferForTrackingVo vo = voCollection.get(i);
ims.emergency.domain.objects.EDTransfer domainObject = EDTransferForTrackingVoAssembler.extractEDTransfer(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.emergency.domain.objects.EDTransfer object.
* @param domainObject ims.emergency.domain.objects.EDTransfer
*/
public static ims.emergency.vo.EDTransferForTrackingVo create(ims.emergency.domain.objects.EDTransfer domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.EDTransfer object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.EDTransferForTrackingVo create(DomainObjectMap map, ims.emergency.domain.objects.EDTransfer domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.EDTransferForTrackingVo valueObject = (ims.emergency.vo.EDTransferForTrackingVo) map.getValueObject(domainObject, ims.emergency.vo.EDTransferForTrackingVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.EDTransferForTrackingVo(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.emergency.domain.objects.EDTransfer
*/
public static ims.emergency.vo.EDTransferForTrackingVo insert(ims.emergency.vo.EDTransferForTrackingVo valueObject, ims.emergency.domain.objects.EDTransfer 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.emergency.domain.objects.EDTransfer
*/
public static ims.emergency.vo.EDTransferForTrackingVo insert(DomainObjectMap map, ims.emergency.vo.EDTransferForTrackingVo valueObject, ims.emergency.domain.objects.EDTransfer domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_EDTransfer(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;
// AcceptedDateTime
java.util.Date AcceptedDateTime = domainObject.getAcceptedDateTime();
if ( null != AcceptedDateTime )
{
valueObject.setAcceptedDateTime(new ims.framework.utils.DateTime(AcceptedDateTime) );
}
// NotAccepted
valueObject.setNotAccepted( domainObject.isNotAccepted() );
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.emergency.domain.objects.EDTransfer extractEDTransfer(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDTransferForTrackingVo valueObject)
{
return extractEDTransfer(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.EDTransfer extractEDTransfer(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDTransferForTrackingVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_EDTransfer();
ims.emergency.domain.objects.EDTransfer domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.EDTransfer)domMap.get(valueObject);
}
// ims.emergency.vo.EDTransferForTrackingVo ID_EDTransfer field is unknown
domainObject = new ims.emergency.domain.objects.EDTransfer();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_EDTransfer());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.EDTransfer)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.EDTransfer) domainFactory.getDomainObject(ims.emergency.domain.objects.EDTransfer.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_EDTransfer());
ims.framework.utils.DateTime dateTime1 = valueObject.getAcceptedDateTime();
java.util.Date value1 = null;
if ( dateTime1 != null )
{
value1 = dateTime1.getJavaDate();
}
domainObject.setAcceptedDateTime(value1);
domainObject.setNotAccepted(valueObject.getNotAccepted());
return domainObject;
}
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/EDTransferForTrackingVoAssembler.java
|
Java
|
agpl-3.0
| 16,817
|
# Copyright (C) 2013 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas 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/>.
#
require File.expand_path(File.dirname(__FILE__) + '/../../api_spec_helper')
describe Quizzes::QuizQuestionsController, type: :request do
context 'as a teacher' do
before :once do
@course = course
teacher_in_course active_all: true
@quiz = @course.quizzes.create!(:title => "A Sample Quiz")
end
describe "GET /courses/:course_id/quizzes/:quiz_id/questions (index)" do
it "returns a list of questions" do
questions = (1..10).map do |n|
@quiz.quiz_questions.create!(:question_data => { :question_name => "Question #{n}" })
end
json = api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions",
:controller => "quizzes/quiz_questions", :action => "index", :format => "json",
:course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s)
question_ids = json.collect { |q| q['id'] }
expect(question_ids).to eq questions.map(&:id)
end
it "returns a list of questions which do not include previously deleted questions" do
question1 = @quiz.quiz_questions.create!(:question_data => { :question_name => "Question 1"})
question2 = @quiz.quiz_questions.create!(:question_data => { :question_name => "Question 2"})
question1.destroy
json = api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions",
:controller => "quizzes/quiz_questions", :action => "index", :format => "json",
:course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s)
question_ids = json.collect {|q| q['id'] }
expect(question_ids).to eq [question2.id]
end
context 'given a submission id and attempt' do
it 'returns the list of questions that were used for the submission' do
question1 = @quiz.quiz_questions.create!(:question_data => { :question_name => "Question 1"})
question2 = @quiz.quiz_questions.create!(:question_data => { :question_name => "Question 2"})
@quiz.generate_quiz_data
@quiz.save
qs = @quiz.generate_submission(@teacher)
question1.destroy
json = api_call(
:get,
"/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions",
{
:controller => "quizzes/quiz_questions",
:action => "index",
:format => "json",
:course_id => @course.id.to_s,
:quiz_id => @quiz.id.to_s
},
{
quiz_submission_id: qs.id,
quiz_submission_attempt: qs.attempt
})
question_ids = json.collect {|q| q['id'] }.sort
expect(question_ids).to eq [question1.id, question2.id]
end
end
end
describe "GET /courses/:course_id/quizzes/:quiz_id/questions/:id (show)" do
context "existing question" do
before do
@question = @quiz.quiz_questions.create!(:question_data => {
"question_name"=>"Example Question", "assessment_question_id"=>"",
"question_type"=>"multiple_choice_question", "points_possible"=>"1",
"correct_comments"=>"", "incorrect_comments"=>"", "neutral_comments"=>"",
"question_text"=>"<p>What's your favorite color?</p>", "position"=>"0",
"text_after_answers"=>"", "matching_answer_incorrect_matches"=>"",
"answers"=>[]
})
@json = api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions/#{@question.id}",
:controller => "quizzes/quiz_questions", :action => "show", :format => "json",
:course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s, :id => @question.id.to_s)
@json.symbolize_keys!
end
it "has only the allowed question output fields" do
question_fields = Api::V1::QuizQuestion::API_ALLOWED_QUESTION_OUTPUT_FIELDS[:only].map(&:to_sym) + Api::V1::QuizQuestion::API_ALLOWED_QUESTION_DATA_OUTPUT_FIELDS.map(&:to_sym)
expect(question_fields).to include(:correct_comments_html)
@json.keys.each { |key| expect(question_fields.to_s).to include(key.to_s) }
end
it "has the question data fields" do
Api::V1::QuizQuestion::API_ALLOWED_QUESTION_DATA_OUTPUT_FIELDS.map(&:to_sym).each do |field|
expect(@json).to have_key(field)
# ugh... due to wonkiness in Question#question_data's treatment of keys,
# and the fact that symbolize_keys doesn't recurse, we resort to this.
if @json[field].is_a?(Array) && @question.question_data[field].is_a?(Array)
expect(@json[field].map(&:symbolize_keys)).to eq @question.question_data[field].map(&:symbolize_keys)
else
expect(@json[field]).to eq @question.question_data.symbolize_keys[field]
end
end
end
end
context "non-existent question" do
before do
@json = api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions/9034831",
{:controller => "quizzes/quiz_questions", :action => "show", :format => "json", :course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s, :id => "9034831"},
{}, {}, {:expected_status => 404})
end
it "should return a not found error message" do
expect(@json.inspect).to include "does not exist"
end
end
end
end
context 'as a student' do
before :once do
course_with_student :active_all => true
@quiz = @course.quizzes.create!(:title => 'quiz')
@quiz.published_at = Time.now
@quiz.workflow_state = 'available'
@quiz.save!
end
context 'whom has not started the quiz' do
describe 'GET /courses/:course_id/quizzes/:quiz_id/questions (index)' do
it "should be unauthorized" do
raw_api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions",
:controller => "quizzes/quiz_questions", :action => "index", :format => "json",
:course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s)
assert_status(401)
end
end
describe 'GET /courses/:course_id/quizzes/:quiz_id/questions/:id (show) ' do
it "should be unauthorized" do
@question = @quiz.quiz_questions.create!(:question_data => multiple_choice_question_data)
raw_api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions/#{@question.id}",
:controller => "quizzes/quiz_questions", :action => "show", :format => "json",
:course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s, :id => @question.id)
assert_status(401)
end
end
end
context 'whom has started a quiz' do
before :once do
@quiz.generate_submission(@student)
end
describe 'GET /courses/:course_id/quizzes/:quiz_id/questions (index)' do
it "should be unauthorized" do
raw_api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions",
:controller => "quizzes/quiz_questions", :action => "index", :format => "json",
:course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s)
assert_status(401)
end
end
describe 'GET /courses/:course_id/quizzes/:quiz_id/questions/:id (show)' do
it "should be unauthorized" do
@question = @quiz.quiz_questions.create!(:question_data => multiple_choice_question_data)
raw_api_call(:get, "/api/v1/courses/#{@course.id}/quizzes/#{@quiz.id}/questions/#{@question.id}",
:controller => "quizzes/quiz_questions", :action => "show", :format => "json",
:course_id => @course.id.to_s, :quiz_id => @quiz.id.to_s, :id => @question.id)
assert_status(401)
end
end
end
end
end
|
va7map/canvas-lms
|
spec/apis/v1/quizzes/quiz_questions_api_spec.rb
|
Ruby
|
agpl-3.0
| 9,201
|
package io.bitsquare.p2p.messaging;
public interface SendDirectMessageListener {
void onArrived();
void onFault();
}
|
haiqu/bitsquare
|
network/src/main/java/io/bitsquare/p2p/messaging/SendDirectMessageListener.java
|
Java
|
agpl-3.0
| 127
|
## BeatmapsetCompact
Represents a beatmapset.
Field | Type | Description
--------------- | ----------------------------------- | -----------
artist | string | |
artist_unicode | string | |
covers | [Covers](#beatmapsetcompact-covers) | |
creator | string | |
favourite_count | number | |
id | number | |
play_count | number | |
preview_url | string | |
source | string | |
status | string | |
title | string | |
title_unicode | string | |
user_id | number | |
video | string | |
Those fields are optional.
Field | Type | Description
----------------------- | --------------------- | -----------
beatmaps | [Beatmap](#beatmap)[] | |
converts | | |
current_user_attributes | | |
description | | |
discussions | | |
events | | |
genre | | |
has_favourited | boolean | |
language | | |
nominations | | |
ratings | | |
recent_favourites | | |
related_users | | |
user | | |
<div id="beatmapsetcompact-covers" data-unique="beatmapsetcompact-covers"></div>
### Covers
Field | Type
------------ | ------
cover | string
cover@2x | string
card | string
card@2x | string
list | string
list@2x | string
slimcover | string
slimcover@2x | string
<div id="beatmapsetcompact-rank-status" data-unique="beatmapsetcompact-rank-status"></div>
### Rank status
The possible values are denoted either as integer or string.
Integer | String
------- | ---------
-2 | graveyard
-1 | wip
0 | pending
1 | ranked
2 | approved
3 | qualified
4 | loved
|
nekodex/osu-web
|
resources/docs/source/includes/_structures/beatmapset_compact.md
|
Markdown
|
agpl-3.0
| 2,523
|
# This is the base class of all prefetched network device provider
class Puppet::Provider::NetworkDevice < Puppet::Provider
def self.device(url)
raise "This provider doesn't implement the necessary device method"
end
def self.lookup(device, name)
raise "This provider doesn't implement the necessary lookup method"
end
def self.prefetch(resources)
resources.each do |name, resource|
device = Puppet::Util::NetworkDevice.current || device(resource[:device_url])
if result = lookup(device, name)
result[:ensure] = :present
resource.provider = new(device, result)
else
resource.provider = new(device, :ensure => :absent)
end
end
rescue => detail
# Preserving behavior introduced in #6907
Puppet.log_exception(detail, "Could not perform network device prefetch: #{detail}")
end
def exists?
@property_hash[:ensure] != :absent
end
attr_accessor :device
def initialize(device, *args)
super(*args)
@device = device
# Make a duplicate, so that we have a copy for comparison
# at the end.
@properties = @property_hash.dup
end
def create
@property_hash[:ensure] = :present
self.class.resource_type.validproperties.each do |property|
if val = resource.should(property)
@property_hash[property] = val
end
end
end
def destroy
@property_hash[:ensure] = :absent
end
def flush
@property_hash.clear
end
def self.instances
end
def former_properties
@properties.dup
end
def properties
@property_hash.dup
end
end
|
nwops/puppet-retrospec
|
vendor/pup410/lib/puppet/provider/network_device.rb
|
Ruby
|
agpl-3.0
| 1,599
|
#ifndef PLUGIN_HANDLER_C
#define PLUGIN_HANDLER_C
#define P_P_F __attribute__((__noinline__)) __attribute__((__cdecl__))
pluginWrapper_t pluginFunctions;
mainFunctions_t mainFunctions;
#include "plugin_com.c"
void Plugin_Init()
{
void *ptr;
int i;
pluginFunctions.loadedPlugins=0;
pluginFunctions.enabled=qfalse;
ptr=(void*)&mainFunctions.Com_Printf;
// Copy the function pointers to mainFunctions struct
mainFunctions.Com_Printf = Com_Printf;
mainFunctions.Com_DPrintf = Com_DPrintf;
mainFunctions.Com_PrintWarning = Com_PrintWarning;
mainFunctions.Com_PrintError = Com_PrintError;
mainFunctions.Cmd_Argv = Cmd_Argv;
mainFunctions.Cmd_Argc = Cmd_Argc;
mainFunctions.FS_SV_FOpenFileRead = FS_SV_FOpenFileRead;
mainFunctions.FS_SV_FOpenFileWrite = FS_SV_FOpenFileWrite;
mainFunctions.FS_Read = FS_Read;
mainFunctions.FS_ReadLine = FS_ReadLine;
mainFunctions.FS_Write = FS_Write;
mainFunctions.FS_FCloseFile = FS_FCloseFile;
mainFunctions.Com_ParseGetToken = Com_ParseGetToken;
mainFunctions.Com_ParseTokenLength = Com_ParseTokenLength;
mainFunctions.Cvar_VariableValue = Cvar_VariableValue;
mainFunctions.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
mainFunctions.Cvar_VariableString = Cvar_VariableString;
mainFunctions.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer;
mainFunctions.Sys_Milliseconds = Sys_Milliseconds;
mainFunctions.Plugin_TcpConnect = Plugin_TcpConnect_p;
mainFunctions.Plugin_TcpGetData = Plugin_TcpGetData_p;
mainFunctions.Plugin_TcpSendData = Plugin_TcpSendData_p;
mainFunctions.Plugin_TcpCloseConnection = Plugin_TcpCloseConnection_p;
mainFunctions.Plugin_UdpSendData = Plugin_UdpSendData_p;
mainFunctions.Plugin_ServerPacketEvent = Plugin_ServerPacketEvent_p;
mainFunctions.NET_StringToAdr = NET_StringToAdr;
mainFunctions.Plugin_GetClientScoreboard = Plugin_GetClientScoreboard;
mainFunctions.Plugin_Cmd_GetInvokerUid = Plugin_Cmd_GetInvokerUid;
mainFunctions.Plugin_GetPlayerUid = Plugin_GetPlayerUid;
mainFunctions.Plugin_GetSlotCount = Plugin_GetSlotCount;
mainFunctions.Plugin_IsSvRunning = Plugin_IsSvRunning;
mainFunctions.Plugin_ChatPrintf = Plugin_ChatPrintf;
mainFunctions.Plugin_BoldPrintf = Plugin_BoldPrintf;
mainFunctions.Plugin_GetPlayerName = Plugin_GetPlayerName;
mainFunctions.Plugin_AddCommand = Plugin_AddCommand;
mainFunctions.Plugin_Malloc = Plugin_Malloc_p;
mainFunctions.Plugin_Free = Plugin_Free_p;
mainFunctions.Plugin_Error = Plugin_Error;
mainFunctions.Plugin_GetLevelTime = Plugin_GetLevelTime_p;
mainFunctions.Plugin_GetServerTime = Plugin_GetServerTime_p;
mainFunctions.Plugin_SetPlayerUID = Plugin_SetPlayerUID_p;
mainFunctions.Plugin_GetPlayerUID = Plugin_GetPlayerUID_p;
mainFunctions.Plugin_GetPlayerGUID = Plugin_GetPlayerGUID_p;
mainFunctions.Plugin_SetPlayerGUID = Plugin_SetPlayerGUID_p;
mainFunctions.Plugin_SetPlayerNoPB = Plugin_SetPlayerNoPB_p;
mainFunctions.Plugin_DoesServerUseUids = Plugin_DoesServerUseUids_p;
mainFunctions.Plugin_SetServerToUseUids = Plugin_SetServerToUseUids_p;
mainFunctions.Cvar_RegisterString = Cvar_RegisterString;
mainFunctions.Cvar_RegisterBool = Cvar_RegisterBool;
mainFunctions.Cvar_RegisterInt = Cvar_RegisterInt;
mainFunctions.Cvar_RegisterEnum = Cvar_RegisterEnum;
mainFunctions.Cvar_RegisterFloat = Cvar_RegisterFloat;
mainFunctions.Cvar_SetInt = Cvar_SetInt;
mainFunctions.Cvar_SetBool = Cvar_SetBool;
mainFunctions.Cvar_SetString = Cvar_SetString;
mainFunctions.Cvar_SetFloat = Cvar_SetFloat;
for(i=0;i<sizeof(mainFunctions_t);i+=sizeof(void*)){
if(ptr==NULL){
Com_Printf("Plugin_Init: Error initializing function pointers.\n");
return;
}
ptr++;
}
Com_Printf("Plugin_Init: Plugins initialization successfull.\n");
memset(&pluginFunctions,0x00,sizeof(pluginFunctions)); // 0 all data
pluginFunctions.enabled=qtrue;
Cmd_AddCommand("loadPlugin", Plugin_LoadPlugin_f);
Cmd_AddCommand("unloadPlugin", Plugin_UnLoadPlugin_f);
Cmd_AddCommand("plugins", Plugin_PluginList_f);
Cmd_AddCommand("pluginInfo", Plugin_PluginInfo_f);
}
void Plugin_Load(char* name, size_t size)
{
int i,j,nstrings;
char dll[256],*strings;
char* realpath;
void *lib_handle;
elf_data_t text;
pluginInfo_t info;
if(!pluginFunctions.enabled){
Com_Printf("Plugin handler is not initialized!\n");
return;
}
if(pluginFunctions.loadedPlugins>=MAX_PLUGINS-1){
Com_Printf("Too many plugins loaded.");
return;
}
if(size>128){
Com_Printf("File name too long.");
return;
}
Com_DPrintf("Checking if the plugin is not already loaded...\n");
// Check if the plugin is not already loaded...
for(i=0;i<MAX_PLUGINS;i++){
if(strcmp(name,pluginFunctions.plugins[i].name)==0){
Com_Printf("This plugin is already loaded!\n");
return;
}
}
Com_DPrintf("Checking if the plugin file exists and is of correct format...\n");
sprintf(dll,"plugins/%s.so",name);
//Additional test if a file is there
realpath = FS_SV_GetFilepath( dll );
if(realpath == NULL)
{
Com_Printf("No such file found: %s. Can not load this plugin.\n", dll);
return;
}
nstrings = ELF32_GetStrTable(realpath,&strings,&text);
if(!nstrings){
Com_Printf("%s is not a plugin file or is corrupt.\n",dll);
return;
}
Com_DPrintf("Parsing plugin function names...\n");
--nstrings;
for(i = 0,j=0 ;i<nstrings;++i){
if(strings[i]==0){
//Com_Printf("\"%s\"\n",strings+i+1);
if(strcmp(strings+i+1,"malloc")==0 || strcmp(strings+i+1,"calloc")==0 || strcmp(strings+i+1,"realloc")==0 || strcmp(strings+i+1,"free")==0 || strcmp(strings+i+1,"printf")==0 || strcmp(strings+i+1,"scanf")==0){
Com_Printf("The plugin file contains one of the disallowed functions! Disallowed function name: \"%s\".\nPlease refer to the documentation for details.\n",strings+i+1);
free(strings);
return;
}
if(strncmp(strings+i+1,"_Znaj",5)==0 || strncmp(strings+i+1,"_Znwj",5)==0){ // new and new[]
Com_Printf("The plugin file contains the C++ new operator which is forbidden.\nPlease refer to the documentation for details.\n");
free(strings);
return;
}
}
else
i+=strlen(strings+i+1);
}
free(strings);
Com_DPrintf("Done parsing plugin function names.\n");
lib_handle = dlopen(realpath, RTLD_LAZY);
if (!lib_handle){
Com_Printf("Can not load %s.\nError string: '%s'.\n",dll,dlerror());
return;
}
Com_DPrintf("Plugin OK! Loading...\n");
// find first free plugin slot
for(i=0;i<MAX_PLUGINS;i++){
if(!(pluginFunctions.plugins[i].loaded))
break;
}
pluginFunctions.plugins[i].OnInit = dlsym(lib_handle, "OnInit");
for(j=0;j<PLUGINS_ITEMCOUNT;++j){
pluginFunctions.plugins[i].OnEvent[j] = dlsym(lib_handle,Plugin_Events[j]);
}
pluginFunctions.plugins[i].OnInfoRequest = pluginFunctions.plugins[i].OnEvent[PLUGINS_ONINFOREQUEST];
pluginFunctions.plugins[i].OnUnload = dlsym(lib_handle, "OnUnload");
dlerror(); // Just clear the errors, if the function was not found then we have a NULL pointer - thats what we want
pluginFunctions.plugins[i].loaded = qtrue;
pluginFunctions.plugins[i].enabled = qtrue;
strcpy(pluginFunctions.plugins[i].name,name);
pluginFunctions.initializing_plugin = qtrue;
pluginFunctions.plugins[i].lib_start = LIBRARY_ADDRESS_BY_HANDLE(lib_handle) + text.offset;;
pluginFunctions.plugins[i].lib_size = text.size;
if(pluginFunctions.plugins[i].OnInit==NULL){
Com_Printf("Error loading plugin's OnInit function.\nPlugin load failed.\n");
return;
}
if((*pluginFunctions.plugins[i].OnInit)(mainFunctions)<0){
Com_Printf("Error in plugin's OnInit function!\nPlugin load failed.\n");
pluginFunctions.plugins[i].loaded = qfalse;
pluginFunctions.initializing_plugin = qfalse;
memset(pluginFunctions.plugins + i,0x00,sizeof(plugin_t)); // We need to remove all references so we can dlclose.
dlclose(lib_handle);
return;
}
else{
Com_Printf("Plugin's OnInit executed successfully!\n");
// Save info about the loaded plugin
pluginFunctions.initializing_plugin = qfalse;
pluginFunctions.loadedPlugins++;
pluginFunctions.plugins[i].lib_handle = lib_handle;
if(pluginFunctions.plugins[i].OnInfoRequest){
Com_DPrintf("Fetching plugin information...\n");
(*pluginFunctions.plugins[i].OnInfoRequest)(&info);
if(info.handlerVersion > PLUGIN_HANDLER_VERSION){
Com_PrintError("This plugin might not be compatible with this server version! Requested plugin handler version: %g, server's plugin handler version: %g. Unloading the plugin...\n",info.handlerVersion,PLUGIN_HANDLER_VERSION);
Plugin_Unload(i);
return;
}
else if(PLUGIN_HANDLER_VERSION - info.handlerVersion >= 0.1){
Com_PrintWarning("This plugin might not be compatible with this server version! Requested plugin handler version: %g, server's plugin handler version: %g.\n",info.handlerVersion,PLUGIN_HANDLER_VERSION);
}
Com_Printf("Plugin %s loaded successfully. Server is currently running %d plugins.\n",pluginFunctions.plugins[i].name,pluginFunctions.loadedPlugins);
}
else{
Com_PrintError("function OnInfoRequest not found in the plugin file. Unloading...\n");
Plugin_Unload(i);
return;
}
Com_Printf("Plugin %s loaded successfully. Server is currently running %d plugins.\n",pluginFunctions.plugins[i].name,pluginFunctions.loadedPlugins);
return;
}
}
void Plugin_Unload(int id)
{
void *lib_handle;
int i;
if(pluginFunctions.plugins[id].loaded){
if(pluginFunctions.plugins[id].exports != 0){ // Library-plugins cannot be unloaded, see plugins/readme.txt
Com_PrintError("Plugin_Unload: Cannot unload a library plugin!\n");
return;
}
if(pluginFunctions.plugins[id].scriptfunctions != 0 || pluginFunctions.plugins[id].scriptmethods != 0){
// Script-library plugins cannot be unloaded, see plugins/readme.txt
Com_PrintError("Plugin_Unload: Cannot unload a script-library plugin!\n");
return;
}
if(pluginFunctions.plugins[id].OnUnload != NULL)
(*pluginFunctions.plugins[id].OnUnload)();
// Remove all server commands of the plugin
for(i=0;i<pluginFunctions.plugins[id].cmds;i++){
if(pluginFunctions.plugins[id].cmd[i].xcommand!=NULL){
Com_DPrintf("Removing command \"%s\"...\n",pluginFunctions.plugins[id].cmd[i].name);
Cmd_RemoveCommand(pluginFunctions.plugins[id].cmd[i].name);
}
}
lib_handle = pluginFunctions.plugins[id].lib_handle; // Save the lib handle
memset(&(pluginFunctions.plugins[id]), 0x00, sizeof(plugin_t)); // Wipe out all the data
dlclose(lib_handle); // Close the dll as there are no more references to it
--pluginFunctions.loadedPlugins;
}else{
Com_Printf("Tried unloading a not loaded plugin!\nPlugin ID: %d.",id);
}
}
int Plugin_GetID(char *name, size_t size)
{
int i;
for(i=0;i<MAX_PLUGINS;i++){
if(strcmp(name,pluginFunctions.plugins[i].name)==0){
return i;
}
}
return PLUGIN_UNKNOWN;
}
P_P_F int Plugin_CallerID()
{
void *funcptrs[3];
int i,j;
j = backtrace(funcptrs,3);
if(j<3){
Com_Error(ERR_FATAL,"Plugin_CallerID: backtrace failed to return function pointers! Possible exploit detected! Terminating the server...\n");
}
for(i=0;i<MAX_PLUGINS;++i){
//Com_Printf("Debug: lib_start: %p, lib_size: %ld, lib_start + lib_size: %p, caller function: %p.\n",pluginFunctions.plugins[i].lib_start,pluginFunctions.plugins[i].lib_size,pluginFunctions.plugins[i].lib_start+pluginFunctions.plugins[i].lib_size,funcptrs[2]);
if(pluginFunctions.plugins[i].lib_start < funcptrs[2] && pluginFunctions.plugins[i].lib_start + pluginFunctions.plugins[i].lib_size > funcptrs[2])
return i;
}
return -1;
}
/*P_P_F int Plugin_CallerID()
{
//asm volatile (""); // this + inline attribute prevents compiler optimization which removes the function call
int i,j;
void *funcptrs[3];
char **names;
char buff[256];
j = backtrace(funcptrs,3);
names = backtrace_symbols(funcptrs,j);
if(!names)
Com_Error(ERR_FATAL,"Function backtrace_symbols() is not working properly!");
//Com_Printf("DEBUG: \"%s\",\"%s\",\"%s\".\n",names[0],names[1],names[2]);
if(strncmp(names[2],"plugins/",8)==0){
j = strlen(names[2]);
for(i=8;i<j;++i){
if(names[2][i]=='.')
break;
}
strncpy(buff,names[2]+8,i-8);
buff[i-8]=0;
}
else{
free(names);
return -1;
}
free(names);
return Plugin_GetID(buff,strlen(buff));
}*/
void Plugin_UnloadByName(char *name, size_t size)
{
int id = Plugin_GetID(name,size);
if(id<0)
Com_Printf("Cannot unload plugin: plugin %s is not loaded!\n",name);
else{
Com_Printf("Unloading plugin %s, plugin id: %d.\n",name,id);
Plugin_Unload(id);
}
}
void *Plugin_Malloc(int pID,size_t size)
{
int i;
//Com_Printf("Attempting to allocate %dB of memory for plugin #%d...\n",size,pID);
//Plugin identified, find the first free spot in it's allocated pointers table
for(i=0;i<PLUGIN_MAX_MALLOCS;i++){
if(pluginFunctions.plugins[pID].memory[i].ptr==NULL){
pluginFunctions.plugins[pID].memory[i].ptr = malloc(size);
pluginFunctions.plugins[pID].memory[i].size = size;
pluginFunctions.plugins[pID].usedMem += size;
++pluginFunctions.plugins[pID].mallocs;
//Com_Printf("Allocating %dB of memory for plugin #%d.\n",size,pID);
//Com_Printf("Debug: %p.\n",pluginFunctions.plugins[pID].memory[i]);
return pluginFunctions.plugins[pID].memory[i].ptr;
}
}
Com_Printf("Plugins: Warning! Memory allocations limit reached for plugin #%d!\n",pID);
return NULL;
}
void Plugin_Free(int pID, void *ptr)
{
int i;
if(ptr==NULL){
Com_DPrintf("Plugins: Warning! Plugin #%d tried freeing a NULL pointer! Called Plugin_Free() twice?\n",pID);
return;
}
//Plugin identified, find the first free spot in it's allocated pointers table
for(i=0;i<PLUGIN_MAX_MALLOCS;i++){
if(pluginFunctions.plugins[pID].memory[i].ptr==ptr){
free(ptr);
pluginFunctions.plugins[pID].memory[i].ptr = NULL;
pluginFunctions.plugins[pID].usedMem -= pluginFunctions.plugins[pID].memory[i].size;
--pluginFunctions.plugins[pID].mallocs;
return;
}
}
Com_DPrintf("Plugins: Warning! Plugin %d tried freeing an unknown pointer!\n",pID);
}
P_P_F void *Plugin_Malloc_p(size_t size)
{
volatile int pID;
//Identify the calling plugin
pID = Plugin_CallerID();
if(pID<0){
Com_Printf("Plugins: Error! Tried allocating memory for unknown plugin!\n");
return NULL;
}
if(pluginFunctions.plugins[pID].enabled==qfalse){
Com_Printf("^1WARNING^7: Tried allocating memory for a disabled plugin!\n");
}
return Plugin_Malloc(pID,size);
}
P_P_F void Plugin_Free_p(void *ptr)
{
//Identify the calling plugin
volatile int pID = Plugin_CallerID();
if(pID<0){
Com_Printf("Plugins: Error! Tried freeing memory for unknown plugin!\n");
return;
}
Plugin_Free(pID,ptr);
}
void Plugin_FreeAll(int pID)
{
int i;
if(pID<0){
Com_Printf("Plugins: Error! Tried to free all memory of an unknown plugin!\n");
return;
}
for(i=0;i<PLUGIN_MAX_MALLOCS;++i){
if(pluginFunctions.plugins[pID].memory[i].ptr!=NULL){
free(pluginFunctions.plugins[pID].memory[i].ptr);
pluginFunctions.plugins[pID].memory[i].ptr=NULL;
}
}
pluginFunctions.plugins[pID].usedMem = 0;
pluginFunctions.plugins[pID].mallocs = 0;
Com_DPrintf("Plugins: Memory for plugin #%d has been freed.\n",pID);
}
P_P_F void Plugin_Error(int code,char *string)
{
volatile int pID = Plugin_CallerID();
if(pID<0){
Com_PrintError("Plugin Error called from unknown plugin!\n");
return;
}
else if(pluginFunctions.plugins[pID].enabled==qfalse){
Com_PrintWarning("An error of ID %d and string \"%s\" occured in a disabled plugin with ID %d!\n",code,string,pID);
return;
}
switch(code)
{
case P_ERROR_WARNING:
Com_Printf("Plugin #%d ('%s') issued a warning: \"%s\"\n",pID,pluginFunctions.plugins[pID].name, string);
break;
case P_ERROR_DISABLE:
Com_Printf("Plugin #%d ('%s') returned an error and will be disabled! Error string: \"%s\".\n",pID,pluginFunctions.plugins[pID].name,string);
pluginFunctions.plugins[pID].enabled = qfalse;
break;
case P_ERROR_TERMINATE:
Com_Printf("Plugin #%d ('%s') reported a critical error, the server will be terminated. Error string: \"%s\".\n",pID,pluginFunctions.plugins[pID].name,string);
Com_Error(ERR_FATAL,string);
break;
default:
Com_DPrintf("Plugin #%d ('%s') reported an unknown error! Error string: \"%s\", error code: %d.\n",pID,pluginFunctions.plugins[pID].name,string,code);
break;
}
}
int Plugin_ClientToSlot(client_t *client)
{
return client-svs.clients;
}
void Plugin_Event(int eventID,...)
{
int i=0;
if(!pluginFunctions.enabled)
return;
if(eventID < 0 || eventID >= PLUGINS_ITEMCOUNT){
Com_DPrintf("Plugins: unknown event occured! Event ID: %d.\n",eventID);
return;
}
va_list argptr;
va_start(argptr, eventID);
void *arg_0 = va_arg(argptr, void*);
void *arg_1 = va_arg(argptr, void*);
void *arg_2 = va_arg(argptr, void*);
void *arg_3 = va_arg(argptr, void*);
void *arg_4 = va_arg(argptr, void*);
void *arg_5 = va_arg(argptr, void*);
va_end(argptr);
for(i=0;i < pluginFunctions.loadedPlugins; i++){
if(pluginFunctions.plugins[i].OnEvent[eventID]!= NULL)
(*pluginFunctions.plugins[i].OnEvent[eventID])(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5);
}
}
/*
void Plugin_Event(int eventID, void *dataPt)
{
int i=0;
if(!pluginFunctions.enabled)
return;
switch(eventID){
case PLUGINS_ONPLAYERDC:
for(i=0;i<MAX_PLUGINS;i++){
if(pluginFunctions.plugins[i].OnPlayerDC!=NULL)
(*pluginFunctions.plugins[i].OnPlayerDC)((client_t*)dataPt);
}
break;
case PLUGINS_ONPLAYERCONNECT:
for(i=0;i<pluginFunctions.loadedPlugins;i++){
if(pluginFunctions.plugins[i].OnPlayerConnect!=NULL)
(*pluginFunctions.plugins[i].OnPlayerConnect)((client_t*)dataPt);
}
break;
case PLUGINS_ONEXITLEVEL:
for(i=0;i<pluginFunctions.loadedPlugins;i++){
if(pluginFunctions.plugins[i].OnExitLevel!=NULL)
(*pluginFunctions.plugins[i].OnExitLevel)();
}
break;
case PLUGINS_ONMESSAGESENT:
for(i=0;i<pluginFunctions.loadedPlugins;i++){
if(pluginFunctions.plugins[i].OnMessageSent!=NULL)
(*pluginFunctions.plugins[i].OnMessageSent)(dataPt);
}
break;
case PLUGINS_ONTENSECONDS:
for(i=0;i<pluginFunctions.loadedPlugins;i++){
if(pluginFunctions.plugins[i].OnTenSeconds!=NULL)
(*pluginFunctions.plugins[i].OnTenSeconds)(dataPt);
}
break;
case PLUGINS_ONCLIENTSPAWN:
for(i=0;i<pluginFunctions.loadedPlugins;i++){
if(pluginFunctions.plugins[i].OnClientSpawn!=NULL)
(*pluginFunctions.plugins[i].OnClientSpawn)(dataPt);
}
break;
case PLUGINS_ONCLIENTENTERWORLD:
for(i=0;i<pluginFunctions.loadedPlugins;i++){
if(pluginFunctions.plugins[i].OnClientEnterWorld!=NULL)
(*pluginFunctions.plugins[i].OnClientEnterWorld)(dataPt);
}
break;
case PLUGINS_ONTCPSERVERPACKET:
for(i=0;i<pluginFunctions.loadedPlugins;i++){
if(pluginFunctions.plugins[i].OnTcpPacketEvent!=NULL)
(*pluginFunctions.plugins[i].OnTcpPacketEvent)(dataPt);
}
break;
default:
Com_DPrintf("Plugins: unknown event occured! Event ID: %d.\n",eventID);
break;
}
}
*/
clientScoreboard_t Plugin_GetClientScoreboard(int clientNum)
{
return level.clients[clientNum].pers.scoreboard;
}
int Plugin_Cmd_GetInvokerUid()
{
return svse.cmdInvoker.currentCmdInvoker;
}
int Plugin_GetPlayerUid(int slot)
{
return svs.clients[slot].uid;
}
int Plugin_GetSlotCount()
{
return sv_maxclients->integer;
}
qboolean Plugin_IsSvRunning()
{
if(com_sv_running)
return com_sv_running->boolean;
else
return qfalse;
}
void Plugin_ChatPrintf(int slot, char *fmt, ... )
{
//int ebp,*ptr;
char str[256];
client_t *cl;
va_list vl;
cl = slot >=0 ? &(svs.clients[slot]) : NULL;
va_start(vl,fmt);
vsprintf(str,fmt,vl);
va_end(vl);
SV_SendServerCommand(cl, "h \"%s\"", str);
}
void Plugin_BoldPrintf(int slot, char *fmt, ... )
{
char str[256];
client_t *cl;
va_list vl;
cl = slot >=0 ? &(svs.clients[slot]) : NULL;
va_start(vl,fmt);
vsprintf(str,fmt,vl);
va_end(vl);
SV_SendServerCommand(cl, "c \"%s\"", str);
}
char *Plugin_GetPlayerName(int slot)
{
return svs.clients[slot].name;
}
void Plugin_CmdExecute_f()
{
Com_DPrintf("Attempting to execute a plugin command '%s'.\n",Cmd_Argv(0));
if(!pluginFunctions.enabled){
Com_DPrintf("Error! Tried executing a plugin command with plugins being disabled! Command name: '%s'.\n",Cmd_Argv(1));
return;
}
char name[128];
int i,j;
void (*func)();
strcpy(name,Cmd_Argv(0));
for(i=0;i<MAX_PLUGINS;i++){
if(pluginFunctions.plugins[i].loaded && pluginFunctions.plugins[i].enabled){
for(j=0;j<pluginFunctions.plugins[i].cmds;j++)
if(strcmp(name,pluginFunctions.plugins[i].cmd[j].name)==0){
Com_DPrintf("Executing plugin command '%s' for plugin '%s', plugin ID: %d.\n",name,pluginFunctions.plugins[i].name,i);
func = (void (*)())(pluginFunctions.plugins[i].cmd[j].xcommand);
func();
return;
}
}
}
}
P_P_F void Plugin_AddCommand(char *name, xcommand_t xcommand, int power)
{
volatile int pID;
pID = Plugin_CallerID();
if(pID>=MAX_PLUGINS){
Com_PrintError("Tried adding a command for a plugin with non existent pID. pID supplied: %d.\n",pID);
return;
}else if(pID<0){
Com_PrintError("Plugin_AddServerCommand called from not within a plugin or from a disabled plugin!\n");
return;
}
if(!pluginFunctions.plugins[pID].loaded){
Com_PrintError("Tried adding a command for not loaded plugin! PID: %d.\n",pID);
}
Com_DPrintf("Adding a plugin command for plugin %d, command name: %s.\n",pID,name);
Cmd_AddCommand(name,Plugin_CmdExecute_f);
Cmd_SetPower(name, power);
pluginFunctions.plugins[pID].cmd[pluginFunctions.plugins[pID].cmds].xcommand = xcommand;
strcpy(pluginFunctions.plugins[pID].cmd[pluginFunctions.plugins[pID].cmds++].name,name);
Com_DPrintf("Command added.\n");
// pluginFunctions.plugins[pID].
}
void Plugin_RemoveCommand(int pID,char *name)
{
int i,j,k;
j=pluginFunctions.plugins[pID].cmds;
for(i=0;i<j;i++){
if(strcmp(name,pluginFunctions.plugins[pID].cmd[i].name)==0){
Cmd_RemoveCommand(name);
memset(pluginFunctions.plugins[pID].cmd,0x00,sizeof(pluginCmd_t));
// Now we need to rearrrange the array...
for(k=i;k<j-1;k++){
pluginFunctions.plugins[pID].cmd[k] = pluginFunctions.plugins[pID].cmd[k+1];
}
Com_DPrintf("Command '%s' removed for plugin %s.\n",name,pluginFunctions.plugins[pID].name);
return;
}
}
Com_DPrintf("Warning: tried removing command '%s', which was not found for plugin %s.\n",name,pluginFunctions.plugins[pID].name);
}
/*
P_P_F void Plugin_ScrAddFunction(char *name,xcommand_t xcommand)
{
volatile int pID;
pID = Plugin_CallerID();
if(pID>=MAX_PLUGINS){
Com_Printf("Error: tried adding a script command for a plugin with non existent pID. pID supplied: %d.\n",pID);
return;
}else if(pID<0){
Com_Printf("Plugin Handler error: Plugin_ScrAddFunction called from not within a plugin or from a disabled plugin!\n");
return;
}
if(!pluginFunctions.plugins[pID].loaded){
Com_Printf("Error: Tried adding a command for not loaded plugin! PID: %d.\n",pID);
}
Com_Printf("Adding a plugin script function for plugin %d, command name: %s.\n",pID,name);
Cmd_AddCommand(name, xcommand);
pluginFunctions.plugins[pID].cmd[pluginFunctions.functions[pID].cmds].xcommand = xcommand;
strcpy(pluginFunctions.plugins[pID].cmd[pluginFunctions.plugins[pID].cmds++].name,name);
Com_Printf("Command added.\n");
// pluginFunctions.plugins[pID].
}
void Plugin_ScrRemoveFunction(int pID,char *name)
{
int i,j,k;
j=pluginFunctions.plugins[pID].cmds;
for(i=0;i<j;i++){
if(strcmp(name,pluginFunctions.plugins[pID].cmd[i].name)==0){
Cmd_RemoveCommand(name);
memset(pluginFunctions.plugins[pID].cmd,0x00,sizeof(pluginCmd_t));
// Now we need to rearrrange the array...
for(k=i;k<j-1;k++){
pluginFunctions.plugins[pID].cmd[k] = pluginFunctions.plugins[pID].cmd[k+1];
}
Com_Printf("Command '%s' removed for plugin %s.\n",name,pluginFunctions.plugins[pID].name);
return;
}
}
Com_Printf("Warning: tried removing command '%s', which was not found for plugin %s.\n",name,pluginFunctions.plugins[pID].name);
}
*/
/*
==================
SV_LoadPlugin_f
Loads and initializes a plugin
==================
*/
void Plugin_LoadPlugin_f( void )
{
if( Cmd_Argc() < 2){
Com_Printf("Usage: %s <plugin file name without extension>\n", Cmd_Argv(0));
return;
}
Plugin_Load(Cmd_Argv(1),128);
}
void Plugin_UnLoadPlugin_f()
{
if( Cmd_Argc() < 2){
Com_Printf("Usage: %s <plugin file name without extension>\n", Cmd_Argv(0));
return;
}
Plugin_UnloadByName(Cmd_Argv(1),128);
}
void Plugin_PluginInfo_f()
{
if(Cmd_Argc() < 2){
Com_Printf("Usage: %s <plugin name>\n",Cmd_Argv(0));
return;
}
int id = Plugin_GetID(Cmd_Argv(1),strlen(Cmd_Argv(1)));
int i;
pluginInfo_t info;
if(id<0){
Com_Printf("Plugin \"%s\" is not loaded!\n",Cmd_Argv(1));
return;
}
(*pluginFunctions.plugins[id].OnInfoRequest)(&info);
Com_Printf("\n");
Com_Printf("\n^2Plugin name:^7\n%s\n\n",pluginFunctions.plugins[id].name);
Com_Printf("\n^2Plugin version:^7\n%g\n\n",info.pluginVersion);
Com_Printf("\n^2Full plugin name:^7\n%s\n\n",info.fullName);
Com_Printf("\n^2Short plugin description:^7\n%s\n\n",info.shortDescription);
Com_Printf("\n^2Full plugin description:^7\n%s\n\n",info.longDescription);
Com_Printf("\n^2Plugin commands:^7\n\n");
for(i=0;i<pluginFunctions.plugins[id].cmds;++i){
Com_Printf(" -%s\n",pluginFunctions.plugins[id].cmd[i].name);
}
Com_Printf("\n^2Total of %d commands.^7\n\n",pluginFunctions.plugins[id].cmds);
}
void Plugin_PluginList_f()
{
int i,j;
if(pluginFunctions.loadedPlugins == 0){
Com_Printf("No plugins are loaded.\n");
}
else{
Com_Printf("\nLoaded plugins:\n\n");
Com_Printf("*----------------------------------------------------------------------------------*\n");
Com_Printf("| ID | name | enabled? | memory allocations | total all. mem. in B |\n");
for(i=0,j=0;i<pluginFunctions.loadedPlugins;++i,++j){
while(j<MAX_PLUGINS){ // ORing might be dangerous when the compiler uses optimalization...
if(pluginFunctions.plugins[j].loaded)
break;
++j;
}
if(j==MAX_PLUGINS){
i=j;
break;
}
Com_Printf("| %-3d| %-21s| %-9s| %-19d| %-21d|\n",j,pluginFunctions.plugins[j].name,pluginFunctions.plugins[j].enabled==0 ? "no" : "yes",pluginFunctions.plugins[j].mallocs,pluginFunctions.plugins[j].usedMem);
}
Com_Printf("*----------------------------------------------------------------------------------*\n");
Com_Printf("\nTotal of %d loaded plugins.\n",i);
}
Com_Printf("\nPlugin handler version: %g.\n",PLUGIN_HANDLER_VERSION);
}
qboolean Plugin_TcpConnect(int pID, const char* remote, int connection)
{
if(pluginFunctions.plugins[pID].sockets[connection].sock < 1){
pluginFunctions.plugins[pID].sockets[connection].sock = NET_TcpConnect( remote );
if(pluginFunctions.plugins[pID].sockets[connection].sock < 1){
Com_Printf("Plugins: Notice! Error connecting to server: %s for plugin #%d!\n", remote, pID);
return qfalse;
}
NET_StringToAdr(remote, &pluginFunctions.plugins[pID].sockets[connection].remote, NA_UNSPEC);
return qtrue;
}
Com_PrintError("Plugin_TcpConnect: Connection id %d is already in use for plugin #%d!\n",connection ,pID );
return qfalse;
}
P_P_F qboolean Plugin_TcpConnect_p( int connection, const char* remote)
{
int pID;
//Identify the calling plugin
pID = Plugin_CallerID();
if(pID<0){
Com_Printf("Plugins: Error! Tried open a TCP-Connection for unknown plugin!\n");
return qfalse;
}
if(pluginFunctions.plugins[pID].enabled==qfalse){
Com_Printf("^1WARNING^7: Tried open a TCP-Connection for a disabled plugin!\n");
return qfalse;
}
if(connection >= PLUGIN_MAX_SOCKETS || connection < 0){
Com_PrintError("Plugin_TcpConnect: Second argument can only be a value inside the range: 0...%d plugin ID: #%d\n", PLUGIN_MAX_SOCKETS);
return qfalse;
}
return Plugin_TcpConnect(pID, remote, connection);
}
int Plugin_TcpGetData(int pID, int connection, void* buf, int size )
{
int len;
pluginTcpClientSocket_t* ptcs = &pluginFunctions.plugins[pID].sockets[connection];
if(ptcs->sock < 1){
Com_PrintWarning("Plugin_TcpGetData: called on a non open socket for plugin ID: #%d\n", pID);
return -1;
}
len = NET_TcpGetData(&ptcs->sock, buf, size);
return len;
}
P_P_F int Plugin_TcpGetData_p(int connection, void* buf, int size)
{
int pID;
//Identify the calling plugin
pID = Plugin_CallerID();
if(pID<0){
Com_Printf("Plugin_TcpGetData: Error! Tried get TCP data for unknown plugin!\n");
return -1;
}
if(pluginFunctions.plugins[pID].enabled==qfalse){
Com_Printf("^1WARNING^7: Plugin_TcpGetData: Tried get TCP data for a disabled plugin!\n");
return -1;
}
if(connection >= PLUGIN_MAX_SOCKETS || connection < 0){
Com_PrintError("Plugin_TcpGetData: First argument can only be a value inside the range: 0...%d plugin ID: #%d\n", PLUGIN_MAX_SOCKETS, pID);
return -1;
}
if(buf == NULL){
Com_PrintError("Plugin_TcpGetData: Third argument can not be a NULL-Pointer for plugin ID: #%d\n", pID);
return -1;
}
return Plugin_TcpGetData(pID, connection, buf, size);
}
qboolean Plugin_TcpSendData(int pID, int connection, void* data, int len)
{
pluginTcpClientSocket_t* ptcs = &pluginFunctions.plugins[pID].sockets[connection];
if(ptcs->sock < 1){
Com_PrintWarning("Plugin_TcpSendData: called on a non open socket for plugin ID: #%d\n", pID);
return qfalse;
}
return NET_TcpSendData(&ptcs->sock, data, len);
}
P_P_F qboolean Plugin_TcpSendData_p(int connection, void* data, int len)
{
int pID;
//Identify the calling plugin
pID = Plugin_CallerID();
if(pID<0){
Com_Printf("Plugin_TcpSendData: Error! Tried get TCP data for unknown plugin!\n");
return qfalse;
}
if(pluginFunctions.plugins[pID].enabled==qfalse){
Com_Printf("^1WARNING^7: Plugin_TcpSendData: Tried get TCP data for a disabled plugin!\n");
return qfalse;
}
if(connection >= PLUGIN_MAX_SOCKETS || connection < 0){
Com_PrintError("Plugin_TcpSendData: Second argument can only be a value inside the range: 0...%d plugin ID: #%d\n", PLUGIN_MAX_SOCKETS, pID);
return qfalse;
}
if(data == NULL){
Com_PrintError("Plugin_TcpSendData: Second argument can not be a NULL-Pointer for plugin ID: #%d\n", pID);
return qfalse;
}
return Plugin_TcpSendData(pID, connection, data, len);
}
void Plugin_TcpCloseConnection(int pID, int connection)
{
pluginTcpClientSocket_t* ptcs = &pluginFunctions.plugins[pID].sockets[connection];
if(ptcs->sock < 1){
Com_PrintWarning("Plugin_TcpCloseConnection: Called on a non open socket for plugin ID: #%d\n", pID);
return;
}
NET_TcpCloseConnection(&ptcs->sock);
}
P_P_F void Plugin_TcpCloseConnection_p(int connection)
{
int pID;
//Identify the calling plugin
pID = Plugin_CallerID();
if(pID<0){
Com_Printf("Plugin_TcpCloseConnection: Error! Tried get close a connection for unknown plugin!\n");
return;
}
if(pluginFunctions.plugins[pID].enabled==qfalse){
Com_Printf("^1WARNING^7: Plugin_TcpCloseConnection: Tried to close a connection for a disabled plugin!\n");
return;
}
if(connection >= PLUGIN_MAX_SOCKETS || connection < 0){
Com_PrintError("Plugin_TcpCloseConnection: Second argument can only be a value inside the range: 0...%d plugin ID: #%d\n", PLUGIN_MAX_SOCKETS, pID);
return;
}
Plugin_TcpCloseConnection(pID, connection);
}
P_P_F qboolean Plugin_UdpSendData_p(netadr_t* to, void* data, int len)
{
int pID;
if(to == NULL){
pID = Plugin_CallerID();
Com_PrintError("Plugin_UdpSendData: First argument can not be a NULL-Pointer for plugin ID: #%d\n", pID);
return qfalse;
}
if(data == NULL){
pID = Plugin_CallerID();
Com_PrintError("Plugin_UdpSendData: First argument can not be a NULL-Pointer for plugin ID: #%d\n", pID);
return qfalse;
}
return Sys_SendPacket( len, data, to);
}
P_P_F void Plugin_ServerPacketEvent_p(netadr_t* to, void* data, int len)
{
msg_t msg;
msg.data = data;
msg.cursize = len;
msg.maxsize = len;
msg.bit = 0;
msg.overflowed = qfalse;
msg.readonly = qtrue;
SV_PacketEvent( to, &msg );
}
P_P_F void Plugin_SetPlayerUID_p(unsigned int clientslot, unsigned int uid)
{
client_t *cl;
if(!psvs.useuids){
Plugin_Error(P_ERROR_TERMINATE, "Plugin tried to set UID while server don't work with UIDs\n");
}
if(clientslot > sv_maxclients->integer)
{
Plugin_Error(P_ERROR_TERMINATE, va("Plugin tried to set UID for bad client: %d\n", clientslot));
}
cl = &svs.clients[clientslot];
cl->uid = uid;
}
P_P_F unsigned int Plugin_GetPlayerUID_p(unsigned int clientslot)
{
client_t *cl;
if(!psvs.useuids){
Plugin_Error(P_ERROR_TERMINATE, "Plugin tried to get UID while server don't work with UIDs\n");
}
if(clientslot > sv_maxclients->integer)
{
Plugin_Error(P_ERROR_TERMINATE, va("Plugin tried to get UID for bad client: %d\n", clientslot));
}
cl = &svs.clients[clientslot];
return cl->uid;
}
P_P_F const char* Plugin_GetPlayerGUID_p(unsigned int clientslot)
{
client_t *cl;
if(clientslot > sv_maxclients->integer)
{
Plugin_Error(P_ERROR_TERMINATE, va("Plugin tried to get GUID for bad client: %d\n", clientslot));
}
cl = &svs.clients[clientslot];
return cl->pbguid;
}
P_P_F void Plugin_SetPlayerGUID_p(unsigned int clientslot, const char* guid)
{
client_t *cl;
if(clientslot > sv_maxclients->integer)
{
Plugin_Error(P_ERROR_TERMINATE, va("Plugin tried to get GUID for bad client: %d\n", clientslot));
}
cl = &svs.clients[clientslot];
Q_strncpyz(cl->pbguid, guid, sizeof(cl->pbguid));
}
P_P_F void Plugin_SetPlayerNoPB_p(unsigned int clientslot)
{
client_t *cl;
if(clientslot > sv_maxclients->integer)
{
Plugin_Error(P_ERROR_TERMINATE, va("Plugin tried to set No PunkBuster flag for bad client: %d\n", clientslot));
}
cl = &svs.clients[clientslot];
cl->noPb = qtrue;
}
P_P_F int Plugin_DoesServerUseUids_p(void)
{
return psvs.useuids;
}
P_P_F void Plugin_SetServerToUseUids_p(int useuids)
{
psvs.useuids = useuids;
}
P_P_F int Plugin_GetLevelTime_p(void)
{
return level.time;
}
P_P_F int Plugin_GetServerTime_p(void)
{
return svs.time;
}
#endif
|
atrX/CoD4x-Server
|
dis/plugin_handler.c
|
C
|
agpl-3.0
| 38,222
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Neil McAnaspie using IMS Development Environment (version 1.51 build 2480.15886)
// Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved.
package ims.core.forms.diagnosislist;
import java.io.Serializable;
public final class AccessLogic extends BaseAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public boolean isAccessible()
{
if(!super.isAccessible())
return false;
// TODO: Add your conditions here.
return true;
}
}
|
IMS-MAXIMS/openMAXIMS
|
Source Library/openmaxims_workspace/Core/src/ims/core/forms/diagnosislist/AccessLogic.java
|
Java
|
agpl-3.0
| 2,406
|
"""
Backfill opportunity ids for Enterprise Coupons, Enterprise Offers and Manual Order Offers.
"""
import csv
import logging
from collections import Counter, defaultdict
from time import sleep
from uuid import UUID
from django.core.management import BaseCommand
from ecommerce.core.constants import COUPON_PRODUCT_CLASS_NAME
from ecommerce.extensions.offer.models import OFFER_PRIORITY_ENTERPRISE, OFFER_PRIORITY_MANUAL_ORDER
from ecommerce.programs.custom import get_model
ConditionalOffer = get_model('offer', 'ConditionalOffer')
Product = get_model('catalogue', 'Product')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class Command(BaseCommand):
"""
Backfill opportunity ids for Enterprise Coupons, Enterprise Offers and Manual Order Offers.
"""
def add_arguments(self, parser):
parser.add_argument(
'--data-csv',
action='store',
dest='data_csv',
default=None,
help='Path of csv to read enterprise uuids and opportunity ids.',
type=str,
)
parser.add_argument(
'--contract-type',
action='store',
dest='contract_type',
default='single',
choices=['single', 'multi'],
help='Specify type of backfilling',
type=str,
)
parser.add_argument(
'--batch-limit',
action='store',
dest='batch_limit',
default=100,
help='Number of records to be fetched in each batch of backfilling.',
type=int,
)
parser.add_argument(
'--batch-offset',
action='store',
dest='batch_offset',
default=0,
help='Which index to start batching from.',
type=int,
)
parser.add_argument(
'--batch-sleep',
action='store',
dest='batch_sleep',
default=10,
help='How long to sleep between batches.',
type=int,
)
def read_csv(self, csv_path):
data = {}
with open(csv_path) as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
data[UUID(row['enterprise_customer_uuid'])] = row['opportunity_id']
return data
def read_multi_contracts_csv(self, csv_path):
data = {
'coupons': defaultdict(list),
'offers': defaultdict(list),
'ec_uuids': defaultdict(list),
}
with open(csv_path) as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
if row['ORDER_LINE_OFFER_TYPE'] == 'Voucher':
data['coupons'][row['ORDER_LINE_COUPON_ID']].append(row['OPP_ID'])
elif row['ORDER_LINE_OFFER_TYPE'] in ('Site', 'User'):
data['offers'][row['ORDER_LINE_OFFER_ID']].append(row['OPP_ID'])
else:
data['ec_uuids'][UUID(row['ENTERPRISE_CUSTOMER_UUID'])].append(row['OPP_ID'])
# condition the data so that at the end we have only one opportunity id for each coupon/offer
for __, category_data in data.items():
for category_object_id, opportunity_ids in category_data.items():
if len(opportunity_ids) > 1:
most_common_opportunity_id, __ = Counter(opportunity_ids).most_common(1)[0]
category_data[category_object_id] = most_common_opportunity_id
else:
category_data[category_object_id] = opportunity_ids[0]
return data
def get_enterprise_coupons_batch(self, coupon_filter, start, end):
logger.info('Fetching new batch of enterprise coupons from indexes: %s to %s', start, end)
return Product.objects.filter(**coupon_filter)[start:end]
def get_enterprise_offers_batch(self, offer_filter, start, end):
return ConditionalOffer.objects.filter(**offer_filter)[start:end]
def _backfill_enterprise_coupons(self, data, options, coupon_filter):
batch_limit = options['batch_limit']
batch_sleep = options['batch_sleep']
batch_offset = options['batch_offset']
current_batch_index = batch_offset
logger.info('Started Backfilling Enterprise Coupons...')
coupons = self.get_enterprise_coupons_batch(coupon_filter, batch_offset, batch_offset + batch_limit)
while coupons:
for coupon in coupons:
opportunity_id = data.get(str(coupon.id)) or data.get(UUID(coupon.attr.enterprise_customer_uuid))
if getattr(coupon.attr, 'sales_force_id', None) is None and opportunity_id:
logger.info(
'Enterprise Coupon updated. CouponID: [%s], OpportunityID: [%s]',
coupon.id,
opportunity_id
)
coupon.attr.sales_force_id = opportunity_id
coupon.save()
sleep(batch_sleep)
current_batch_index += len(coupons)
coupons = self.get_enterprise_coupons_batch(
coupon_filter, current_batch_index, current_batch_index + batch_limit
)
logger.info('Backfilling for Enterprise Coupons finished.')
def _backfill_offers(self, data, options, offer_filter, log_prefix):
logger.info('[%s] Started Backfilling Offers...', log_prefix)
batch_limit = options['batch_limit']
batch_sleep = options['batch_sleep']
batch_offset = options['batch_offset']
current_batch_index = batch_offset
ent_offers = self.get_enterprise_offers_batch(offer_filter, batch_offset, batch_offset + batch_limit)
while ent_offers:
for ent_offer in ent_offers:
opportunity_id = data.get(str(ent_offer.id)) or data.get(ent_offer.condition.enterprise_customer_uuid)
if bool(ent_offer.sales_force_id) is False and opportunity_id:
logger.info(
'[%s] Offer updated. OfferID: [%s], OpportunityID: [%s]',
log_prefix,
ent_offer.id,
opportunity_id,
)
ent_offer.sales_force_id = opportunity_id
ent_offer.save()
sleep(batch_sleep)
current_batch_index += len(ent_offers)
ent_offers = self.get_enterprise_offers_batch(
offer_filter, current_batch_index, current_batch_index + batch_limit
)
logger.info('[%s] Backfilling for Offers finished.', log_prefix)
def handle(self, *args, **options):
if options['contract_type'] == 'single':
logger.info('Backfilling for single contracts.')
self.backfill_single_contracts(options)
elif options['contract_type'] == 'multi':
logger.info('Backfilling for multi contracts.')
self.backfill_multi_contracts(options)
def backfill_single_contracts(self, options):
data = self.read_csv(options['data_csv'])
self._backfill_enterprise_coupons(data, options, {
'product_class__name': COUPON_PRODUCT_CLASS_NAME,
'attributes__code': 'enterprise_customer_uuid',
'attribute_values__value_text__in': data.keys()
})
self._backfill_offers(data, options, {
'offer_type': ConditionalOffer.SITE,
'priority': OFFER_PRIORITY_ENTERPRISE,
'condition__enterprise_customer_uuid__in': data.keys(),
}, 'ENTERPRISE OFFER')
self._backfill_offers(data, options, {
'offer_type': ConditionalOffer.USER,
'priority': OFFER_PRIORITY_MANUAL_ORDER,
'condition__enterprise_customer_uuid__in': data.keys(),
}, 'ENTERPRISE MANUAL ORDER OFFER')
def backfill_multi_contracts(self, options):
data = self.read_multi_contracts_csv(options['data_csv'])
coupons_data = data['coupons']
self._backfill_enterprise_coupons(coupons_data, options, {
'product_class__name': COUPON_PRODUCT_CLASS_NAME,
'id__in': coupons_data.keys()
})
offers_data = data['offers']
self._backfill_offers(offers_data, options, {
'offer_type__in': (ConditionalOffer.SITE, ConditionalOffer.USER),
'priority__in': (OFFER_PRIORITY_ENTERPRISE, OFFER_PRIORITY_MANUAL_ORDER),
'id__in': offers_data.keys(),
}, 'ALL ENTERPRISE OFFERS')
# backfill coupons and offers missing both coupon id and offer id
ec_uuids = data['ec_uuids']
self._backfill_enterprise_coupons(ec_uuids, options, {
'product_class__name': COUPON_PRODUCT_CLASS_NAME,
'attributes__code': 'enterprise_customer_uuid',
'attribute_values__value_text__in': ec_uuids.keys()
})
self._backfill_offers(ec_uuids, options, {
'offer_type': ConditionalOffer.SITE,
'priority': OFFER_PRIORITY_ENTERPRISE,
'condition__enterprise_customer_uuid__in': ec_uuids.keys(),
}, 'ENTERPRISE OFFER')
self._backfill_offers(ec_uuids, options, {
'offer_type': ConditionalOffer.USER,
'priority': OFFER_PRIORITY_MANUAL_ORDER,
'condition__enterprise_customer_uuid__in': ec_uuids.keys(),
}, 'ENTERPRISE MANUAL ORDER OFFER')
|
edx/ecommerce
|
ecommerce/enterprise/management/commands/backfill_opportunity_ids.py
|
Python
|
agpl-3.0
| 9,523
|
// NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// 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/>.
#include "stdmisc.h"
#include "nel/misc/big_file.h"
#include "nel/misc/path.h"
using namespace std;
using namespace NLMISC;
#ifdef DEBUG_NEW
#define new DEBUG_NEW
#endif
namespace NLMISC {
//CBigFile *CBigFile::_Singleton = NULL;
NLMISC_SAFE_SINGLETON_IMPL(CBigFile);
// ***************************************************************************
void CBigFile::releaseInstance()
{
if (_Instance)
{
NLMISC::INelContext::getInstance().releaseSingletonPointer("CBigFile", _Instance);
delete _Instance;
_Instance = NULL;
}
}
// ***************************************************************************
CBigFile::CThreadFileArray::CThreadFileArray()
{
_CurrentId= 0;
}
// ***************************************************************************
uint32 CBigFile::CThreadFileArray::allocate()
{
return _CurrentId++;
}
// ***************************************************************************
CBigFile::CHandleFile &CBigFile::CThreadFileArray::get(uint32 index)
{
// If the thread struct ptr is NULL, must allocate it.
vector<CHandleFile> *ptr= (vector<CHandleFile>*)_TDS.getPointer();
if(ptr==NULL)
{
ptr= new vector<CHandleFile>;
_TDS.setPointer(ptr);
}
// if the vector is not allocated, allocate it (empty entries filled with NULL => not opened FILE* in this thread)
if(index>=ptr->size())
{
ptr->resize(index+1);
}
return (*ptr)[index];
}
// ***************************************************************************
void CBigFile::currentThreadFinished()
{
_ThreadFileArray.currentThreadFinished();
}
// ***************************************************************************
void CBigFile::CThreadFileArray::currentThreadFinished()
{
vector<CHandleFile> *ptr= (vector<CHandleFile>*)_TDS.getPointer();
if (ptr==NULL) return;
for (uint k = 0; k < ptr->size(); ++k)
{
if ((*ptr)[k].File)
{
fclose((*ptr)[k].File);
(*ptr)[k].File = NULL;
}
}
delete ptr;
_TDS.setPointer(NULL);
}
// ***************************************************************************
//CBigFile::CBigFile ()
//{
//}
//
//// ***************************************************************************
//CBigFile &CBigFile::getInstance ()
//{
// if (_Singleton == NULL)
// {
// _Singleton = new CBigFile();
// }
// return *_Singleton;
//}
// ***************************************************************************
bool CBigFile::add (const std::string &sBigFileName, uint32 nOptions)
{
// Is already the same bigfile name ?
string bigfilenamealone = toLower(CFile::getFilename (sBigFileName));
if (_BNPs.find(bigfilenamealone) != _BNPs.end())
{
nlwarning ("CBigFile::add : bigfile %s already added.", bigfilenamealone.c_str());
return false;
}
// Create the new bnp entry
BNP &bnp = _BNPs[bigfilenamealone];
bnp.BigFileName= sBigFileName;
// Allocate a new ThreadSafe FileId for this bnp.
bnp.ThreadFileId= _ThreadFileArray.allocate();
// Get a ThreadSafe handle on the file
CHandleFile &handle= _ThreadFileArray.get(bnp.ThreadFileId);
// Open the big file.
handle.File = fopen (sBigFileName.c_str(), "rb");
if (handle.File == NULL)
return false;
uint32 nFileSize=CFile::getFileSize (handle.File);
//nlfseek64 (handle.File, 0, SEEK_END);
//uint32 nFileSize = ftell (handle.File);
// Result
if (nlfseek64 (handle.File, nFileSize-4, SEEK_SET) != 0)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
uint32 nOffsetFromBeginning;
if (fread (&nOffsetFromBeginning, sizeof(uint32), 1, handle.File) != 1)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
#ifdef NL_BIG_ENDIAN
NLMISC_BSWAP32(nOffsetFromBeginning);
#endif
if (nlfseek64 (handle.File, nOffsetFromBeginning, SEEK_SET) != 0)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
// Read the file count
uint32 nNbFile;
if (fread (&nNbFile, sizeof(uint32), 1, handle.File) != 1)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
#ifdef NL_BIG_ENDIAN
NLMISC_BSWAP32(nNbFile);
#endif
map<string,BNPFile> tempMap;
for (uint32 i = 0; i < nNbFile; ++i)
{
char FileName[256];
uint8 nStringSize;
if (fread (&nStringSize, 1, 1, handle.File) != 1)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
if (fread (FileName, nStringSize, 1, handle.File) != 1)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
FileName[nStringSize] = 0;
uint32 nFileSize2;
if (fread (&nFileSize2, sizeof(uint32), 1, handle.File) != 1)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
#ifdef NL_BIG_ENDIAN
NLMISC_BSWAP32(nFileSize2);
#endif
uint32 nFilePos;
if (fread (&nFilePos, sizeof(uint32), 1, handle.File) != 1)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
#ifdef NL_BIG_ENDIAN
NLMISC_BSWAP32(nFilePos);
#endif
BNPFile bnpfTmp;
bnpfTmp.Pos = nFilePos;
bnpfTmp.Size = nFileSize2;
tempMap.insert (make_pair(toLower(string(FileName)), bnpfTmp));
}
if (nlfseek64 (handle.File, 0, SEEK_SET) != 0)
{
fclose (handle.File);
handle.File = NULL;
return false;
}
// Convert temp map
if (nNbFile > 0)
{
uint nSize = 0, nNb = 0;
map<string,BNPFile>::iterator it = tempMap.begin();
while (it != tempMap.end())
{
nSize += (uint)it->first.size() + 1;
nNb++;
it++;
}
bnp.FileNames = new char[nSize];
memset(bnp.FileNames, 0, nSize);
bnp.Files.resize(nNb);
it = tempMap.begin();
nSize = 0;
nNb = 0;
while (it != tempMap.end())
{
strcpy(bnp.FileNames+nSize, it->first.c_str());
bnp.Files[nNb].Name = bnp.FileNames+nSize;
bnp.Files[nNb].Size = it->second.Size;
bnp.Files[nNb].Pos = it->second.Pos;
nSize += (uint)it->first.size() + 1;
nNb++;
it++;
}
}
// End of temp map conversion
if (nOptions&BF_CACHE_FILE_ON_OPEN)
bnp.CacheFileOnOpen = true;
else
bnp.CacheFileOnOpen = false;
if (!(nOptions&BF_ALWAYS_OPENED))
{
fclose (handle.File);
handle.File = NULL;
bnp.AlwaysOpened = false;
}
else
{
bnp.AlwaysOpened = true;
}
//nldebug("BigFile : added bnp '%s' to the collection", bigfilenamealone.c_str());
return true;
}
// ***************************************************************************
void CBigFile::remove (const std::string &sBigFileName)
{
if (_BNPs.find (sBigFileName) != _BNPs.end())
{
map<string, BNP>::iterator it = _BNPs.find (sBigFileName);
BNP &rbnp = it->second;
// Get a ThreadSafe handle on the file
CHandleFile &handle= _ThreadFileArray.get(rbnp.ThreadFileId);
// close it if needed
if (handle.File != NULL)
{
fclose (handle.File);
handle.File= NULL;
}
delete [] rbnp.FileNames;
_BNPs.erase (it);
}
}
// ***************************************************************************
bool CBigFile::isBigFileAdded(const std::string &sBigFileName) const
{
// Is already the same bigfile name ?
string bigfilenamealone = CFile::getFilename (sBigFileName);
return _BNPs.find(bigfilenamealone) != _BNPs.end();
}
// ***************************************************************************
std::string CBigFile::getBigFileName(const std::string &sBigFileName) const
{
string bigfilenamealone = CFile::getFilename (sBigFileName);
map<string, BNP>::const_iterator it = _BNPs.find(bigfilenamealone);
if (it != _BNPs.end())
return it->second.BigFileName;
else
return "";
}
// ***************************************************************************
void CBigFile::list (const std::string &sBigFileName, std::vector<std::string> &vAllFiles)
{
string lwrFileName = toLower(sBigFileName);
if (_BNPs.find (lwrFileName) == _BNPs.end())
return;
vAllFiles.clear ();
BNP &rbnp = _BNPs.find (lwrFileName)->second;
vector<BNPFile>::iterator it = rbnp.Files.begin();
while (it != rbnp.Files.end())
{
vAllFiles.push_back (string(it->Name)); // Add the name of the file to the return vector
++it;
}
}
// ***************************************************************************
void CBigFile::removeAll ()
{
while (_BNPs.begin() != _BNPs.end())
{
remove (_BNPs.begin()->first);
}
}
// ***************************************************************************
bool CBigFile::getFileInternal (const std::string &sFileName, BNP *&zeBnp, BNPFile *&zeBnpFile)
{
string zeFileName, zeBigFileName, lwrFileName = toLower(sFileName);
string::size_type i, nPos = sFileName.find ('@');
if (nPos == string::npos)
{
return false;
}
for (i = 0; i < nPos; ++i)
zeBigFileName += lwrFileName[i];
++i; // Skip @
for (; i < lwrFileName.size(); ++i)
zeFileName += lwrFileName[i];
if (_BNPs.find (zeBigFileName) == _BNPs.end())
{
return false;
}
BNP &rbnp = _BNPs.find (zeBigFileName)->second;
if (rbnp.Files.size() == 0)
{
return false;
}
vector<BNPFile>::iterator itNBPFile;
BNPFile temp_bnp_file;
temp_bnp_file.Name = (char*)zeFileName.c_str();
itNBPFile = lower_bound(rbnp.Files.begin(), rbnp.Files.end(), temp_bnp_file, CBNPFileComp());
if (itNBPFile != rbnp.Files.end())
{
if (strcmp(itNBPFile->Name, zeFileName.c_str()) != 0)
{
return false;
}
}
else
{
return false;
}
BNPFile &rbnpfile = *itNBPFile;
// set ptr on found bnp/bnpFile
zeBnp= &rbnp;
zeBnpFile= &rbnpfile;
return true;
}
// ***************************************************************************
FILE* CBigFile::getFile (const std::string &sFileName, uint32 &rFileSize,
uint32 &rBigFileOffset, bool &rCacheFileOnOpen, bool &rAlwaysOpened)
{
BNP *bnp= NULL;
BNPFile *bnpFile= NULL;
if(!getFileInternal(sFileName, bnp, bnpFile))
{
nlwarning ("BF: Couldn't load '%s'", sFileName.c_str());
return NULL;
}
nlassert(bnp && bnpFile);
// Get a ThreadSafe handle on the file
CHandleFile &handle= _ThreadFileArray.get(bnp->ThreadFileId);
/* If not opened, open it now. There is 2 reason for it to be not opened:
rbnp.AlwaysOpened==false, or it is a new thread which use it for the first time.
*/
if(handle.File== NULL)
{
handle.File = fopen (bnp->BigFileName.c_str(), "rb");
if (handle.File == NULL)
{
nlwarning ("bnp: can't fopen big file '%s' error %d '%s'", bnp->BigFileName.c_str(), errno, strerror(errno));
return NULL;
}
}
rCacheFileOnOpen = bnp->CacheFileOnOpen;
rAlwaysOpened = bnp->AlwaysOpened;
rBigFileOffset = bnpFile->Pos;
rFileSize = bnpFile->Size;
return handle.File;
}
// ***************************************************************************
bool CBigFile::getFileInfo (const std::string &sFileName, uint32 &rFileSize, uint32 &rBigFileOffset)
{
BNP *bnp= NULL;
BNPFile *bnpFile= NULL;
if(!getFileInternal(sFileName, bnp, bnpFile))
{
nlwarning ("BF: Couldn't find '%s' for info", sFileName.c_str());
return false;
}
nlassert(bnp && bnpFile);
// get infos
rBigFileOffset = bnpFile->Pos;
rFileSize = bnpFile->Size;
return true;
}
// ***************************************************************************
char *CBigFile::getFileNamePtr(const std::string &sFileName, const std::string &sBigFileName)
{
string bigfilenamealone = CFile::getFilename (sBigFileName);
if (_BNPs.find(bigfilenamealone) != _BNPs.end())
{
BNP &rbnp = _BNPs.find (bigfilenamealone)->second;
vector<BNPFile>::iterator itNBPFile;
if (rbnp.Files.size() == 0)
return NULL;
string lwrFileName = toLower(sFileName);
BNPFile temp_bnp_file;
temp_bnp_file.Name = (char*)lwrFileName.c_str();
itNBPFile = lower_bound(rbnp.Files.begin(), rbnp.Files.end(), temp_bnp_file, CBNPFileComp());
if (itNBPFile != rbnp.Files.end())
{
if (strcmp(itNBPFile->Name, lwrFileName.c_str()) == 0)
{
return itNBPFile->Name;
}
}
}
return NULL;
}
// ***************************************************************************
void CBigFile::getBigFilePaths(std::vector<std::string> &bigFilePaths)
{
bigFilePaths.clear();
for(std::map<std::string, BNP>::iterator it = _BNPs.begin(); it != _BNPs.end(); ++it)
{
bigFilePaths.push_back(it->second.BigFileName);
}
}
} // namespace NLMISC
|
jinxiaoye1987/RyzomCore
|
nel/src/misc/big_file.cpp
|
C++
|
agpl-3.0
| 12,754
|
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo.lookups;
import ims.framework.cn.data.TreeNode;
import java.util.ArrayList;
import ims.framework.utils.Image;
import ims.framework.utils.Color;
public class VSTempInstrument extends ims.vo.LookupInstVo implements TreeNode
{
private static final long serialVersionUID = 1L;
public VSTempInstrument()
{
super();
}
public VSTempInstrument(int id)
{
super(id, "", true);
}
public VSTempInstrument(int id, String text, boolean active)
{
super(id, text, active, null, null, null);
}
public VSTempInstrument(int id, String text, boolean active, VSTempInstrument parent, Image image)
{
super(id, text, active, parent, image);
}
public VSTempInstrument(int id, String text, boolean active, VSTempInstrument parent, Image image, Color color)
{
super(id, text, active, parent, image, color);
}
public VSTempInstrument(int id, String text, boolean active, VSTempInstrument parent, Image image, Color color, int order)
{
super(id, text, active, parent, image, color, order);
}
public static VSTempInstrument buildLookup(ims.vo.LookupInstanceBean bean)
{
return new VSTempInstrument(bean.getId(), bean.getText(), bean.isActive());
}
public String toString()
{
if(getText() != null)
return getText();
return "";
}
public TreeNode getParentNode()
{
return (VSTempInstrument)super.getParentInstance();
}
public VSTempInstrument getParent()
{
return (VSTempInstrument)super.getParentInstance();
}
public void setParent(VSTempInstrument parent)
{
super.setParentInstance(parent);
}
public TreeNode[] getChildren()
{
ArrayList children = super.getChildInstances();
VSTempInstrument[] typedChildren = new VSTempInstrument[children.size()];
for (int i = 0; i < children.size(); i++)
{
typedChildren[i] = (VSTempInstrument)children.get(i);
}
return typedChildren;
}
public int addChild(TreeNode child)
{
if (child instanceof VSTempInstrument)
{
super.addChild((VSTempInstrument)child);
}
return super.getChildInstances().size();
}
public int removeChild(TreeNode child)
{
if (child instanceof VSTempInstrument)
{
super.removeChild((VSTempInstrument)child);
}
return super.getChildInstances().size();
}
public Image getExpandedImage()
{
return super.getImage();
}
public Image getCollapsedImage()
{
return super.getImage();
}
public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection()
{
VSTempInstrumentCollection result = new VSTempInstrumentCollection();
return result;
}
public static VSTempInstrument[] getNegativeInstances()
{
return new VSTempInstrument[] {};
}
public static String[] getNegativeInstanceNames()
{
return new String[] {};
}
public static VSTempInstrument getNegativeInstance(String name)
{
if(name == null)
return null;
// No negative instances found
return null;
}
public static VSTempInstrument getNegativeInstance(Integer id)
{
if(id == null)
return null;
// No negative instances found
return null;
}
public int getTypeId()
{
return TYPE_ID;
}
public static final int TYPE_ID = 1021051;
}
|
FreudianNM/openMAXIMS
|
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/lookups/VSTempInstrument.java
|
Java
|
agpl-3.0
| 5,327
|
<?php
// Prevent loading this file directly
if ( !defined('SENDPRESS_VERSION') ) {
header('HTTP/1.0 403 Forbidden');
die;
}
class SendPress_View_Help extends SendPress_View{
function prerender($sp = false){
wp_enqueue_script( 'dashboard' );
sp_add_help_widget( 'help_support', 'Contact Us', array(&$this,'help_support'));
//sp_add_help_widget( 'help_knowledge', 'Recent Knowledge Base Articles', array(&$this,'help_knowledge'),'side' );
sp_add_help_widget( 'help_debug', 'Debug Information', array(&$this,'help_debug'), 'side');
//sp_add_help_widget( 'help_blog', 'Recent Blog Posts', array(&$this,'help_blog'),'normal', array(&$this,'help_blog_control') );
sp_add_help_widget( 'help_shortcodes', 'Shortcode Cheat Sheet', array(&$this,'help_shortcodes') ,'normal');
sp_add_help_widget( 'help_editemail', 'Customizing Emails', array(&$this,'help_editemail') ,'normal');
}
function help_editemail(){
?>
<b>SendPress Editor Button</b>
<p>Look for this button <img src="<?php echo SENDPRESS_URL; ?>/js/icon.png" /> to open the popup for adding posts to an email and personilizing emails.</p>
<?php
}
function help_shortcodes(){ ?>
<p class="lead">Click a title to view info about a shortcode.</p>
<?php
SendPress_Shortcode_Loader::docs();
}
function help_support(){
?>
<b>Basic Support</b>
<p>You can get support for the FREE version of SendPress on the <a href="http://wordpress.org/support/plugin/sendpress" target="_blank">WordPress.org forums</a>.<br>Also check our <a href="http://sendpress.com/support" target="_blank">Knowledge Base</a> for help at <a href="http://docs.sendpress.com/" target="_blank">http://docs.sendpress.com/</a></p>
<br>
<b>Premium Support</b>
<p>Premium support is available if you have purchased SendPress Pro from SendPress.com. Premium support can be accessed via our support site: <a href="http://sendpress.com/your-account" target="_blank">http://sendpress.com/your-account</a> and requires a SendPress.com account.</p>
<?php
}
function display() {
$browser = NEW SendPress_Browser();
if ( get_bloginfo( 'version' ) < '3.4' ) {
$theme_data = get_theme_data( get_stylesheet_directory() . '/style.css' );
$theme = $theme_data['Name'] . ' ' . $theme_data['Version'];
} else {
$theme_data = wp_get_theme();
$theme = $theme_data->Name . ' ' . $theme_data->Version;
}
// Try to identify the hosting provider
$host = false;
if ( defined( 'WPE_APIKEY' ) ) {
$host = 'WP Engine';
} elseif ( defined( 'PAGELYBIN' ) ) {
$host = 'Pagely';
}
$request['cmd'] = '_notify-validate';
$params = array(
'sslverify' => false,
'timeout' => 60,
'body' => $request,
);
$response = wp_remote_post( 'https://www.paypal.com/cgi-bin/webscr', $params );
if ( ! is_wp_error( $response ) && $response['response']['code'] >= 200 && $response['response']['code'] < 300 ) {
$WP_REMOTE_POST = 'wp_remote_post() works' . "\n";
} else {
$WP_REMOTE_POST = 'wp_remote_post() does not work' . "\n";
}
return $this->display_output( $browser, $theme, $host, $WP_REMOTE_POST );
}
//Render Info Display
function display_output( $browser, $theme, $host, $WP_REMOTE_POST ) {
global $wpdb;
ob_start();
require_once( SENDPRESS_PATH . 'inc/output.php' );
return ob_get_clean();
}
function help_debug(){
global $wp_version,$wpdb;
$browser = NEW SendPress_Browser();
echo "<b>WordPress Version</b>: ". $wp_version."<br>";
echo "<b>SendPress Version</b>: ".SENDPRESS_VERSION ."<br>";
if(defined('SENDPRESS_PRO_VERSION')){
echo "<b>SendPress Pro Version</b>: ".SENDPRESS_VERSION ."<br>";
}
echo '<b>PHP Version</b>: ' . phpversion(). '<br>';
$mem = (int) ini_get('memory_limit') ;
$used = function_exists('memory_get_usage') ? round(memory_get_usage() / 1024 / 1024, 2) : 0;
if(!empty( $mem ) && !empty( $used ) ){
$prec = round ( $used / $mem * 100, 0);
}
echo '<b>PHP Memory Limit</b>: '. $mem . __(' MByte') . '<br>';
echo '<b>PHP Memory Used</b>: '. $used . __(' MByte') . '<br>';
echo '<b>MySQL Version</b>: ' . $wpdb->db_version() . '<br><br>';
echo '<b>Send Setup</b>: ' . SendPress_Option::get( 'sendmethod' ) . '<br><br>';
SendPress_DB_Tables::check_setup();
/*
echo "<b>Ports:</b><br>";
$server = "smtp.sendgrid.net";
$port = "25";
$port2 = "465";
$port3 = "587";
$timeout = "1";
if ($server and $port and $timeout) {
$port25 = @fsockopen("$server", $port, $errno, $errstr, $timeout);
$port465 = @fsockopen("$server", $port2, $errno, $errstr, $timeout);
$port587 = @fsockopen("$server", $port3, $errno, $errstr, $timeout);
}
echo "Port 25: ";
if(!$port25){
_e('blocked','sendpress');
} else {
_e('open','sendpress');
}
echo "<br>Port 465: ";
if(!$port465){
_e('blocked','sendpress');
} else {
_e('open','sendpress');
}
echo "<br>Port 587: ";
if(!$port587){
_e('blocked','sendpress');
} else {
_e('open','sendpress');
} */?><br><br>
<b>Support Info:</b>
<textarea readonly="readonly" class="sendpress-sysinfo" name="sendpress-sysinfo" title="<?php _e( 'To copy the system info, click below then press Ctrl + C (PC) or Cmd + C (Mac).', 'sendpress' ); ?>"><?php echo esc_html( $this->display() ); ?></textarea>
<?php
}
function help_blog(){
// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed('http://sendpress.com/feed');
if (!is_wp_error( $rss ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 5.
$maxitems = $rss->get_item_quantity(5);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items(0, $maxitems);
endif;
?>
<ul>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<li>
<a href='<?php echo esc_url( $item->get_permalink() ); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo esc_html( $item->get_title() ); ?></a>
</li>
<?php endforeach; ?>
</ul><?php
}
function help_knowledge(){
// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed('http://sendpress.com/support/feed/?post_type=knowledgebase');
if (!is_wp_error( $rss ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 5.
$maxitems = $rss->get_item_quantity(5);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items(0, $maxitems);
endif;
?>
<ul>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<li>
<a href='<?php echo esc_url( $item->get_permalink() ); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo esc_html( $item->get_title() ); ?></a>
</li>
<?php endforeach; ?>
</ul><?php
}
function help_knowledge_control(){
echo "Add Some settings";
}
function html($sp){
SendPress_Tracking::event('Help Tab');
global $wp_version;
$screen = get_current_screen();
$class = 'columns-2';//. get_current_screen()->get_columns();
?>
<div id="dashboard-widgets" class="metabox-holder clearfix <?php echo $class; ?>">
<div id='postbox-container-1' class='postbox-container'>
<?php do_meta_boxes( $screen->id, 'normal', '' ); ?>
</div>
<div id='postbox-container-2' class='postbox-container'>
<?php do_meta_boxes( $screen->id, 'side', '' ); ?>
</div>
<div id='postbox-container-3' class='postbox-container'>
<?php do_meta_boxes( $screen->id, 'column3', '' ); ?>
</div>
<div id='postbox-container-4' class='postbox-container'>
<?php do_meta_boxes( $screen->id, 'column4', '' ); ?>
</div>
</div>
<?php
wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
}
}
// Add Access Controll!
SendPress_Admin::add_cap('Help','sendpress_view');
//SendPress_View_Overview::cap('sendpress_access');
function _sp_help_control_callback( $dashboard, $meta_box ) {
echo '<form action="" method="post" class="dashboard-widget-control-form">';
wp_dashboard_trigger_widget_control( $meta_box['id'] );
echo '<input type="hidden" name="widget_id" value="' . esc_attr($meta_box['id']) . '" />';
submit_button( __('Submit') );
echo '</form>';
}
function sp_add_help_widget( $widget_id, $widget_name, $callback, $location =null, $control_callback = null ) {
$screen = get_current_screen();
global $wp_dashboard_control_callbacks;
if ( $control_callback && current_user_can( 'edit_dashboard' ) && is_callable( $control_callback ) ) {
$wp_dashboard_control_callbacks[$widget_id] = $control_callback;
if ( isset( $_GET['edit'] ) && $widget_id == $_GET['edit'] ) {
//Uses esc_url
list($url) = explode( '#', add_query_arg( 'edit', false ), 2 );
$widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( $url ) . '">' . __( 'Cancel' ) . '</a></span>';
$callback = '_sp_help_control_callback';
} else {
//Uses esc_url
list($url) = explode( '#', add_query_arg( 'edit', $widget_id ), 2 );
$widget_name .= ' <span class="postbox-title-action"><a href="' . esc_url( "$url#$widget_id" ) . '" class="edit-box open-box">' . __( 'Configure' ) . '</a></span>';
}
}
if ( is_blog_admin () )
$side_widgets = array('dashboard_quick_press', 'dashboard_recent_drafts', 'dashboard_primary', 'dashboard_secondary');
else if (is_network_admin() )
$side_widgets = array('dashboard_primary', 'dashboard_secondary');
else
$side_widgets = array();
if( $location == null)
$location = 'normal';
if ( in_array($widget_id, $side_widgets) )
$location = 'side';
$priority = 'core';
if ( 'dashboard_browser_nag' === $widget_id )
$priority = 'high';
add_meta_box( $widget_id, $widget_name, $callback, $screen, $location, $priority );
}
|
pmatheus/participacao-sitebase
|
src/wp-content/plugins/sendpress/classes/views/class-sendpress-view-help.php
|
PHP
|
agpl-3.0
| 10,300
|
//#############################################################################
//# #
//# 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: 16/04/2014, 12:34
*
*/
package ims.careuk.domain.objects;
/**
*
* @author Neil McAnaspie
* Generated.
*/
public class ReviewReferralDetail extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1096100019;
private static final long serialVersionUID = 1096100019L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
/** Review Type */
private ims.domain.lookups.LookupInstance reviewType;
/** ReasonNotes */
private String reasonNotes;
/** ReviewedDate */
private java.util.Date reviewedDate;
/** Reviewed By */
private ims.core.resource.people.domain.objects.MemberOfStaff reviewedBy;
/** ReviewNotes */
private String reviewNotes;
/** Recording User */
private ims.core.resource.people.domain.objects.MemberOfStaff recordingUser;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public ReviewReferralDetail (Integer id, int ver)
{
super(id, ver);
}
public ReviewReferralDetail ()
{
super();
}
public ReviewReferralDetail (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
}
public Class getRealDomainClass()
{
return ims.careuk.domain.objects.ReviewReferralDetail.class;
}
public ims.domain.lookups.LookupInstance getReviewType() {
return reviewType;
}
public void setReviewType(ims.domain.lookups.LookupInstance reviewType) {
this.reviewType = reviewType;
}
public String getReasonNotes() {
return reasonNotes;
}
public void setReasonNotes(String reasonNotes) {
if ( null != reasonNotes && reasonNotes.length() > 255 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for reasonNotes. Tried to set value: "+
reasonNotes);
}
this.reasonNotes = reasonNotes;
}
public java.util.Date getReviewedDate() {
return reviewedDate;
}
public void setReviewedDate(java.util.Date reviewedDate) {
this.reviewedDate = reviewedDate;
}
public ims.core.resource.people.domain.objects.MemberOfStaff getReviewedBy() {
return reviewedBy;
}
public void setReviewedBy(ims.core.resource.people.domain.objects.MemberOfStaff reviewedBy) {
this.reviewedBy = reviewedBy;
}
public String getReviewNotes() {
return reviewNotes;
}
public void setReviewNotes(String reviewNotes) {
if ( null != reviewNotes && reviewNotes.length() > 255 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for reviewNotes. Tried to set value: "+
reviewNotes);
}
this.reviewNotes = reviewNotes;
}
public ims.core.resource.people.domain.objects.MemberOfStaff getRecordingUser() {
return recordingUser;
}
public void setRecordingUser(ims.core.resource.people.domain.objects.MemberOfStaff recordingUser) {
this.recordingUser = recordingUser;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*reviewType* :");
if (reviewType != null)
auditStr.append(reviewType.getText());
auditStr.append("; ");
auditStr.append("\r\n*reasonNotes* :");
auditStr.append(reasonNotes);
auditStr.append("; ");
auditStr.append("\r\n*reviewedDate* :");
auditStr.append(reviewedDate);
auditStr.append("; ");
auditStr.append("\r\n*reviewedBy* :");
if (reviewedBy != null)
{
auditStr.append(toShortClassName(reviewedBy));
auditStr.append(reviewedBy.getId());
}
auditStr.append("; ");
auditStr.append("\r\n*reviewNotes* :");
auditStr.append(reviewNotes);
auditStr.append("; ");
auditStr.append("\r\n*recordingUser* :");
if (recordingUser != null)
{
auditStr.append(toShortClassName(recordingUser));
auditStr.append(recordingUser.getId());
}
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" id=\"" + this.getId() + "\"");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
String keyClassName = "ReviewReferralDetail";
String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName();
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId());
if (impObj == null)
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(this.getId());
impObj.setExternalSource(externalSource);
impObj.setDomainObject(this);
impObj.setLocalId(this.getId());
impObj.setClassName(keyClassName);
domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj);
}
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getReviewType() != null)
{
sb.append("<reviewType>");
sb.append(this.getReviewType().toXMLString());
sb.append("</reviewType>");
}
if (this.getReasonNotes() != null)
{
sb.append("<reasonNotes>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getReasonNotes().toString()));
sb.append("</reasonNotes>");
}
if (this.getReviewedDate() != null)
{
sb.append("<reviewedDate>");
sb.append(new ims.framework.utils.DateTime(this.getReviewedDate()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</reviewedDate>");
}
if (this.getReviewedBy() != null)
{
sb.append("<reviewedBy>");
sb.append(this.getReviewedBy().toXMLString(domMap));
sb.append("</reviewedBy>");
}
if (this.getReviewNotes() != null)
{
sb.append("<reviewNotes>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getReviewNotes().toString()));
sb.append("</reviewNotes>");
}
if (this.getRecordingUser() != null)
{
sb.append("<recordingUser>");
sb.append(this.getRecordingUser().toXMLString(domMap));
sb.append("</recordingUser>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
ReviewReferralDetail domainObject = getReviewReferralDetailfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.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())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
ReviewReferralDetail domainObject = getReviewReferralDetailfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.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=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static ReviewReferralDetail getReviewReferralDetailfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getReviewReferralDetailfromXML(doc.getRootElement(), factory, domMap);
}
public static ReviewReferralDetail getReviewReferralDetailfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!ReviewReferralDetail.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!ReviewReferralDetail.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the ReviewReferralDetail class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (ReviewReferralDetail)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(ReviewReferralDetail.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
ReviewReferralDetail ret = null;
int extId = Integer.parseInt(el.attributeValue("id"));
String externalSource = el.attributeValue("source");
ret = (ReviewReferralDetail)factory.getImportedDomainObject(ReviewReferralDetail.class, externalSource, extId);
if (ret == null)
{
ret = new ReviewReferralDetail();
}
String keyClassName = "ReviewReferralDetail";
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId);
if (impObj != null)
{
return (ReviewReferralDetail)impObj.getDomainObject();
}
else
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(extId);
impObj.setExternalSource(externalSource);
impObj.setDomainObject(ret);
domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj);
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, ReviewReferralDetail obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("reviewType");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setReviewType(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("reasonNotes");
if(fldEl != null)
{
obj.setReasonNotes(new String(fldEl.getTextTrim()));
}
fldEl = el.element("reviewedDate");
if(fldEl != null)
{
obj.setReviewedDate(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("reviewedBy");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setReviewedBy(ims.core.resource.people.domain.objects.MemberOfStaff.getMemberOfStafffromXML(fldEl, factory, domMap));
}
fldEl = el.element("reviewNotes");
if(fldEl != null)
{
obj.setReviewNotes(new String(fldEl.getTextTrim()));
}
fldEl = el.element("recordingUser");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setRecordingUser(ims.core.resource.people.domain.objects.MemberOfStaff.getMemberOfStafffromXML(fldEl, factory, domMap));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
public static class FieldNames
{
public static final String ID = "id";
public static final String ReviewType = "reviewType";
public static final String ReasonNotes = "reasonNotes";
public static final String ReviewedDate = "reviewedDate";
public static final String ReviewedBy = "reviewedBy";
public static final String ReviewNotes = "reviewNotes";
public static final String RecordingUser = "recordingUser";
}
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/DomainObjects/src/ims/careuk/domain/objects/ReviewReferralDetail.java
|
Java
|
agpl-3.0
| 16,545
|
# Copyright (c) 2008 The Kaphan Foundation
#
# For licensing information see LICENSE.
#
# Please visit http://www.peerworks.org/contact for further information.
#
require File.dirname(__FILE__) + '/../spec_helper'
require 'atom'
require 'atom/pub'
require 'atom/version'
require 'uri'
require 'net/http'
shared_examples_for 'parser of spec/app/service.xml' do
it "should have 2 workspaces" do
@service.should have(2).workspaces
end
it "should have a title" do
@workspace.title.should == "Main Site"
end
it "should have 2 collections" do
@workspace.should have(2).collections
end
it "should have the right href" do
@collection1.href.should == 'http://example.org/blog/main'
end
it "should have categories" do
@collection1.categories.should_not be_nil
end
it "should have a href on categories" do
@collection1.categories.href.should == "http://example.org/cats/forMain.cats"
@collection1.categories.fixed?.should be_false
end
it "should have a title" do
@collection1.title.should == 'My Blog Entries'
end
it "should have a title" do
@collection2.title.should == 'Pictures'
end
it "should have the right href" do
@collection2.href.should == 'http://example.org/blog/pic'
end
it "should not have categories" do
@collection2.categories.should be_nil
end
it "should have 3 accepts" do
@collection2.should have(3).accepts
end
it "should accept 'image/png'" do
@collection2.accepts.should include('image/png')
end
it "should accept 'image/jpeg'" do
@collection2.accepts.should include('image/jpeg')
end
it "should accept 'image/gif'" do
@collection2.accepts.should include('image/gif')
end
it "should have a title on workspace 2" do
@workspace2.title.should == 'Sidebar Blog'
end
it "should have 1 collection on workspace 2" do
@workspace2.should have(1).collections
end
it "should have a title on collection 3" do
@collection3.title.should == 'Remaindered Links'
end
it "should have 1 accept on collection 3" do
@collection3.should have(1).accepts
end
it "should accept 'application/atom+xml;type=entry'" do
@collection3.accepts.should include('application/atom+xml;type=entry')
end
it "should have categories" do
@collection3.categories.should_not be_nil
end
it "should have fixed == 'yes' on categories" do
@collection3.categories.fixed.should == "yes"
end
it "should have fixed? == true on categories" do
@collection3.categories.fixed?.should be_true
end
end
describe Atom::Pub do
describe Atom::Pub::Service do
it "should load from a URL" do
uri = URI.parse('http://example.com/service.xml')
response = Net::HTTPSuccess.new(nil, nil, nil)
response.stub!(:body).and_return(File.read('spec/app/service.xml'))
mock_http_get(uri, response)
Atom::Pub::Service.load_service(uri).should be_an_instance_of(Atom::Pub::Service)
end
it "should raise ArgumentError with a non-http URL" do
lambda { Atom::Pub::Service.load_service(URI.parse('file:/tmp')) }.should raise_error(ArgumentError)
end
it "should be able to be created without xml" do
lambda { Atom::Pub::Service.new }.should_not raise_error
end
it "should yield in the initializer" do
yielded = false
Atom::Pub::Service.new do
yielded = true
end
yielded.should be_true
end
it "should parse it's output" do
orig = File.read('spec/app/service.xml')
svc = Atom::Pub::Service.load_service(orig)
xml = svc.to_xml
lambda do
Atom::Pub::Service.load_service(xml)
end.should_not raise_error
end
describe "load_service" do
before(:all) do
@service = Atom::Pub::Service.load_service(File.open('spec/app/service.xml'))
@workspace = @service.workspaces.first
@workspace2 = @service.workspaces[1]
@collection1 = @workspace.collections.first
@collection2 = @workspace.collections[1]
@collection3 = @workspace2.collections.first
end
it_should_behave_like 'parser of spec/app/service.xml'
end
describe "load service with xml:base" do
before(:all) do
@service = Atom::Pub::Service.load_service(File.open('spec/app/service_xml_base.xml'))
@workspace = @service.workspaces.first
@workspace2 = @service.workspaces[1]
@collection1 = @workspace.collections.first
@collection2 = @workspace.collections[1]
@collection3 = @workspace2.collections.first
end
it_should_behave_like 'parser of spec/app/service.xml'
end
describe "load_service with authentication" do
it "should pass credentials to the server" do
uri = URI.parse('http://example.com/service.xml')
response = Net::HTTPSuccess.new(nil, nil, nil)
response.stub!(:body).and_return(File.read('spec/app/service.xml'))
mock_http_get(uri, response, 'user', 'pass')
Atom::Pub::Service.load_service(uri, :user => 'user', :pass => 'pass')
end
it "should pass credentials on to the collections" do
uri = URI.parse('http://example.com/service.xml')
response = Net::HTTPSuccess.new(nil, nil, nil)
response.stub!(:body).and_return(File.read('spec/app/service.xml'))
mock_http_get(uri, response, 'user', 'pass')
pub = Atom::Pub::Service.load_service(uri, :user => 'user', :pass => 'pass')
uri2 = URI.parse('http://example.org/blog/main')
response2 = Net::HTTPSuccess.new(nil, nil, nil)
response2.stub!(:body).and_return(File.read('spec/fixtures/simple_single_entry.atom'))
mock_http_get(uri2, response2, 'user', 'pass')
pub.workspaces.first.collections.first.feed(:user => 'user', :pass => 'pass')
end
end
describe "#to_xml" do
before(:each) do
@svc = Atom::Pub::Service.load_service(File.read('spec/app/service.xml'))
@xml = @svc.to_xml
@service = Atom::Pub::Service.load_service(@xml)
@workspace = @service.workspaces.first
@workspace2 = @service.workspaces[1]
@collection1 = @workspace.collections.first
@collection2 = @workspace.collections[1]
@collection3 = @workspace2.collections.first
end
it "should put title in Atom namespace" do
@xml.should match(%r{atom:title})
end
it_should_behave_like 'parser of spec/app/service.xml'
end
end
describe Atom::Pub::Collection do
describe '.new' do
it "should set the href from the hash" do
collection = Atom::Pub::Collection.new(:href => 'http://example.org/blog')
collection.href.should == 'http://example.org/blog'
end
it "should set the href from a block" do
collection = Atom::Pub::Collection.new do |c|
c.href = "http://example.org/blog"
end
collection.href.should == 'http://example.org/blog'
end
end
it "should return the feed" do
collection = Atom::Pub::Collection.new(:href => 'http://example.org/blog')
response = Net::HTTPSuccess.new(nil, nil, nil)
response.stub!(:body).and_return(File.read('spec/fixtures/simple_single_entry.atom'))
mock_http_get(URI.parse(collection.href), response)
collection.feed.should be_an_instance_of(Atom::Feed)
end
describe '#publish' do
before(:each) do
@collection = Atom::Pub::Collection.new(:href => 'http://example.org/blog')
@request_headers = {'Accept' => 'application/atom+xml',
'Content-Type' => 'application/atom+xml;type=entry',
'User-Agent' => "rAtom #{Atom::VERSION::STRING}"
}
end
it "should send a POST request when an entry is published" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
response = mock_response(Net::HTTPCreated, entry.to_xml.to_s)
request = mock('request')
Net::HTTP::Post.should_receive(:new).with('/blog', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
created = @collection.publish(entry)
created.should == entry
end
it "should send a POST with basic auth request when an entry is published" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
response = mock_response(Net::HTTPCreated, entry.to_xml.to_s)
request = mock('request')
request.should_receive(:basic_auth).with('user', 'pass')
Net::HTTP::Post.should_receive(:new).with('/blog', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
created = @collection.publish(entry, :user => 'user', :pass => 'pass')
created.should == entry
end
if Atom::Configuration.auth_hmac_enabled?
it "should send a POST with hmac authentication when an entry is published" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
response = mock_response(Net::HTTPCreated, entry.to_xml.to_s)
http = mock('http')
http.should_receive(:request) do |request, entry_xml|
request['Authorization'].should match(/^AuthHMAC access_id:[a-zA-Z0-9\/+]+=*/)
response
end
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
created = @collection.publish(entry, :hmac_access_id => 'access_id', :hmac_secret_key => 'secret')
created.should == entry
end
else
xit "should send a POST with hmac authentication when an entry is published"
end
it "should behave well when no content is returned" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
response = mock_response(Net::HTTPCreated, " ")
request = mock('request')
Net::HTTP::Post.should_receive(:new).with('/blog', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
created = @collection.publish(entry)
created.should == entry
end
it "should raise error when response is not HTTPCreated" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
response = mock_response(Net::HTTPPreconditionFailed, "")
request = mock('request')
Net::HTTP::Post.should_receive(:new).with('/blog', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
lambda { @collection.publish(entry) }.should raise_error(Atom::Pub::ProtocolError)
end
it "should copy Location into edit link of entry" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
response = mock_response(Net::HTTPCreated, entry.to_xml.to_s, 'Location' => 'http://example.org/edit/entry1.atom')
request = mock('request')
Net::HTTP::Post.should_receive(:new).with('/blog', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
created = @collection.publish(entry)
created.edit_link.should_not be_nil
created.edit_link.href.should == 'http://example.org/edit/entry1.atom'
end
it "should update the entry when response is different" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
response = mock_response(Net::HTTPCreated, File.read('spec/fixtures/created_entry.atom'),
'Location' => 'http://example.org/edit/atom')
request = mock('request')
Net::HTTP::Post.should_receive(:new).with('/blog', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
created = @collection.publish(entry)
created.should == Atom::Entry.load_entry(File.open('spec/fixtures/created_entry.atom'))
end
end
end
describe Atom::Pub::Workspace do
it "should do the block initialization thing" do
workspace = Atom::Pub::Workspace.new do |w|
w.title = "Title"
end
workspace.title.should == "Title"
end
it "should do the hash initialization thing" do
workspace = Atom::Pub::Workspace.new(:title => 'Title')
workspace.title.should == "Title"
end
end
describe Atom::Entry do
before(:each) do
@request_headers = {'Accept' => 'application/atom+xml',
'Content-Type' => 'application/atom+xml;type=entry',
'User-Agent' => "rAtom #{Atom::VERSION::STRING}"
}
end
it "should send a PUT to the edit link on save!" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPSuccess, nil)
request = mock('request')
Net::HTTP::Put.should_receive(:new).with('/member_entry.atom', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
entry.save!
end
it "should send a PUT with auth to the edit link on save!" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPSuccess, nil)
request = mock('request')
request.should_receive(:basic_auth).with('user', 'pass')
Net::HTTP::Put.should_receive(:new).with('/member_entry.atom', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
entry.save!(:user => 'user', :pass => 'pass')
end
if Atom::Configuration.auth_hmac_enabled?
it "should send a PUT with hmac auth to the edit link on save!" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPSuccess, nil)
http = mock('http')
http.should_receive(:request) do |request, entry_xml|
request['Authorization'].should match(/^AuthHMAC access_id:[a-zA-Z0-9\/+]+=*$/)
response
end
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
entry.save!(:hmac_access_id => 'access_id', :hmac_secret_key => 'secret')
end
end
it "should send a DELETE to the edit link on delete!" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPSuccess, nil)
request = mock('request')
Net::HTTP::Delete.should_receive(:new).with('/member_entry.atom', an_instance_of(Hash)).and_return(request)
http = mock('http')
http.should_receive(:request).with(request).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
entry.destroy!
end
it "should send a DELETE with basic auth to the edit link on delete!" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPSuccess, nil)
request = mock('request')
request.should_receive(:basic_auth).with('user', 'pass')
Net::HTTP::Delete.should_receive(:new).with('/member_entry.atom', an_instance_of(Hash)).and_return(request)
http = mock('http')
http.should_receive(:request).with(request).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
entry.destroy!(:user => 'user', :pass => 'pass')
end
if Atom::Configuration.auth_hmac_enabled?
it "should send a DELETE with hmac auth to the edit link on delete!" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPSuccess, nil)
http = mock('http')
http.should_receive(:request) do |request|
request['Authorization'].should match(/^AuthHMAC access_id:[a-zA-Z0-9\/+]+=*$/)
response
end
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
entry.destroy!(:hmac_access_id => 'access_id', :hmac_secret_key => 'secret')
end
end
it "should raise exception on save! without an edit link" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
lambda { entry.save! }.should raise_error(Atom::Pub::NotSupported)
end
it "should raise exception on save failure" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPClientError, nil)
request = mock('request')
Net::HTTP::Put.should_receive(:new).with('/member_entry.atom', @request_headers).and_return(request)
http = mock('http')
http.should_receive(:request).with(request, entry.to_xml.to_s).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
lambda { entry.save! }.should raise_error(Atom::Pub::ProtocolError)
end
it "should raise exception on destroy! without an edit link" do
entry = Atom::Entry.load_entry(File.open('spec/fixtures/entry.atom'))
lambda { entry.destroy! }.should raise_error(Atom::Pub::NotSupported)
end
it "should raise exception on destroy failure" do
entry = Atom::Entry.load_entry(File.open('spec/app/member_entry.atom'))
response = mock_response(Net::HTTPClientError, nil)
request = mock('request')
Net::HTTP::Delete.should_receive(:new).with('/member_entry.atom', an_instance_of(Hash)).and_return(request)
http = mock('http')
http.should_receive(:request).with(request).and_return(response)
Net::HTTP.should_receive(:start).with('example.org', 80).and_yield(http)
lambda { entry.destroy! }.should raise_error(Atom::Pub::ProtocolError)
end
end
end
|
usmschuck/canvas
|
vendor/bundle/ruby/1.9.1/gems/ratom-instructure-0.6.9/spec/atom/pub_spec.rb
|
Ruby
|
agpl-3.0
| 19,553
|
The following is all the data collected.
You can view the server code [here](https://github.com/joonatoona/OpenMineMods_Analytics), and the code that sends data to the server [here](https://github.com/joonatoona/OpenMineMods/blob/master/Utils/Analytics.py)
```
TIMESTAMP: 1505221402316
VERSION: '1.0.1'
COUNTRY: 'FI'
LAST OCTLET OF IP: 87
UUID: '6e300ac8-e0f6-4848-9668-bebfac0dfbc4'
MULTIMC FOLDER: '/home/{USER}/.local/share/multimc'
OPENMINEMODS FOLDER: '/home/{USER}/src/OpenMineMods'
SYSTEM: 'Linux 4.10.0-33-generic (x86_64)'
```
|
OpenMineMods/OpenMineMods
|
ExampleAnalytics.md
|
Markdown
|
agpl-3.0
| 536
|
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
//go:build !windows
// +build !windows
package spool_test
import (
"io"
"net"
"github.com/juju/errors"
)
func dial(socketPath string) (io.ReadCloser, error) {
conn, err := net.Dial("unix", socketPath)
if err != nil {
return nil, errors.Trace(err)
}
return conn, nil
}
|
jameinel/juju
|
worker/metrics/spool/listener_unix_test.go
|
GO
|
agpl-3.0
| 375
|
<?php
namespace MapasCulturais;
use \MapasCulturais\App;
/**
* The base class for all controllers.
*
* To create a controller you must extends this class and register the new controller class as a controller in the application
* with the method \MapasCulturais\App::registerController(). Inside this class you can create actions.
*
* The controllers actions are methods with name starting with the request type (GET_, POST_, PUT_ or DELETE_) or the word ALL_
* followed by action name. So if you want an action that responds to all requests methods you use the word ALL, otherwise you put
* the request type in the begin of the method name.
*
* Inside the action method you can access the data passed to action through
* $this->data, $this->urlData, $this->requestData, $this->getData, $this->postData, $this->putData and $this->deleteData
*
* If you want that only logged in users can access an action, call the method $this->requireAuthentication(); at the first line of the action.
* This method redirects the user, if he is not logged in, to the login page and redirects back to the action after the user successful log in
*
* To render a json call $this->json($data_to_encode_to_json).
*
* To render a template with the layout call $this->render('template-name', $array_of_data_to_pass_to_template).
*
* To render a template without the layout call $this->partial('template-name', $array_of_data_to_pass_to_template).
*
* The template files for this controller is located in the folder themes/active/views/{$controller_id}/
*
*
* @property-read string $action
*
* @property-read array $data URL + GET + POST + PUT + DELETE data
* @property-read array $urlData URL data
* @property-read array $requestData GET + POST + PUT + DELETE data
* @property-read array $getData GET data
* @property-read array $postData POST data
* @property-read array $putData PUT data
* @property-read array $deleteData DELETE data
*
*
* @see \MapasCulturais\App::registerController()
*
* @hook **{$method}({$controller_id}.{$action_name})** *($arguments)* - executed if the methods {$method}_{$action_name} and ALL_{$action_name} not exists.
* @hook **ALL({$controller_id}.{$action_name})** *($arguments)* - executed if the methods {$method}_{$action_name} and ALL_{$action_name} and the previous hook not exists.
*
* @hook **{$method}:before** *($arguments)* - executed before the execution of all actions of all controllers.
* @hook **{$method}({$controller_id}):before** *($arguments)* - executed before the execution of all actions of the controller.
* @hook **{$method}({$controller_id}.{$action_name}):before** *($arguments)* - executed before the execution of the action.
* @hook **ALL:before** *($arguments)* - executed before the execution of all actions of all controllers.
* @hook **ALL({$controller_id}):before** *($arguments)* - executed before the execution ofall actions of the controller.
* @hook **ALL({$controller_id}.{$action_name}):before** *($arguments)* - executed before the execution of the action.
*
* @hook **{$method}:after** *($arguments)* - executed after the execution of all actions of all controllers
* @hook **{$method}({$controller_id}):after** *($arguments)* - executed after the execution of all actions of the controller.
* @hook **{$method}({$controller_id}.{$action_name}):after** *($arguments)* - executed after the execution of the action.
* @hook **ALL:after** *($arguments)* - executed after the execution of all actions of all controllers.
* @hook **ALL({$controller_id}):after** *($arguments)* - executed after the execution of all actions of the controller.
* @hook **ALL({$controller_id}.{$action_name}):after** *($arguments)* - executed after the execution of the action.
*/
abstract class Controller{
use Traits\MagicGetter,
Traits\MagicSetter,
Traits\MagicCallers;
/**
* URL based vars passed in URL after the action name (not by GET).
*
* @example for de url **http://mapasculturais/controller/action/id:11/name:Fulanano** this property will be ['id' => 11, 'name' => 'Fulano']
*
* @var array The URL data
*/
protected $_urlData = [];
/**
* Array with the request data.
*
* This array is the merge of the URL based vars with $_REQUEST
*
* @example for the URL .../actionname/id:1/a-data/name:Fulano?age=33 the resultant array will be [id=>1, 0=>a-data, name=>Fulano, age=>33]
* @var array
*/
protected $data = [];
protected $action = null;
protected $method = null;
/**
* Array of instances of this class and all subclasses.
* @var array
*/
protected static $_singletonInstances = [];
/**
*
* @var string controller id
*/
protected $_id = null;
/**
* Returns the singleton instance. This method creates the instance when called for the first time.
* @return self
*/
static public function i(string $controller_id): Controller {
$class = get_called_class();
$id = "{$class}:{$controller_id}";
if (!key_exists($id, self::$_singletonInstances)) {
self::$_singletonInstances[$id] = new $class;
self::$_singletonInstances[$id]->_id = $controller_id;
}
return self::$_singletonInstances[$id];
}
/**
* This class use Singleton
* @return true
*/
public static function usesSingleton(){
return true;
}
// =================== GETTERS ================== //
/**
* Returns the controller id.
*
* @see \MapasCulturais\App::getControllerId()
*
* @return string The controller id.
*/
public function getId(){
return $this->_id;
}
/**
* Returns the URL based vars passed in URL after the action name (not by GET).
*
* @return array URL data
*/
public function getUrlData(){
return $this->_urlData;
}
/**
* Returns the GET + POST + PUT + DELETE data
*
* @return array GET + POST + PUT + DELETE data
*/
public function getRequestData(){
return App::i()->request()->params();
}
/**
* Returns the GET data
*
* @return array GET data
*/
public function getGetData(){
return App::i()->request()->get();
}
/**
* Returns the POST data
*
* @return array POST data
*/
public function getPostData(){
return App::i()->request()->post();
}
/**
* Returns the PUT data
*
* @return array PUT data
*/
public function getPutData(){
return App::i()->request()->put();
}
/**
* Returns the DELETE data
*
* @return array DELETE data
*/
public function getDeleteData(){
return App::i()->request()->delete();
}
// =================== SETTERS ===================== //
/**
* Set the layout to use to render the template.
*
* This method sets the layout in the view object.
*
* @see \MapasCulturais\View::setLayout()
*
* @param string $layout
*/
public function setLayout($layout){
App::i()->view()->layout = $layout;
}
/**
* Defines the request data to be used in actions.
*
* @param array $args
*/
public function setRequestData(array $args){
$this->_urlData = $args;
$this->data = $args + App::i()->request()->params();
}
/**
* Call an action of this controller.
*
* The action is a method named {$method}_actionName (ex: GET_list) or a hook like GET(controllerId.actionName).
*
* This method first try to call a method starting with the request type (like GET_), then try to call a method starting with the word ALL_, then try to call the hooks.
* If none of these methods exists, the request is passed by calling the App::i()->pass().
*
* For the API actions the name of the action method must starts with API_ (ex: API_actionName)
*
* @param string $method (GET, PUT, POST, DELETE or ALL)
* @param string $action_name the action name
* @param array $arguments arguments to pass to action
*
* @example For a POST request to the ..../controller_id/actionName, first try Controller::POST_actionName, then Controller::ALL_actionName,
* then the hook with name POST(controller_id.actionName), then the hook ALL(controller_id.actionName)
*
* @hook **{$method}({$controller_id}.{$action_name})** *($arguments)* - executed if the methods {$method}_{$action_name} and ALL_{$action_name} not exists.
* @hook **ALL({$controller_id}.{$action_name})** *($arguments)* - executed if the methods {$method}_{$action_name} and ALL_{$action_name} and the previous hook not exists.
*
* @hook **{$method}:before** *($arguments)* - executed before the execution of all actions of all controllers.
* @hook **{$method}({$controller_id}):before** *($arguments)* - executed before the execution of all actions of the controller.
* @hook **{$method}({$controller_id}.{$action_name}):before** *($arguments)* - executed before the execution of the action.
* @hook **ALL:before** *($arguments)* - executed before the execution of all actions of all controllers.
* @hook **ALL({$controller_id}):before** *($arguments)* - executed before the execution ofall actions of the controller.
* @hook **ALL({$controller_id}.{$action_name}):before** *($arguments)* - executed before the execution of the action.
*
* @hook **{$method}:after** *($arguments)* - executed after the execution of all actions of all controllers
* @hook **{$method}({$controller_id}):after** *($arguments)* - executed after the execution of all actions of the controller.
* @hook **{$method}({$controller_id}.{$action_name}):after** *($arguments)* - executed after the execution of the action.
* @hook **ALL:after** *($arguments)* - executed after the execution of all actions of all controllers.
* @hook **ALL({$controller_id}):after** *($arguments)* - executed after the execution of all actions of the controller.
* @hook **ALL({$controller_id}.{$action_name}):after** *($arguments)* - executed after the execution of the action.
*
*/
public function callAction($method, $action_name, $arguments) {
$app = App::i();
if(@$app->config['app.log.requestData'] && $app->config['slim.log.level'] === \Slim\Log::DEBUG){
$app->log->debug('===== POST DATA >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
$app->log->debug(print_r($this->postData,true));
$app->log->debug('===== GET DATA >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
$app->log->debug(print_r($this->getData,true));
$app->log->debug('===== URL DATA >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
$app->log->debug(print_r($this->urlData,true));
}
$this->action = $action_name;
$method = strtoupper($method);
$this->method = $method;
foreach($app->config['ini.set'] as $pattern => $configs) {
$pattern = str_replace('*', '.*', $pattern);
if(preg_match("#{$pattern}#i", "{$this->method} {$this->id}/{$this->action}")) {
foreach($configs as $varname => $newvalue) {
ini_set($varname, $newvalue);
}
}
}
// hook like GET(user.teste)
$hook = $method . "({$this->id}.{$action_name})";
// hook like ALL(user.teste)
$ALL_hook = $method !== 'API' ? "ALL({$this->id}.{$action_name})" : null;
$call_method = null;
$call_hook = null;
// first try to call an action defined inside the controller
if(method_exists($this, $method . '_' . $action_name)){
$call_method = [$this, $method . '_' . $action_name];
}elseif($method !== 'API' && method_exists($this, 'ALL_' . $action_name)){
$call_method = [$this, 'ALL_' . $action_name];
// then try to call an action defined outside the controller
}elseif($app->getHooks($hook)){
$call_hook = $hook;
}elseif($method !== 'API' && $app->getHooks($ALL_hook)){
$call_hook = $ALL_hook;
}
if($call_method || $call_hook){
$app->applyHookBoundTo($this, $hook . ':before', $arguments);
if($call_method)
$call_method();
else
$app->applyHookBoundTo($this, $call_hook, $arguments);
$app->applyHookBoundTo($this, $hook . ':after', $arguments);
// else pass to 404?
}else{
$app->pass();
}
}
/**
* Render a template in the folder with the name of the controller id
*
* @param string $template the template name
* @param type $data array with data to pass to the template
*/
public function render($template, $data = []){
$app = App::i();
$app->applyHookBoundTo($this, 'controller(' . $this->id . ').render(' . $template . ')', ['template' => &$template, 'data' => &$data]);
$template = $this->id . '/' . $template;
$app->render($template, $data);
}
/**
* Render a template without the layout, in the folder with the name of the controller id
*
* @param string $template the template name
* @param type $data array with data to pass to the template
*/
public function partial($template, $data = []){
$app = App::i();
$app->applyHookBoundTo($this, 'controller(' . $this->id . ').partial(' . $template . ')', ['template' => &$template, 'data' => &$data]);
$template = $this->id . '/' . $template;
$app->view->partial = true;
$app->render($template, $data);
}
/**
* Sets the response content type to application/json and prints the $data encoded to json.
*
* @param mixed $data
*/
public function json($data, $status = 200){
$app = App::i();
$app->contentType('application/json');
$app->halt($status, json_encode($data));
}
/**
* Sets the response content type to application/json and prints a json of ['error' => true, 'data' => $data]
*
* @param mixed $data
*
* @TODO Alterar o status padrão para 400. será necessário alterar os js para esperar este retorno.
*/
public function errorJson($data, $status = 200){
$app = App::i();
$app->contentType('application/json');
$app->halt($status, json_encode(['error' => true, 'data' => $data]));
}
/**
* Creates a URL to the given action name and data
* @param string $actionName
* @param array $data
* @return string the generated URL
*/
public function createUrl($actionName, array $data = []){
return App::i()->routesManager->createUrl($this->id, $actionName, $data);
}
/**
* This method redirects the request to authentication page if the user is not logged in.
*
* Call this method at the beginning of actions that require authentication.
*/
public function requireAuthentication(){
$app = App::i();
if($app->user->is('guest')){
$app->applyHookBoundTo($this, "controller({$this->id}).requireAuthentication");
$app->auth->requireAuthentication();
}
}
}
|
secultce/mapasculturais
|
src/protected/application/lib/MapasCulturais/Controller.php
|
PHP
|
agpl-3.0
| 15,596
|
import copy
from django.db.models.fields.related import ForeignKey, OneToOneField
from rest_framework import mixins
from rest_framework.generics import (
GenericAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView,
RetrieveUpdateDestroyAPIView
)
from api.generics.serializers import (
DynamicFieldsModelSerializer, DynamicFieldsSerializer
)
class DynamicView(GenericAPIView):
# foreign / one-to-one fields that can be used with select_related()
select_related_fields = []
serializer_fields = []
field_source_mapping = {}
fields = ()
selectable_fields = ()
def __init__(self, *args, **kwargs):
"""
Extract prefetches and default fields from Meta
"""
# TODO: move this to a meta class, to evaluate once when defining the
# class
# TODO: This is not efficient - 2016-01-20
serializer_class = self.get_serializer_class()
serializer = serializer_class() # need an instance to extract fields
model = serializer_class.Meta.model
assert issubclass(
serializer_class, DynamicFieldsModelSerializer
) or issubclass(serializer_class, DynamicFieldsSerializer), (
"serializer class must be an instance of \
DynamicFieldsModelSerializer " "instead got %s"
) % (serializer_class.__name__,)
self.serializer_fields = serializer.fields.keys()
self.select_related_fields = [
field.name for field in model._meta.fields
if isinstance(field, (ForeignKey, OneToOneField))
]
self.field_source_mapping = {
field.field_name: field.source
for field in serializer.fields.values()
if isinstance(
field, (ForeignKey, OneToOneField)
)
}
def _get_query_fields(self):
if not self.request:
return ()
request_fields = self.request.query_params.get('fields')
# if requested query fields is set to `all` we will return all
# serializer fields defined in serializer class. Here we assign
# `self.fields = ()` so that it will be assigned all serializer
# fields in `filter_queryset` method.
if request_fields and request_fields == 'all':
self.fields = ()
self.selectable_fields = (self.selectable_fields + tuple(
self.serializer_fields))
elif request_fields:
for request_field in request_fields.split(','):
if request_field not in list(self.fields):
# put selectable fields together with required fields
# defined in the class
self.fields = self.fields + (request_field,)
# just in case if you want to know which of fields
# we get as selectable field
self.selectable_fields = self.selectable_fields+(request_field,) # NOQA: E501
# Some bugs if request fields has 'aggregations'
# So we need to remove it from request fields.
# And assign a tuple fields without aggregations
fields = list(self.fields)
try:
fields.remove('aggregations')
except ValueError:
pass
# Assign it again
self.fields = tuple(fields)
return getattr(self, 'fields', ())
def filter_queryset(self, queryset, *args, **kwargs):
"""
Prefetches based on 'fields' GET arg
"""
filter_fields = copy.deepcopy(self.request.query_params)
if 'fields' in filter_fields:
filter_fields.pop('fields')
if 'format' in filter_fields:
filter_fields.pop('format')
if 'page' in filter_fields:
filter_fields.pop('page')
if 'page_size' in filter_fields:
filter_fields.pop('page_size')
if 'ordering' in filter_fields:
filter_fields.pop('ordering')
if 'q'in filter_fields:
filter_fields.pop('q')
if 'q_fields' in filter_fields:
filter_fields.pop('q_fields')
for filter_field in filter_fields:
found = False
try:
declared_filters = self.filter_class.declared_filters
for key in declared_filters:
if filter_field == key:
found = True
if found is False:
# make error in the code to fail
# if input wrong filter name.
setattr(self, 'filter_class', 'No Filter Class')
break
except AttributeError:
pass
fields = self._get_query_fields(*args, **kwargs)
if not fields:
fields = self.serializer_fields
select_related_fields = list(set(
self.select_related_fields
) & set(fields))
if select_related_fields:
queryset = queryset.select_related(*select_related_fields)
for field in fields:
# TODO: Hook this up in the view - 2016-01-15
if hasattr(queryset, 'prefetch_%s' % field):
queryset = getattr(queryset, 'prefetch_%s' % field)()
queryset = super(DynamicView, self).filter_queryset(
queryset, *args, **kwargs
)
return queryset
def get_serializer(self, *args, **kwargs):
"""
Apply 'fields' to dynamic fields serializer
"""
fields = self._get_query_fields()
kwargs['context'] = self.get_serializer_context()
return super(DynamicView, self).get_serializer(
fields=fields, *args, **kwargs
)
class DynamicListView(DynamicView, ListAPIView):
"""
List view with dynamic properties
"""
class DynamicDetailView(DynamicView, RetrieveAPIView):
"""
List view with dynamic properties
"""
class DynamicListCRUDView(DynamicView, ListCreateAPIView):
"""
List view with dynamic properties
"""
class DynamicDetailCRUDView(DynamicView, RetrieveUpdateDestroyAPIView):
"""
List view with dynamic properties
"""
class SaveAllSerializer(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
openaid-IATI/OIPA
|
OIPA/api/generics/views.py
|
Python
|
agpl-3.0
| 6,974
|
// ----------------------------------------------------------------------------------
// 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 Expenses.Web.Repository
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Web.Security;
using Expenses.Web.Models;
public class ReportsContextInitializer : CreateDatabaseIfNotExists<ReportsContext>
{
public const byte DraftStatus = 1;
public const byte PendingStatus = 2;
public const byte ApprovedStatus = 3;
public const byte RejectedStatus = 4;
private static Random random = new Random();
protected override void Seed(ReportsContext context)
{
base.Seed(context);
this.CreateDatabaseConstraints();
this.AddUsers();
this.AddProfiles();
this.AddReportStatuses();
this.AddExpenseReports();
}
private void AddUsers()
{
Roles.CreateRole("manager");
Roles.CreateRole("user");
Membership.CreateUser("manager", "Passw0rd!");
Roles.AddUsersToRole(new[] { "manager" }, "manager");
Membership.CreateUser("manager2", "Passw0rd!");
Roles.AddUsersToRole(new[] { "manager2" }, "manager");
Membership.CreateUser("manager3", "Passw0rd!");
Roles.AddUsersToRole(new[] { "manager3" }, "manager");
Membership.CreateUser("user", "Passw0rd!");
Roles.AddUsersToRole(new[] { "user" }, "user");
Membership.CreateUser("user2", "Passw0rd!");
Roles.AddUsersToRole(new[] { "user2" }, "user");
}
private void CreateDatabaseConstraints()
{
using (var ctx = new ReportsContext())
{
ctx.Database.ExecuteSqlCommand("ALTER TABLE UserProfile ADD CONSTRAINT uc_UserName UNIQUE(UserName)");
}
}
private void AddProfiles()
{
using (var ctx = new ReportsContext())
{
var manager1 = new UserProfile() { UserId = new Guid("99038106-F2AC-41B0-9C5F-CE9D1233E0A4"), UserName = "manager", FirstName = "Sample", LastName = "Manager One", IsAdmin = true };
ctx.UserProfiles.Add(manager1);
var manager2 = new UserProfile() { UserId = new Guid("4D64501B-A08A-4EE1-88A9-914DB8BDFC25"), UserName = "manager2", FirstName = "Sample", LastName = "Manager Two", IsAdmin = true };
ctx.UserProfiles.Add(manager2);
var manager3 = new UserProfile() { UserId = new Guid("33436645-A051-402C-814F-4618F91E75E2"), UserName = "manager3", FirstName = "Sample", LastName = "Manager Three", IsAdmin = true };
ctx.UserProfiles.Add(manager3);
ctx.UserProfiles.Add(new UserProfile() { UserId = new Guid("BF8F48E1-714A-4501-8D96-C3C677156BF7"), UserName = "user", FirstName = "Sample", LastName = "User One", Manager = manager1, IsAdmin = false });
ctx.UserProfiles.Add(new UserProfile() { UserId = new Guid("7B211E9F-BE02-4A00-A41D-83761C24F66E"), UserName = "user2", FirstName = "Sample", LastName = "User Two", Manager = manager2, IsAdmin = false });
ctx.SaveChanges();
}
}
private void AddReportStatuses()
{
using (var ctx = new ReportsContext())
{
ctx.ExpenseReportStatuses.Add(new ExpenseReportStatus() { Name = "Draft", Description = "Draft report pending to be submitted" });
ctx.ExpenseReportStatuses.Add(new ExpenseReportStatus() { Name = "Pending", Description = "Submitted report pending to be approved/rejected" });
ctx.ExpenseReportStatuses.Add(new ExpenseReportStatus() { Name = "Approved", Description = "Report approved by a manager" });
ctx.ExpenseReportStatuses.Add(new ExpenseReportStatus() { Name = "Rejected", Description = "Report rejected by a manager" });
ctx.SaveChanges();
}
}
private void AddExpenseReports()
{
var repository = new ExpenseReportsRepository();
repository.Save(this.CreateNewExpenseReport("Trip to Denver", PendingStatus, new Guid("BF8F48E1-714A-4501-8D96-C3C677156BF7"), 3));
repository.Save(this.CreateNewExpenseReport("Dinner with Customers", PendingStatus, new Guid("7B211E9F-BE02-4A00-A41D-83761C24F66E"), 2));
repository.Save(this.CreateNewExpenseReport("Trip to Colorado", DraftStatus, new Guid("7B211E9F-BE02-4A00-A41D-83761C24F66E"), 4));
repository.Save(this.CreateNewExpenseReport("Trip to Arizona", ApprovedStatus, new Guid("7B211E9F-BE02-4A00-A41D-83761C24F66E"), 3));
repository.Save(this.CreateNewExpenseReport("Lunch at TreyResearch", RejectedStatus, new Guid("BF8F48E1-714A-4501-8D96-C3C677156BF7"), 2));
}
private ExpenseReport CreateNewExpenseReport(string title, byte status, Guid userId, int expensesCount)
{
var details = new List<ExpenseReportDetail>();
for (int i = 0; i < expensesCount; i++)
{
var amount = (random.NextDouble() + 0.2) * (random.Next(1000) + 1);
details.Add(new ExpenseReportDetail()
{
Description = "Sample Expense " + i,
TransactionAmount = (decimal)Math.Ceiling(amount),
BilledAmount = (decimal)amount,
AccountNumber = (random.Next(100000000) + 1000000000).ToString(),
Date = DateTime.Now.Subtract(new TimeSpan((long)(random.Next(100) * 100000)))
});
}
var report = new ExpenseReport() { Name = title, Purpose = "This should be the purpose of " + title, Created = DateTime.Now, StatusId = status, UserId = userId, Details = details };
if (status != 1)
{
report.Submitted = DateTime.Now;
}
return report;
}
}
}
|
Evilazaro/MCSDAzureTraining
|
Design and Implement Cloud Services/Demos/WATK/ContosoExpenseReporting/Source/Code/End/Expenses.Web/Repository/ReportsContextInitializer.cs
|
C#
|
agpl-3.0
| 6,896
|
/*
* Copyright (C) 2017 ScyllaDB
*
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/util/gcc6-concepts.hh>
#include <seastar/core/apply.hh>
#include "cql3/statements/modification_statement.hh"
#include "cql3/statements/prepared_statement.hh"
#include "cql3/query_processor.hh"
#include "service/migration_manager.hh"
#include "database.hh"
/**
* \class table_helper
* \brief A helper class that unites the operations on a single table under the same roof.
*/
class table_helper {
private:
const sstring _keyspace; /** a keyspace name */
const sstring _name; /** a table name */
const sstring _create_cql; /** a CQL CREATE TABLE statement for the table */
const sstring _insert_cql; /** a CQL INSERT statement */
cql3::statements::prepared_statement::checked_weak_ptr _prepared_stmt; /** a raw prepared statement object (containing the INSERT statement) */
shared_ptr<cql3::statements::modification_statement> _insert_stmt; /** INSERT prepared statement */
public:
table_helper(sstring keyspace, sstring name, sstring create_cql, sstring insert_cql)
: _keyspace(std::move(keyspace))
, _name(std::move(name))
, _create_cql(std::move(create_cql))
, _insert_cql(std::move(insert_cql)) {}
/**
* Tries to create a table using create_cql command.
*
* @return A future that resolves when the operation is complete. Any
* possible errors are ignored.
*/
future<> setup_table() const;
/**
* @return a future that resolves when the given t_helper is ready to be used for
* data insertion.
*/
future<> cache_table_info(service::query_state&);
/**
* @return The table name
*/
const sstring& name() const {
return _name;
}
/**
* @return A pointer to the INSERT prepared statement
*/
shared_ptr<cql3::statements::modification_statement> insert_stmt() const {
return _insert_stmt;
}
/**
* Execute a single insertion into the table.
*
* @tparam OptMaker cql_options maker functor type
* @tparam Args OptMaker arguments' types
* @param opt_maker cql_options maker functor
* @param opt_maker_args opt_maker arguments
*/
template <typename OptMaker, typename... Args>
GCC6_CONCEPT( requires seastar::CanApply<OptMaker, Args...> )
future<> insert(service::query_state& qs, OptMaker opt_maker, Args&&... opt_maker_args) {
return cache_table_info(qs).then([this, &qs, opt_maker = std::move(opt_maker), args = std::forward_as_tuple(std::forward<Args>(opt_maker_args)...)] () mutable {
return do_with(apply(opt_maker, std::move(args)), [this, &qs] (auto& opts) {
return _insert_stmt->execute(service::get_storage_proxy().local(), qs, opts);
});
}).discard_result();
}
template <typename... Args>
static inline future<> setup_keyspace(const sstring& keyspace_name, sstring replication_factor, service::query_state& qs, const Args&... args) {
if (engine().cpu_id() == 0) {
size_t n = sizeof...(args);
const table_helper* tables[sizeof...(args)] = {&args...};
for (size_t i = 0; i < n; ++i) {
if (tables[i]->_keyspace != keyspace_name) {
throw std::invalid_argument("setup_keyspace called with table_helper for different keyspace");
}
}
return seastar::async([&keyspace_name, replication_factor, &qs, &args...] {
auto& db = cql3::get_local_query_processor().db().local();
// Create a keyspace
if (!db.has_keyspace(keyspace_name)) {
std::map<sstring, sstring> opts;
opts["replication_factor"] = replication_factor;
auto ksm = keyspace_metadata::new_keyspace(keyspace_name, "org.apache.cassandra.locator.SimpleStrategy", std::move(opts), true);
// We use min_timestamp so that default keyspace metadata will loose with any manual adjustments. See issue #2129.
service::get_local_migration_manager().announce_new_keyspace(ksm, api::min_timestamp, false).get();
}
qs.get_client_state().set_keyspace(cql3::get_local_query_processor().db(), keyspace_name);
// Create tables
size_t n = sizeof...(args);
const table_helper* tables[sizeof...(args)] = {&args...};
for (size_t i = 0; i < n; ++i) {
tables[i]->setup_table().get();
}
});
} else {
return make_ready_future<>();
}
}
/**
* Makes a monotonically increasing value in 100ns ("nanos") based on the given time
* stamp and the "nanos" value of the previous event.
*
* If the amount of 100s of ns evaluated from the @param tp is equal to the
* given @param last_event_nanos increment @param last_event_nanos by one
* and return a time point based its new value.
*
* @param last_event_nanos a reference to the last nanos to align the given time point to.
* @param tp the amount of time passed since the Epoch that will be used for the calculation.
*
* @return the monotonically increasing vlaue in 100s of ns based on the
* given time stamp and on the "nanos" value of the previous event.
*/
static std::chrono::system_clock::time_point make_monotonic_UUID_tp(int64_t& last_event_nanos, std::chrono::system_clock::time_point tp) {
using namespace std::chrono;
auto tp_nanos = duration_cast<nanoseconds>(tp.time_since_epoch()).count() / 100;
if (tp_nanos > last_event_nanos) {
last_event_nanos = tp_nanos;
return tp;
} else {
return std::chrono::system_clock::time_point(nanoseconds((++last_event_nanos) * 100));
}
}
};
struct bad_column_family : public std::exception {
private:
sstring _keyspace;
sstring _cf;
sstring _what;
public:
bad_column_family(const sstring& keyspace, const sstring& cf)
: _keyspace(keyspace)
, _cf(cf)
, _what(sprint("%s.%s doesn't meet expected schema.", _keyspace, _cf))
{ }
bad_column_family(const sstring& keyspace, const sstring& cf, const std::exception& e)
: _keyspace(keyspace)
, _cf(cf)
, _what(sprint("%s.%s doesn't meet expected schema: %s", _keyspace, _cf, e.what()))
{ }
const char* what() const noexcept override {
return _what.c_str();
}
};
|
fastio/pedis
|
table_helper.hh
|
C++
|
agpl-3.0
| 7,277
|
/*
* Copyright 2011 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of JogAmp Community.
*/
package com.jogamp.opengl.fixedfunc;
public class GLPointerFuncUtil {
public static final String mgl_Vertex = "mgl_Vertex";
public static final String mgl_Normal = "mgl_Normal";
public static final String mgl_Color = "mgl_Color";
public static final String mgl_MultiTexCoord = "mgl_MultiTexCoord" ;
public static final String mgl_InterleaveArray = "mgl_InterleaveArray" ; // magic name for interleaved arrays w/ sub-arrays
/**
* @param glArrayIndex the fixed function array index
* @return default fixed function array name
*/
public static String getPredefinedArrayIndexName(final int glArrayIndex) {
return getPredefinedArrayIndexName(glArrayIndex, -1);
}
/**
* @param glArrayIndex the fixed function array index
* @param multiTexCoordIndex index for multiTexCoordIndex
* @return default fixed function array name
*/
public static String getPredefinedArrayIndexName(final int glArrayIndex, final int multiTexCoordIndex) {
switch(glArrayIndex) {
case GLPointerFunc.GL_VERTEX_ARRAY:
return mgl_Vertex;
case GLPointerFunc.GL_NORMAL_ARRAY:
return mgl_Normal;
case GLPointerFunc.GL_COLOR_ARRAY:
return mgl_Color;
case GLPointerFunc.GL_TEXTURE_COORD_ARRAY:
if(0<=multiTexCoordIndex) {
return mgl_MultiTexCoord+multiTexCoordIndex;
} else {
return mgl_MultiTexCoord+multiTexCoordIndex;
}
}
return null;
}
}
|
gama-platform/gama.cloud
|
ummisco.gama.opengl_web/src/com/jogamp/opengl/fixedfunc/GLPointerFuncUtil.java
|
Java
|
agpl-3.0
| 3,179
|
//#############################################################################
//# #
//# 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.admin.forms.applicationroles;
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 lyrRightsLayer extends Layer
{
private static final long serialVersionUID = 1L;
public static class tabRightsGrantedContainer extends LayerBridge
{
private static final long serialVersionUID = 1L;
public static class cmbRightsComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.admin.vo.AppRightVo value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.admin.vo.AppRightVo value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.admin.vo.AppRightVo value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.admin.vo.AppRightVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.admin.vo.AppRightVo value)
{
return super.control.removeRow(value);
}
public ims.admin.vo.AppRightVo getValue()
{
return (ims.admin.vo.AppRightVo)super.control.getValue();
}
public void setValue(ims.admin.vo.AppRightVo value)
{
super.control.setValue(value);
}
}
public static class grdRightsRow extends GridRowBridge
{
private static final long serialVersionUID = 1L;
protected grdRightsRow(GridRow row)
{
super(row);
}
public void showOpened(int column)
{
super.row.showOpened(column);
}
public void setAppRightReadOnly(boolean value)
{
super.row.setReadOnly(0, value);
}
public boolean isAppRightReadOnly()
{
return super.row.isReadOnly(0);
}
public void showAppRightOpened()
{
super.row.showOpened(0);
}
public String getAppRight()
{
return (String)super.row.get(0);
}
public void setAppRight(String value)
{
super.row.set(0, value);
}
public void setCellAppRightTooltip(String value)
{
super.row.setTooltip(0, value);
}
public ims.admin.vo.AppRightVo getValue()
{
return (ims.admin.vo.AppRightVo)super.row.getValue();
}
public void setValue(ims.admin.vo.AppRightVo value)
{
super.row.setValue(value);
}
}
public static class grdRightsRowCollection extends GridRowCollectionBridge
{
private static final long serialVersionUID = 1L;
private grdRightsRowCollection(GridRowCollection collection)
{
super(collection);
}
public grdRightsRow get(int index)
{
return new grdRightsRow(super.collection.get(index));
}
public grdRightsRow newRow()
{
return new grdRightsRow(super.collection.newRow());
}
public grdRightsRow newRow(boolean autoSelect)
{
return new grdRightsRow(super.collection.newRow(autoSelect));
}
public grdRightsRow newRowAt(int index)
{
return new grdRightsRow(super.collection.newRowAt(index));
}
public grdRightsRow newRowAt(int index, boolean autoSelect)
{
return new grdRightsRow(super.collection.newRowAt(index, autoSelect));
}
}
public static class grdRightsGrid 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);
}
public ims.admin.vo.AppRightVoCollection getValues()
{
ims.admin.vo.AppRightVoCollection listOfValues = new ims.admin.vo.AppRightVoCollection();
for(int x = 0; x < this.getRows().size(); x++)
{
listOfValues.add(this.getRows().get(x).getValue());
}
return listOfValues;
}
public ims.admin.vo.AppRightVo getValue()
{
return (ims.admin.vo.AppRightVo)super.grid.getValue();
}
public void setValue(ims.admin.vo.AppRightVo value)
{
super.grid.setValue(value);
}
public grdRightsRow getSelectedRow()
{
return super.grid.getSelectedRow() == null ? null : new grdRightsRow(super.grid.getSelectedRow());
}
public int getSelectedRowIndex()
{
return super.grid.getSelectedRowIndex();
}
public grdRightsRowCollection getRows()
{
return new grdRightsRowCollection(super.grid.getRows());
}
public grdRightsRow getRowByValue(ims.admin.vo.AppRightVo value)
{
GridRow row = super.grid.getRowByValue(value);
return row == null?null:new grdRightsRow(row);
}
public void setAppRightHeaderTooltip(String value)
{
super.grid.setColumnHeaderTooltip(0, value);
}
public String getAppRightHeaderTooltip()
{
return super.grid.getColumnHeaderTooltip(0);
}
}
public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate)
{
super.container.setTabActivatedEvent(delegate);
}
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");
// Button Controls
RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 328, 8, 48, 23, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Button.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()), new Integer(startTabIndex.intValue() + 1010), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Add", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
// ComboBox Controls
RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 312, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbRightsTemp = (ComboBox)factory.getControl(ComboBox.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()), new Integer(startTabIndex.intValue() + 1008), 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_cmbRightsTemp);
cmbRightsComboBox cmbRights = (cmbRightsComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbRightsComboBox.class, m_cmbRightsTemp);
super.addComboBox(cmbRights);
// Grid Controls
RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 8, 40, 368, 56, ims.framework.enumerations.ControlAnchoring.ALL);
Grid m_grdRightsTemp = (Grid)factory.getControl(Grid.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()), new Integer(startTabIndex.intValue() + 1012), ControlState.READONLY, ControlState.READONLY, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, Boolean.FALSE, new Integer(24), Boolean.TRUE, contextMenus.contextMenuGenericGrid, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE});
addControl(m_grdRightsTemp);
grdRightsGrid grdRights = (grdRightsGrid)GridFlyweightFactory.getInstance().createGridBridge(grdRightsGrid.class, m_grdRightsTemp);
grdRights.addStringColumn("Assigned Rights", 0, 0, -1, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL);
super.addGrid(grdRights);
}
public Button btnAdd()
{
return (Button)super.getControl(0);
}
public cmbRightsComboBox cmbRights()
{
return (cmbRightsComboBox)super.getComboBox(0);
}
public grdRightsGrid grdRights()
{
return (grdRightsGrid)super.getGrid(0);
}
}
public static class tabActionsDeniedContainer extends LayerBridge
{
private static final long serialVersionUID = 1L;
public void setTabActivatedEvent(ims.framework.delegates.TabActivated delegate)
{
super.container.setTabActivatedEvent(delegate);
}
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");
// Tree Controls
RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 368, 96, ims.framework.enumerations.ControlAnchoring.ALL);
super.addControl(factory.getControl(TreeView.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() + 1014), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, contextMenus.Admin.contextMenuRoleMenuAction, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE}));
}
public TreeView treActions()
{
return (TreeView)super.getControl(0);
}
}
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 anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 16, 456, 392, 136, ims.framework.enumerations.ControlAnchoring.ALL);
Container m_tabRightsGranted = (Container)factory.getControl(Container.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()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Rights", new Integer(startControlID.intValue() + 0), new Boolean(true), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)});
tabRightsGrantedContainer m_tabRightsGrantedContainer = (tabRightsGrantedContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabRightsGrantedContainer.class, m_tabRightsGranted, factory);
super.addContainer(m_tabRightsGranted, m_tabRightsGrantedContainer);
ims.framework.utils.SizeInfo m_tabRightsGrantedDesignSize = new ims.framework.utils.SizeInfo(392, 136);
ims.framework.utils.SizeInfo m_tabRightsGrantedRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper5.getWidth(), anchoringHelper5.getHeight());
m_tabRightsGrantedContainer.setContext(form, appForm, m_tabRightsGranted, loader, form_images_local, contextMenus, startControlID, m_tabRightsGrantedDesignSize, m_tabRightsGrantedRuntimeSize, startTabIndex, skipContextValidation);
RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 16, 456, 392, 136, ims.framework.enumerations.ControlAnchoring.ALL);
Container m_tabActionsDenied = (Container)factory.getControl(Container.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()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL,"Actions Denied", new Integer(startControlID.intValue() + 0), new Boolean(false), new Boolean(false), new Boolean(true), new Boolean(true), new Boolean(false), new Boolean(false)});
tabActionsDeniedContainer m_tabActionsDeniedContainer = (tabActionsDeniedContainer)LayerBridgeFlyweightFactory.getInstance().createLayerBridge(tabActionsDeniedContainer.class, m_tabActionsDenied, factory);
super.addContainer(m_tabActionsDenied, m_tabActionsDeniedContainer);
ims.framework.utils.SizeInfo m_tabActionsDeniedDesignSize = new ims.framework.utils.SizeInfo(392, 136);
ims.framework.utils.SizeInfo m_tabActionsDeniedRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper6.getWidth(), anchoringHelper6.getHeight());
m_tabActionsDeniedContainer.setContext(form, appForm, m_tabActionsDenied, loader, form_images_local, contextMenus, startControlID, m_tabActionsDeniedDesignSize, m_tabActionsDeniedRuntimeSize, startTabIndex, skipContextValidation);
}
public void hide()
{
tabRightsGranted().setVisible(false);
tabActionsDenied().setVisible(false);
}
public void settabRightsGrantedEnabled(boolean value)
{
tabRightsGranted().setEnabled(value);
}
public void settabActionsDeniedEnabled(boolean value)
{
tabActionsDenied().setEnabled(value);
}
public void showtabRightsGranted()
{
tabActionsDenied().setVisible(false);
tabRightsGranted().setVisible(true);
}
public void showtabActionsDenied()
{
tabRightsGranted().setVisible(false);
tabActionsDenied().setVisible(true);
}
public tabRightsGrantedContainer tabRightsGranted()
{
return (tabRightsGrantedContainer)super.layers.get(0);
}
public tabActionsDeniedContainer tabActionsDenied()
{
return (tabActionsDeniedContainer)super.layers.get(1);
}
}
public static class cmbTopButtonsComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.admin.vo.AppTopButtonConfigShortVo value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.admin.vo.AppTopButtonConfigShortVo value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.admin.vo.AppTopButtonConfigShortVo value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.admin.vo.AppTopButtonConfigShortVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.admin.vo.AppTopButtonConfigShortVo value)
{
return super.control.removeRow(value);
}
public ims.admin.vo.AppTopButtonConfigShortVo getValue()
{
return (ims.admin.vo.AppTopButtonConfigShortVo)super.control.getValue();
}
public void setValue(ims.admin.vo.AppTopButtonConfigShortVo value)
{
super.control.setValue(value);
}
}
public static class cmbNavsComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.admin.vo.AppNavShortVo value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.admin.vo.AppNavShortVo value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.admin.vo.AppNavShortVo value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.admin.vo.AppNavShortVo value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.admin.vo.AppNavShortVo value)
{
return super.control.removeRow(value);
}
public ims.admin.vo.AppNavShortVo getValue()
{
return (ims.admin.vo.AppNavShortVo)super.control.getValue();
}
public void setValue(ims.admin.vo.AppNavShortVo value)
{
super.control.setValue(value);
}
}
public static class grdRolesRow extends GridRowBridge
{
private static final long serialVersionUID = 1L;
protected grdRolesRow(GridRow row)
{
super(row);
}
public void showOpened(int column)
{
super.row.showOpened(column);
}
public void setcolRoleNameReadOnly(boolean value)
{
super.row.setReadOnly(0, value);
}
public boolean iscolRoleNameReadOnly()
{
return super.row.isReadOnly(0);
}
public void showcolRoleNameOpened()
{
super.row.showOpened(0);
}
public String getcolRoleName()
{
return (String)super.row.get(0);
}
public void setcolRoleName(String value)
{
super.row.set(0, value);
}
public void setCellcolRoleNameTooltip(String value)
{
super.row.setTooltip(0, value);
}
public ims.admin.vo.AppRoleShortVo getValue()
{
return (ims.admin.vo.AppRoleShortVo)super.row.getValue();
}
public void setValue(ims.admin.vo.AppRoleShortVo value)
{
super.row.setValue(value);
}
}
public static class grdRolesRowCollection extends GridRowCollectionBridge
{
private static final long serialVersionUID = 1L;
private grdRolesRowCollection(GridRowCollection collection)
{
super(collection);
}
public grdRolesRow get(int index)
{
return new grdRolesRow(super.collection.get(index));
}
public grdRolesRow newRow()
{
return new grdRolesRow(super.collection.newRow());
}
public grdRolesRow newRow(boolean autoSelect)
{
return new grdRolesRow(super.collection.newRow(autoSelect));
}
public grdRolesRow newRowAt(int index)
{
return new grdRolesRow(super.collection.newRowAt(index));
}
public grdRolesRow newRowAt(int index, boolean autoSelect)
{
return new grdRolesRow(super.collection.newRowAt(index, autoSelect));
}
}
public static class grdRolesGrid 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);
}
public ims.admin.vo.AppRoleShortVoCollection getValues()
{
ims.admin.vo.AppRoleShortVoCollection listOfValues = new ims.admin.vo.AppRoleShortVoCollection();
for(int x = 0; x < this.getRows().size(); x++)
{
listOfValues.add(this.getRows().get(x).getValue());
}
return listOfValues;
}
public ims.admin.vo.AppRoleShortVo getValue()
{
return (ims.admin.vo.AppRoleShortVo)super.grid.getValue();
}
public void setValue(ims.admin.vo.AppRoleShortVo value)
{
super.grid.setValue(value);
}
public grdRolesRow getSelectedRow()
{
return super.grid.getSelectedRow() == null ? null : new grdRolesRow(super.grid.getSelectedRow());
}
public int getSelectedRowIndex()
{
return super.grid.getSelectedRowIndex();
}
public grdRolesRowCollection getRows()
{
return new grdRolesRowCollection(super.grid.getRows());
}
public grdRolesRow getRowByValue(ims.admin.vo.AppRoleShortVo value)
{
GridRow row = super.grid.getRowByValue(value);
return row == null?null:new grdRolesRow(row);
}
public void setcolRoleNameHeaderTooltip(String value)
{
super.grid.setColumnHeaderTooltip(0, value);
}
public String getcolRoleNameHeaderTooltip()
{
return super.grid.getColumnHeaderTooltip(0);
}
}
private void validateContext(ims.framework.Context context)
{
if(context == null)
return;
}
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);
}
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.contextMenuGenericGrid = factory.createMenu(startControlID.intValue() + 1);
contextMenus.contextMenuGenericGridAddItem = factory.createMenuItem(startControlID.intValue() + 1, "New", true, false, new Integer(102179), true, false);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridAddItem);
contextMenus.contextMenuGenericGridUpdateItem = factory.createMenuItem(startControlID.intValue() + 2, "Edit", true, false, new Integer(102150), true, false);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridUpdateItem);
contextMenus.contextMenuGenericGridRemoveItem = factory.createMenuItem(startControlID.intValue() + 3, "Remove", true, false, new Integer(102148), true, false);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridRemoveItem);
contextMenus.contextMenuGenericGridViewItem = factory.createMenuItem(startControlID.intValue() + 4, "View", true, false, new Integer(102223), false, true);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridViewItem);
contextMenus.contextMenuGenericGridMoveUpItem = factory.createMenuItem(startControlID.intValue() + 5, "Move Up", true, false, new Integer(102197), true, true);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridMoveUpItem);
contextMenus.contextMenuGenericGridMoveDownItem = factory.createMenuItem(startControlID.intValue() + 6, "Move Down", true, false, new Integer(102198), true, false);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridMoveDownItem);
contextMenus.contextMenuGenericGridReplaceItem = factory.createMenuItem(startControlID.intValue() + 7, "Replace", true, false, new Integer(102255), true, true);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridReplaceItem);
contextMenus.contextMenuGenericGridConfirmItem = factory.createMenuItem(startControlID.intValue() + 8, "Confirm", true, false, new Integer(102209), true, false);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridConfirmItem);
contextMenus.contextMenuGenericGridEDIT_VIEW_ICP_ACTIONSItem = factory.createMenuItem(startControlID.intValue() + 9, "Edit/View ICP action(s)", true, false, new Integer(118107), true, false);
contextMenus.contextMenuGenericGrid.add(contextMenus.contextMenuGenericGridEDIT_VIEW_ICP_ACTIONSItem);
form.registerMenu(contextMenus.contextMenuGenericGrid);
contextMenus.Admin.contextMenuRoleMenuAction = factory.createMenu(startControlID.intValue() + 2);
contextMenus.Admin.contextMenuRoleMenuActionAddItem = factory.createMenuItem(startControlID.intValue() + 10, "Add", true, false, new Integer(102179), true, false);
contextMenus.Admin.contextMenuRoleMenuAction.add(contextMenus.Admin.contextMenuRoleMenuActionAddItem);
contextMenus.Admin.contextMenuRoleMenuActionRemoveItem = factory.createMenuItem(startControlID.intValue() + 11, "Remove", true, false, new Integer(102300), true, true);
contextMenus.Admin.contextMenuRoleMenuAction.add(contextMenus.Admin.contextMenuRoleMenuActionRemoveItem);
contextMenus.Admin.contextMenuRoleMenuActionRemoveAllItem = factory.createMenuItem(startControlID.intValue() + 12, "Remove All", true, false, new Integer(102148), true, false);
contextMenus.Admin.contextMenuRoleMenuAction.add(contextMenus.Admin.contextMenuRoleMenuActionRemoveAllItem);
form.registerMenu(contextMenus.Admin.contextMenuRoleMenuAction);
// Panel Controls
RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 16, 168, 392, 280, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(Panel.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()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,"Role Details", new Integer(2), ""}));
RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 16, 8, 816, 152, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(Panel.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()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,"Configured Roles", new Integer(2), ""}));
RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 424, 168, 408, 424, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMRIGHT);
super.addControl(factory.getControl(Panel.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.TOPBOTTOMRIGHT,"Navigation View", new Integer(2), ""}));
// Custom Controls
ims.framework.CustomComponent instance1 = factory.getEmptyCustomComponent();
RuntimeAnchoring anchoringHelper10 = new RuntimeAnchoring(designSize, runtimeSize, 32, 360, 371, 80, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ims.framework.FormUiLogic m_ccTaxonomyMappingsForm = loader.loadComponent(104124, appForm, startControlID * 10 + 1000, anchoringHelper10.getSize(), instance1, startTabIndex.intValue() + 7, skipContextValidation);
//ims.framework.Control m_ccTaxonomyMappingsControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1009), new Integer(32), new Integer(360), new Integer(371), new Integer(80), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT, new Integer(startTabIndex.intValue() + 7), m_ccTaxonomyMappingsForm, instance1 } );
ims.framework.Control m_ccTaxonomyMappingsControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1010), new Integer(anchoringHelper10.getX()), new Integer(anchoringHelper10.getY()), new Integer(anchoringHelper10.getWidth()), new Integer(anchoringHelper10.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT, new Integer(startTabIndex.intValue() + 7), m_ccTaxonomyMappingsForm, instance1, Boolean.FALSE } );
super.addControl(m_ccTaxonomyMappingsControl);
Menu[] menus1 = m_ccTaxonomyMappingsForm.getForm().getRegisteredMenus();
for(int x = 0; x < menus1.length; x++)
{
form.registerMenu(menus1[x]);
}
// Layer Clasess
lyrRightsLayer m_lyrRightsLayer = (lyrRightsLayer)LayerFlyweightFactory.getInstance().createLayer(lyrRightsLayer.class, this, factory);
super.addLayer(m_lyrRightsLayer);
m_lyrRightsLayer.setContext(form, appForm, control, loader, this.getImages(), contextMenus, startControlID, designSize, runtimeSize, startTabIndex, skipContextValidation);
// Label Controls
RuntimeAnchoring anchoringHelper11 = new RuntimeAnchoring(designSize, runtimeSize, 32, 344, 63, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1011), new Integer(anchoringHelper11.getX()), new Integer(anchoringHelper11.getY()), new Integer(anchoringHelper11.getWidth()), new Integer(anchoringHelper11.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Mappings:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper12 = new RuntimeAnchoring(designSize, runtimeSize, 32, 288, 77, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1012), new Integer(anchoringHelper12.getX()), new Integer(anchoringHelper12.getY()), new Integer(anchoringHelper12.getWidth()), new Integer(anchoringHelper12.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Top Buttons:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper13 = new RuntimeAnchoring(designSize, runtimeSize, 32, 256, 70, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1013), new Integer(anchoringHelper13.getX()), new Integer(anchoringHelper13.getY()), new Integer(anchoringHelper13.getWidth()), new Integer(anchoringHelper13.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Navigation:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper14 = new RuntimeAnchoring(designSize, runtimeSize, 32, 224, 73, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1014), new Integer(anchoringHelper14.getX()), new Integer(anchoringHelper14.getY()), new Integer(anchoringHelper14.getWidth()), new Integer(anchoringHelper14.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Description:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper15 = new RuntimeAnchoring(designSize, runtimeSize, 32, 320, 43, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1015), new Integer(anchoringHelper15.getX()), new Integer(anchoringHelper15.getY()), new Integer(anchoringHelper15.getWidth()), new Integer(anchoringHelper15.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Active:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper16 = new RuntimeAnchoring(designSize, runtimeSize, 32, 192, 41, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1016), new Integer(anchoringHelper16.getX()), new Integer(anchoringHelper16.getY()), new Integer(anchoringHelper16.getWidth()), new Integer(anchoringHelper16.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Name:", new Integer(1), null, new Integer(0)}));
// Button Controls
RuntimeAnchoring anchoringHelper17 = new RuntimeAnchoring(designSize, runtimeSize, 757, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1017), new Integer(anchoringHelper17.getX()), new Integer(anchoringHelper17.getY()), new Integer(anchoringHelper17.getWidth()), new Integer(anchoringHelper17.getHeight()), new Integer(startTabIndex.intValue() + 1021), 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 }));
RuntimeAnchoring anchoringHelper18 = new RuntimeAnchoring(designSize, runtimeSize, 680, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1018), new Integer(anchoringHelper18.getX()), new Integer(anchoringHelper18.getY()), new Integer(anchoringHelper18.getWidth()), new Integer(anchoringHelper18.getHeight()), new Integer(startTabIndex.intValue() + 1020), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Save", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper19 = new RuntimeAnchoring(designSize, runtimeSize, 96, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1019), new Integer(anchoringHelper19.getX()), new Integer(anchoringHelper19.getY()), new Integer(anchoringHelper19.getWidth()), new Integer(anchoringHelper19.getHeight()), new Integer(startTabIndex.intValue() + 1019), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Edit", Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper20 = new RuntimeAnchoring(designSize, runtimeSize, 16, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1020), new Integer(anchoringHelper20.getX()), new Integer(anchoringHelper20.getY()), new Integer(anchoringHelper20.getWidth()), new Integer(anchoringHelper20.getHeight()), new Integer(startTabIndex.intValue() + 1018), ControlState.ENABLED, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "New", Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
// TextBox Controls
RuntimeAnchoring anchoringHelper21 = new RuntimeAnchoring(designSize, runtimeSize, 120, 224, 272, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1021), new Integer(anchoringHelper21.getX()), new Integer(anchoringHelper21.getY()), new Integer(anchoringHelper21.getWidth()), new Integer(anchoringHelper21.getHeight()), new Integer(startTabIndex.intValue() + 3), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(255), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper22 = new RuntimeAnchoring(designSize, runtimeSize, 120, 192, 272, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1022), new Integer(anchoringHelper22.getX()), new Integer(anchoringHelper22.getY()), new Integer(anchoringHelper22.getWidth()), new Integer(anchoringHelper22.getHeight()), new Integer(startTabIndex.intValue() + 2), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.FALSE, new Integer(30), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.TRUE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
// ComboBox Controls
RuntimeAnchoring anchoringHelper23 = new RuntimeAnchoring(designSize, runtimeSize, 120, 288, 272, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbTopButtonsTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1023), new Integer(anchoringHelper23.getX()), new Integer(anchoringHelper23.getY()), new Integer(anchoringHelper23.getWidth()), new Integer(anchoringHelper23.getHeight()), new Integer(startTabIndex.intValue() + 5), 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_cmbTopButtonsTemp);
cmbTopButtonsComboBox cmbTopButtons = (cmbTopButtonsComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbTopButtonsComboBox.class, m_cmbTopButtonsTemp);
super.addComboBox(cmbTopButtons);
RuntimeAnchoring anchoringHelper24 = new RuntimeAnchoring(designSize, runtimeSize, 120, 256, 272, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbNavsTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1024), new Integer(anchoringHelper24.getX()), new Integer(anchoringHelper24.getY()), new Integer(anchoringHelper24.getWidth()), new Integer(anchoringHelper24.getHeight()), new Integer(startTabIndex.intValue() + 4), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)});
addControl(m_cmbNavsTemp);
cmbNavsComboBox cmbNavs = (cmbNavsComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbNavsComboBox.class, m_cmbNavsTemp);
super.addComboBox(cmbNavs);
// CheckBox Controls
RuntimeAnchoring anchoringHelper25 = new RuntimeAnchoring(designSize, runtimeSize, 120, 320, 24, 16, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1025), new Integer(anchoringHelper25.getX()), new Integer(anchoringHelper25.getY()), new Integer(anchoringHelper25.getWidth()), new Integer(anchoringHelper25.getHeight()), new Integer(startTabIndex.intValue() + 6), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFT ,"", Boolean.FALSE, null}));
// Grid Controls
RuntimeAnchoring anchoringHelper26 = new RuntimeAnchoring(designSize, runtimeSize, 32, 32, 784, 112, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
Grid m_grdRolesTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1026), new Integer(anchoringHelper26.getX()), new Integer(anchoringHelper26.getY()), new Integer(anchoringHelper26.getWidth()), new Integer(anchoringHelper26.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,Boolean.TRUE, Boolean.FALSE, new Integer(0), Boolean.TRUE, null, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.FALSE, Boolean.TRUE});
addControl(m_grdRolesTemp);
grdRolesGrid grdRoles = (grdRolesGrid)GridFlyweightFactory.getInstance().createGridBridge(grdRolesGrid.class, m_grdRolesTemp);
grdRoles.addStringColumn("Role Name", 0, 0, -1, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL);
super.addGrid(grdRoles);
// Tree Controls
RuntimeAnchoring anchoringHelper27 = new RuntimeAnchoring(designSize, runtimeSize, 440, 200, 376, 370, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMRIGHT);
super.addControl(factory.getControl(TreeView.class, new Object[] { control, new Integer(startControlID.intValue() + 1027), new Integer(anchoringHelper27.getX()), new Integer(anchoringHelper27.getY()), new Integer(anchoringHelper27.getWidth()), new Integer(anchoringHelper27.getHeight()), new Integer(startTabIndex.intValue() + 1017), ControlState.ENABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.TOPBOTTOMRIGHT,Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE}));
}
public Forms getForms()
{
return (Forms)super.getFormReferences();
}
public Images getImages()
{
return (Images)super.getImageReferences();
}
public ims.admin.forms.taxonomymappings.IComponent ccTaxonomyMappings()
{
return (ims.admin.forms.taxonomymappings.IComponent)((ims.framework.cn.controls.CustomComponent)super.getControl(3)).getLogic();
}
public void setccTaxonomyMappingsValueChangedEvent(ims.framework.delegates.ValueChanged delegate)
{
((CustomComponent)super.getControl(3)).setValueChangedEvent(delegate);
}
public void setccTaxonomyMappingsVisible(boolean value)
{
((ims.framework.Control)super.getControl(3)).setVisible(value);
}
public boolean isccTaxonomyMappingsVisible()
{
return ((ims.framework.Control)super.getControl(3)).isVisible();
}
public void setccTaxonomyMappingsEnabled(boolean value)
{
((ims.framework.Control)super.getControl(3)).setEnabled(value);
}
public boolean isccTaxonomyMappingsEnabled()
{
return ((ims.framework.Control)super.getControl(3)).isEnabled();
}
public lyrRightsLayer lyrRights()
{
return (lyrRightsLayer)super.getLayer(0);
}
public Button btnCancel()
{
return (Button)super.getControl(12);
}
public Button btnSave()
{
return (Button)super.getControl(13);
}
public Button btnUpdate()
{
return (Button)super.getControl(14);
}
public Button btnNew()
{
return (Button)super.getControl(15);
}
public TextBox txtRoleDesc()
{
return (TextBox)super.getControl(16);
}
public TextBox txtRoleName()
{
return (TextBox)super.getControl(17);
}
public cmbTopButtonsComboBox cmbTopButtons()
{
return (cmbTopButtonsComboBox)super.getComboBox(0);
}
public cmbNavsComboBox cmbNavs()
{
return (cmbNavsComboBox)super.getComboBox(1);
}
public CheckBox chkIsActive()
{
return (CheckBox)super.getControl(20);
}
public grdRolesGrid grdRoles()
{
return (grdRolesGrid)super.getGrid(0);
}
public TreeView treNavView()
{
return (TreeView)super.getControl(22);
}
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()
{
Admin = new AdminForms();
}
public final class AdminForms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private AdminForms()
{
TopButtonSelect = new LocalFormName(103113);
MenuActionsSelection = new LocalFormName(103182);
}
public final FormName TopButtonSelect;
public final FormName MenuActionsSelection;
}
public AdminForms Admin;
}
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()
{
Core = new CoreImages();
Admin = new AdminImages();
}
public final class CoreImages implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private CoreImages()
{
OpenFolder = new ImageHelper(102134, "Images/Core/open_folder_simple.png", new Integer(16), new Integer(16));
ClosedFolder = new ImageHelper(102135, "Images/Core/closed_folder.png", new Integer(16), new Integer(16));
Memo = new ImageHelper(102136, "Images/Core/memo.GIF", new Integer(17), new Integer(17));
Down = new ImageHelper(102108, "Images/Core/down.gif", new Integer(16), new Integer(16));
DownDisabled = new ImageHelper(102109, "Images/Core/down_disabled.gif", new Integer(16), new Integer(16));
Up = new ImageHelper(102114, "Images/Core/up.gif", new Integer(16), new Integer(16));
UpDisabled = new ImageHelper(102115, "Images/Core/up_disabled.gif", new Integer(16), new Integer(16));
CareContext = new ImageHelper(102252, "Images/Core/CareContext.gif", new Integer(16), new Integer(16));
CareSpell = new ImageHelper(102253, "Images/Core/CareSpell.gif", new Integer(16), new Integer(16));
View = new ImageHelper(102223, "Images/Core/Slide Show.gif", new Integer(16), new Integer(16));
Home = new ImageHelper(102220, "Images/Core/Home-2.gif", new Integer(16), new Integer(16));
HomeDisabled = new ImageHelper(102280, "Images/Core/Home-2_disabled.gif", new Integer(16), new Integer(16));
FindDisabled16 = new ImageHelper(102165, "Images/Core/FindDisabled16.gif", new Integer(16), new Integer(16));
FindEnabled16 = new ImageHelper(102164, "Images/Core/Find.gif", new Integer(16), new Integer(16));
ViewDisabled = new ImageHelper(102279, "Images/Core/Slide Show disabled.gif", new Integer(16), new Integer(16));
Form = new ImageHelper(102258, "Images/Core/Control_Form.gif", new Integer(16), new Integer(16));
AnswerBox_NotAvailable = new ImageHelper(102103, "Images/Core/AnswerBox_NotAvailable.gif", new Integer(10), new Integer(10));
}
public final ims.framework.utils.Image OpenFolder;
public final ims.framework.utils.Image ClosedFolder;
public final ims.framework.utils.Image Memo;
public final ims.framework.utils.Image Down;
public final ims.framework.utils.Image DownDisabled;
public final ims.framework.utils.Image Up;
public final ims.framework.utils.Image UpDisabled;
public final ims.framework.utils.Image CareContext;
public final ims.framework.utils.Image CareSpell;
public final ims.framework.utils.Image View;
public final ims.framework.utils.Image Home;
public final ims.framework.utils.Image HomeDisabled;
public final ims.framework.utils.Image FindDisabled16;
public final ims.framework.utils.Image FindEnabled16;
public final ims.framework.utils.Image ViewDisabled;
public final ims.framework.utils.Image Form;
public final ims.framework.utils.Image AnswerBox_NotAvailable;
}
public final class AdminImages implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private AdminImages()
{
Leaf = new ImageHelper(103101, "Images/Admin/Leaf.gif", new Integer(16), new Integer(16));
Task = new ImageHelper(103106, "Images/Admin/Task.gif", new Integer(24), new Integer(24));
Task_Disabled = new ImageHelper(103107, "Images/Admin/Task_Disabled.gif", new Integer(24), new Integer(24));
Page = new ImageHelper(103152, "Images/Admin/Justify-Full.gif", new Integer(16), new Integer(16));
}
public final ims.framework.utils.Image Leaf;
public final ims.framework.utils.Image Task;
public final ims.framework.utils.Image Task_Disabled;
public final ims.framework.utils.Image Page;
}
public final CoreImages Core;
public final AdminImages Admin;
}
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_RoleSelected = new ims.framework.ContextVariable("RoleSelected", prefix + "_lv_Admin.ApplicationRoles.__internal_x_context__RoleSelected_" + componentIdentifier + "");
}
public boolean getRoleSelectedIsNotNull()
{
return !cxl_RoleSelected.getValueIsNull(context);
}
public ims.admin.vo.AppRoleVo getRoleSelected()
{
return (ims.admin.vo.AppRoleVo)cxl_RoleSelected.getValue(context);
}
public void setRoleSelected(ims.admin.vo.AppRoleVo value)
{
cxl_RoleSelected.setValue(context, value);
}
private ims.framework.ContextVariable cxl_RoleSelected = null;
}
public final class ContextMenus implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
public AdminNamespace Admin = new AdminNamespace();
public final class GenericGrid implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
public static final int Add = 1;
public static final int Update = 2;
public static final int Remove = 3;
public static final int View = 4;
public static final int MoveUp = 5;
public static final int MoveDown = 6;
public static final int Replace = 7;
public static final int Confirm = 8;
public static final int EDIT_VIEW_ICP_ACTIONS = 9;
}
public void disableAllGenericGridMenuItems()
{
this.contextMenuGenericGridAddItem.setEnabled(false);
this.contextMenuGenericGridUpdateItem.setEnabled(false);
this.contextMenuGenericGridRemoveItem.setEnabled(false);
this.contextMenuGenericGridViewItem.setEnabled(false);
this.contextMenuGenericGridMoveUpItem.setEnabled(false);
this.contextMenuGenericGridMoveDownItem.setEnabled(false);
this.contextMenuGenericGridReplaceItem.setEnabled(false);
this.contextMenuGenericGridConfirmItem.setEnabled(false);
this.contextMenuGenericGridEDIT_VIEW_ICP_ACTIONSItem.setEnabled(false);
}
public void hideAllGenericGridMenuItems()
{
this.contextMenuGenericGridAddItem.setVisible(false);
this.contextMenuGenericGridUpdateItem.setVisible(false);
this.contextMenuGenericGridRemoveItem.setVisible(false);
this.contextMenuGenericGridViewItem.setVisible(false);
this.contextMenuGenericGridMoveUpItem.setVisible(false);
this.contextMenuGenericGridMoveDownItem.setVisible(false);
this.contextMenuGenericGridReplaceItem.setVisible(false);
this.contextMenuGenericGridConfirmItem.setVisible(false);
this.contextMenuGenericGridEDIT_VIEW_ICP_ACTIONSItem.setVisible(false);
}
private Menu contextMenuGenericGrid;
public MenuItem getGenericGridAddItem()
{
return this.contextMenuGenericGridAddItem;
}
private MenuItem contextMenuGenericGridAddItem;
public MenuItem getGenericGridUpdateItem()
{
return this.contextMenuGenericGridUpdateItem;
}
private MenuItem contextMenuGenericGridUpdateItem;
public MenuItem getGenericGridRemoveItem()
{
return this.contextMenuGenericGridRemoveItem;
}
private MenuItem contextMenuGenericGridRemoveItem;
public MenuItem getGenericGridViewItem()
{
return this.contextMenuGenericGridViewItem;
}
private MenuItem contextMenuGenericGridViewItem;
public MenuItem getGenericGridMoveUpItem()
{
return this.contextMenuGenericGridMoveUpItem;
}
private MenuItem contextMenuGenericGridMoveUpItem;
public MenuItem getGenericGridMoveDownItem()
{
return this.contextMenuGenericGridMoveDownItem;
}
private MenuItem contextMenuGenericGridMoveDownItem;
public MenuItem getGenericGridReplaceItem()
{
return this.contextMenuGenericGridReplaceItem;
}
private MenuItem contextMenuGenericGridReplaceItem;
public MenuItem getGenericGridConfirmItem()
{
return this.contextMenuGenericGridConfirmItem;
}
private MenuItem contextMenuGenericGridConfirmItem;
public MenuItem getGenericGridEDIT_VIEW_ICP_ACTIONSItem()
{
return this.contextMenuGenericGridEDIT_VIEW_ICP_ACTIONSItem;
}
private MenuItem contextMenuGenericGridEDIT_VIEW_ICP_ACTIONSItem;
public final class AdminNamespace implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
public final class RoleMenuAction implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
public static final int Add = 10;
public static final int Remove = 11;
public static final int RemoveAll = 12;
}
public void disableAllRoleMenuActionMenuItems()
{
this.contextMenuRoleMenuActionAddItem.setEnabled(false);
this.contextMenuRoleMenuActionRemoveItem.setEnabled(false);
this.contextMenuRoleMenuActionRemoveAllItem.setEnabled(false);
}
public void hideAllRoleMenuActionMenuItems()
{
this.contextMenuRoleMenuActionAddItem.setVisible(false);
this.contextMenuRoleMenuActionRemoveItem.setVisible(false);
this.contextMenuRoleMenuActionRemoveAllItem.setVisible(false);
}
private Menu contextMenuRoleMenuAction;
public ReadOnlyMenuItem getRoleMenuActionAddItem()
{
return this.contextMenuRoleMenuActionAddItem;
}
private MenuItem contextMenuRoleMenuActionAddItem;
public ReadOnlyMenuItem getRoleMenuActionRemoveItem()
{
return this.contextMenuRoleMenuActionRemoveItem;
}
private MenuItem contextMenuRoleMenuActionRemoveItem;
public ReadOnlyMenuItem getRoleMenuActionRemoveAllItem()
{
return this.contextMenuRoleMenuActionRemoveAllItem;
}
private MenuItem contextMenuRoleMenuActionRemoveAllItem;
}
}
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[75];
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_CareUk.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral");
fields[71] = new ims.framework.ReportField(this.context, prefix + "_lv_Admin.ApplicationRoles.__internal_x_context__RoleSelected_" + componentIdentifier, "BO-1021100000-ID", "ID_AppRole");
fields[72] = new ims.framework.ReportField(this.context, prefix + "_lv_Admin.ApplicationRoles.__internal_x_context__RoleSelected_" + componentIdentifier, "BO-1021100000-NAME", "Name");
fields[73] = new ims.framework.ReportField(this.context, prefix + "_lv_Admin.ApplicationRoles.__internal_x_context__RoleSelected_" + componentIdentifier, "BO-1021100000-ISACTIVE", "IsActive");
fields[74] = new ims.framework.ReportField(this.context, prefix + "_lv_Admin.ApplicationRoles.__internal_x_context__RoleSelected_" + componentIdentifier, "BO-1021100000-DESCRIPTION", "Description");
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;
}
|
open-health-hub/openmaxims-linux
|
openmaxims_workspace/Admin/src/ims/admin/forms/applicationroles/GenForm.java
|
Java
|
agpl-3.0
| 73,497
|
#
# Copyright (C) 2012 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas 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/>.
#
require File.expand_path(File.dirname(__FILE__) + '/../api_spec_helper')
describe TabsController, type: :request do
describe 'index' do
it "should require read permissions on the context" do
course(:active_all => true)
user(:active_all => true)
api_call(:get, "/api/v1/courses/#{@course.id}/tabs",
{ :controller => 'tabs', :action => 'index', :course_id => @course.to_param, :format => 'json'},
{ :include => ['external']},
{},
{ :expected_status => 401 })
end
it 'should list navigation tabs for a course' do
course_with_teacher(:active_all => true)
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs",
{ :controller => 'tabs', :action => 'index', :course_id => @course.to_param, :format => 'json'},
{ :include => ['external']})
json.should == [
{
"id" => "home",
"html_url" => "/courses/#{@course.id}",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}",
"position" => 1,
"visibility" => "public",
"label" => "Home",
"type" => "internal"
},
{
"id" => "announcements",
"html_url" => "/courses/#{@course.id}/announcements",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/announcements",
"position" => 2,
"unused" => true,
"visibility" => "admins",
"label" => "Announcements",
"type" => "internal"
},
{
"id" => "assignments",
"html_url" => "/courses/#{@course.id}/assignments",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/assignments",
"position" => 3,
"unused" => true,
"visibility" => "admins",
"label" => "Assignments",
"type" => "internal"
},
{
"id" => "discussions",
"html_url" => "/courses/#{@course.id}/discussion_topics",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/discussion_topics",
"position" => 4,
"visibility" => "public",
"label" => "Discussions",
"type" => "internal"
},
{
"id" => "grades",
"html_url" => "/courses/#{@course.id}/grades",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/grades",
"position" => 5,
"visibility" => "public",
"label" => "Grades",
"type" => "internal"
},
{
"id" => "people",
"html_url" => "/courses/#{@course.id}/users",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/users",
"position" => 6,
"visibility" => "public",
"label" => "People",
"type" => "internal"
},
{
"id" => "pages",
"html_url" => "/courses/#{@course.id}/wiki",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/wiki",
"position" => 7,
"unused" => true,
"visibility" => "admins",
"label" => "Pages",
"type" => "internal"
},
{
"id" => "files",
"html_url" => "/courses/#{@course.id}/files",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/files",
"position" => 8,
"unused" => true,
"visibility" => "admins",
"label" => "Files",
"type" => "internal"
},
{
"id" => "syllabus",
"html_url" => "/courses/#{@course.id}/assignments/syllabus",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/assignments/syllabus",
"position" => 9,
"visibility" => "public",
"label" => "Syllabus",
"type" => "internal"
},
{
"id" => "outcomes",
"html_url" => "/courses/#{@course.id}/outcomes",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/outcomes",
"position" => 10,
"unused" => true,
"visibility" => "admins",
"label" => "Outcomes",
"type" => "internal"
},
{
"id" => "quizzes",
"html_url" => "/courses/#{@course.id}/quizzes",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/quizzes",
"position" => 11,
"unused" => true,
"visibility" => "admins",
"label" => "Quizzes",
"type" => "internal"
},
{
"id" => "modules",
"html_url" => "/courses/#{@course.id}/modules",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/modules",
"position" => 12,
"unused" => true,
"visibility" => "admins",
"label" => "Modules",
"type" => "internal"
},
{
"id" => "settings",
"html_url" => "/courses/#{@course.id}/settings",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@course)}/courses/#{@course.id}/settings",
"position" => 13,
"visibility" => "admins",
"label" => "Settings",
"type" => "internal"
}
]
end
it 'should include external tools' do
course_with_teacher(:active_all => true)
@tool = @course.context_external_tools.new({
:name => 'Example',
:url => 'http://www.example.com',
:consumer_key => 'key',
:shared_secret => 'secret',
})
@tool.settings.merge!({
:course_navigation => {
:enabled => 'true',
:url => 'http://www.example.com',
},
})
@tool.save!
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs",
{ :controller => 'tabs', :action => 'index', :course_id => @course.to_param, :format => 'json'},
{ :include => ['external']})
external_tabs = json.select {|tab| tab['type'] == 'external'}
external_tabs.length.should == 1
external_tabs.each do |tab|
tab.should include('url')
uri = URI(tab['url'])
uri.path.should == "/api/v1/courses/#{@course.id}/external_tools/sessionless_launch"
uri.query.should include('id=')
end
end
it 'should list navigation tabs for a group' do
group_with_user(:active_all => true)
json = api_call(:get, "/api/v1/groups/#{@group.id}/tabs",
{ :controller => 'tabs', :action => 'index', :group_id => @group.to_param, :format => 'json'})
json.should == [
{
"id" => "home",
"html_url" => "/groups/#{@group.id}",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@group)}/groups/#{@group.id}",
"type" => "internal",
"label" => "Home",
"position"=>1,
"visibility"=>"public"
},
{
"id" => "announcements",
"label" => "Announcements",
"html_url" => "/groups/#{@group.id}/announcements",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@group)}/groups/#{@group.id}/announcements",
"position"=>2,
"visibility"=>"public",
"type" => "internal"
},
{
"id" => "pages",
"html_url" => "/groups/#{@group.id}/wiki",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@group)}/groups/#{@group.id}/wiki",
"label" => "Pages",
"position"=>3,
"visibility"=>"public",
"type" => "internal"
},
{
"id" => "people",
"html_url" => "/groups/#{@group.id}/users",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@group)}/groups/#{@group.id}/users",
"label" => "People",
"position"=>4,
"visibility"=>"public",
"type" => "internal"
},
{
"id" => "discussions",
"html_url" => "/groups/#{@group.id}/discussion_topics",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@group)}/groups/#{@group.id}/discussion_topics",
"label" => "Discussions",
"position"=>5,
"visibility"=>"public",
"type" => "internal"
},
{
"id" => "files",
"html_url" => "/groups/#{@group.id}/files",
"full_url" => "#{HostUrl.protocol}://#{HostUrl.context_host(@group)}/groups/#{@group.id}/files",
"label" => "Files",
"position"=>6,
"visibility"=>"public",
"type" => "internal"
}
]
end
it "doesn't include hidden tabs for student" do
course_with_student(active_all: true)
tab_ids = [0, 1, 3, 8, 5, 6, 14, 2, 11, 15, 4, 10, 13]
hidden_tabs = [3, 8, 5]
@course.tab_configuration = tab_ids.map do |n|
hash = {'id' => n}
hash['hidden'] = true if hidden_tabs.include?(n)
hash
end
@course.save
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs", { :controller => 'tabs', :action => 'index',
:course_id => @course.to_param, :format => 'json'})
json.count.should == 3
json.each {|t| %w{home syllabus people}.should include(t['id'])}
end
describe "teacher in a course" do
before :once do
course_with_teacher(active_all: true)
@tab_ids = [0, 1, 3, 8, 5, 6, 14, 2, 11, 15, 4, 10, 13]
@tab_lookup = {}.with_indifferent_access
@course.tabs_available(@teacher, :api => true).each do |t|
t = t.with_indifferent_access
@tab_lookup[t['css_class']] = t['id']
end
end
it 'should have the correct position' do
tab_order = [0, 1, 3, 8, 5, 6, 14, 2, 11, 15, 4, 10, 13]
@course.tab_configuration = tab_order.map { |n| {'id' => n} }
@course.save
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs", {:controller => 'tabs', :action => 'index',
:course_id => @course.to_param, :format => 'json'})
json.each { |t| t['position'].should == tab_order.find_index(@tab_lookup[t['id']]) + 1 }
end
it 'should correctly label navigation items as unused' do
unused_tabs = %w{announcements assignments pages files outcomes quizzes modules}
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs", {:controller => 'tabs', :action => 'index',
:course_id => @course.to_param, :format => 'json'})
json.each do |t|
if unused_tabs.include? t['id']
t['unused'].should be_true
else
t['unused'].should be_false
end
end
end
it 'should label hidden items correctly' do
hidden_tabs = [3, 8, 5]
@course.tab_configuration = @tab_ids.map do |n|
hash = {'id' => n}
hash['hidden'] = true if hidden_tabs.include?(n)
hash
end
@course.save
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs", {:controller => 'tabs', :action => 'index',
:course_id => @course.to_param, :format => 'json'})
json.each do |t|
if hidden_tabs.include? @tab_lookup[t['id']]
t['hidden'].should be_true
else
t['hidden'].should be_false
end
end
end
it 'correctly sets visibility' do
hidden_tabs = [3, 8, 5]
public_visibility = %w{home people syllabus}
admins_visibility = %w{announcements assignments pages files outcomes quizzes modules settings discussions grades}
@course.tab_configuration = @tab_ids.map do |n|
hash = {'id' => n}
hash['hidden'] = true if hidden_tabs.include?(n)
hash
end
@course.save
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs", {:controller => 'tabs', :action => 'index',
:course_id => @course.to_param, :format => 'json'})
json.each do |t|
if t['visibility'] == 'public'
public_visibility.should include(t['id'])
elsif t['visibility'] == 'admins'
admins_visibility.should include(t['id'])
else
true.should be_false
end
end
end
it 'sorts tabs correctly' do
course_with_teacher(active_all: true)
tab_order = [0, 1, 3, 8, 5, 6, 14, 2, 11, 15, 4, 10, 13]
@course.tab_configuration = tab_order.map { |n| {'id' => n} }
@course.save
json = api_call(:get, "/api/v1/courses/#{@course.id}/tabs", {:controller => 'tabs', :action => 'index',
:course_id => @course.to_param, :format => 'json'})
json.each_with_index { |t, i| t['position'].should == i+1 }
end
end
end
describe 'update' do
it 'sets the people tab to hidden' do
tab_id = 'people'
course_with_teacher(active_all: true)
json = api_call(:put, "/api/v1/courses/#{@course.id}/tabs/#{tab_id}", {:controller => 'tabs', :action => 'update',
:course_id => @course.to_param, :tab_id => tab_id,
:format => 'json', :hidden => true})
json['hidden'].should == true
@course.reload.tab_configuration[json['position'] - 1]['hidden'].should == true
end
it 'changes the position of the people tab to 2' do
tab_id = 'people'
course_with_teacher(active_all: true)
json = api_call(:put, "/api/v1/courses/#{@course.id}/tabs/#{tab_id}", {:controller => 'tabs', :action => 'update',
:course_id => @course.to_param, :tab_id => tab_id,
:format => 'json', :position => 2})
json['position'].should == 2
@course.reload.tab_configuration[1]['id'].should == @course.class::TAB_PEOPLE
end
it "won't allow you to hide the home tab" do
tab_id = 'home'
course_with_teacher(active_all: true)
result = raw_api_call(:put, "/api/v1/courses/#{@course.id}/tabs/#{tab_id}", {:controller => 'tabs', :action => 'update',
:course_id => @course.to_param, :tab_id => tab_id,
:format => 'json', :hidden => true})
result.should == 400
end
it "won't allow you to move a tab to the first position" do
tab_id = 'people'
course_with_teacher(active_all: true)
result = raw_api_call(:put, "/api/v1/courses/#{@course.id}/tabs/#{tab_id}", {:controller => 'tabs', :action => 'update',
:course_id => @course.to_param, :tab_id => tab_id,
:format => 'json', :position => 1})
result.should == 400
end
it "won't allow you to move a tab to an invalid position" do
tab_id = 'people'
course_with_teacher(active_all: true)
result = raw_api_call(:put, "/api/v1/courses/#{@course.id}/tabs/#{tab_id}", {:controller => 'tabs', :action => 'update',
:course_id => @course.to_param, :tab_id => tab_id,
:format => 'json', :position => 400})
result.should == 400
end
it "doesn't allow a student to modify a tab" do
course_with_student(active_all: true)
tab_id = 'people'
result = raw_api_call(:put, "/api/v1/courses/#{@course.id}/tabs/#{tab_id}", {:controller => 'tabs', :action => 'update',
:course_id => @course.to_param, :tab_id => tab_id,
:format => 'json', :position => 4})
result.should == 401
end
end
end
|
wye0220/shindig-canvas
|
spec/apis/v1/tabs_api_spec.rb
|
Ruby
|
agpl-3.0
| 17,643
|
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa30;
import org.tanaguru.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 4.13.2 of the referential Rgaa 3.0.
*
* For more details about the implementation, refer to <a href="http://tanaguru-rules-rgaa3.readthedocs.org/en/latest/Rule-4-13-2">the rule 4.13.2 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-4-13-2"> 4.13.2 rule specification</a>
*/
public class Rgaa30Rule041302 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa30Rule041302 () {
super();
}
}
|
Tanaguru/Tanaguru
|
rules/rgaa3.0/src/main/java/org/tanaguru/rules/rgaa30/Rgaa30Rule041302.java
|
Java
|
agpl-3.0
| 1,474
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.