code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
/* 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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Text",
inherited=False,
gecko_name="TextReset",
additional_methods=[Method("has_underline", "bool"),
Method("has_overline", "bool"),
Method("has_line_through", "bool")]) %>
${helpers.single_keyword("text-overflow", "clip ellipsis")}
${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")}
<%helpers:longhand name="${'text-decoration' if product == 'servo' else 'text-decoration-line'}"
custom_cascade="${product == 'servo'}">
use cssparser::ToCss;
use std::fmt;
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue {
pub underline: bool,
pub overline: bool,
pub line_through: bool,
// 'blink' is accepted in the parser but ignored.
// Just not blinking the text is a conforming implementation per CSS 2.1.
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut space = false;
if self.underline {
try!(dest.write_str("underline"));
space = true;
}
if self.overline {
if space {
try!(dest.write_str(" "));
}
try!(dest.write_str("overline"));
space = true;
}
if self.line_through {
if space {
try!(dest.write_str(" "));
}
try!(dest.write_str("line-through"));
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(non_upper_case_globals)]
pub const none: T = super::SpecifiedValue {
underline: false, overline: false, line_through: false
};
}
#[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::none
}
/// none | [ underline || overline || line-through || blink ]
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let mut result = SpecifiedValue {
underline: false, overline: false, line_through: false,
};
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(result)
}
let mut blink = false;
let mut empty = true;
while input.try(|input| {
if let Ok(ident) = input.expect_ident() {
match_ignore_ascii_case! { ident,
"underline" => if result.underline { return Err(()) }
else { empty = false; result.underline = true },
"overline" => if result.overline { return Err(()) }
else { empty = false; result.overline = true },
"line-through" => if result.line_through { return Err(()) }
else { empty = false; result.line_through = true },
"blink" => if blink { return Err(()) }
else { empty = false; blink = true },
_ => return Err(())
}
} else {
return Err(());
}
Ok(())
}).is_ok() {
}
if !empty { Ok(result) } else { Err(()) }
}
% if product == "servo":
fn cascade_property_custom<C: ComputedValues>(
_declaration: &PropertyDeclaration,
_inherited_style: &C,
context: &mut computed::Context<C>,
_seen: &mut PropertyBitField,
_cacheable: &mut bool,
_error_reporter: &mut StdBox<ParseErrorReporter + Send>) {
longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context);
}
% endif
</%helpers:longhand>
${helpers.single_keyword("text-decoration-style",
"solid double dotted dashed wavy -moz-none",
products="gecko")}
${helpers.predefined_type(
"text-decoration-color", "CSSColor",
"CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0 })",
products="gecko")}
| Java |
module.exports = { domain:"messages",
locale_data:{ messages:{ "":{ domain:"messages",
plural_forms:"nplurals=2; plural=(n != 1);",
lang:"el" },
"%(addonName)s %(startSpan)sby %(authorList)s%(endSpan)s":[ "%(addonName)s %(startSpan)s από %(authorList)s%(endSpan)s" ],
"Extension Metadata":[ "Μεταδεδομένα επέκτασης" ],
Screenshots:[ "Στιγμιότυπα" ],
"About this extension":[ "Σχετικά με την επέκταση" ],
"Rate your experience":[ "Αξιολογήστε την εμπειρία σας" ],
Category:[ "Κατηγορία" ],
"Used by":[ "Χρήση από" ],
Sentiment:[ "Αίσθηση" ],
Back:[ "Πίσω" ],
Submit:[ "Υποβολή" ],
"Please enter some text":[ "Παρακαλώ εισάγετε κείμενο" ],
"Write a review":[ "Γράψτε μια κριτική" ],
"Tell the world why you think this extension is fantastic!":[ "Πείτε στον κόσμο γιατί θεωρείτε ότι αυτή η επέκταση είναι φανταστική!" ],
"Privacy policy":[ "Πολιτική απορρήτου" ],
"Legal notices":[ "Νομικές σημειώσεις" ],
"View desktop site":[ "Προβολή ιστοσελίδας για υπολογιστές" ],
"Browse in your language":[ "Περιήγηση στη γλώσσα σας" ],
"Firefox Add-ons":[ "Πρόσθετα Firefox" ],
"How are you enjoying your experience with %(addonName)s?":[ "Απολαμβάνετε την εμπειρία σας με το %(addonName)s;" ],
"screenshot %(imageNumber)s of %(totalImages)s":[ "Στιγμιότυπο %(imageNumber)s από %(totalImages)s" ],
"Average rating: %(rating)s out of 5":[ "Μέση βαθμολογία: %(rating)s από 5" ],
"No ratings":[ "Καμία κριτική" ],
"%(users)s user":[ "%(users)s χρήστης",
"%(users)s χρήστες" ],
"Log out":[ "Αποσύνδεση" ],
"Log in/Sign up":[ "Σύνδεση/Εγγραφή" ],
"Add-ons for Firefox":[ "Πρόσθετα για το Firefox" ],
"What do you want Firefox to do?":[ "Τι θέλετε να κάνει το Firefox;" ],
"Block ads":[ "Αποκλεισμός διαφημίσεων" ],
Screenshot:[ "Στιγμιότυπο οθόνης" ],
"Save stuff":[ "Αποθήκευση στοιχείων" ],
"Shop online":[ "Διαδικτυακές αγορές" ],
"Be social":[ "Κοινωνικοποίηση" ],
"Share stuff":[ "Κοινή χρήση στοιχείων" ],
"Browse all extensions":[ "Περιήγηση σε όλες τις επεκτάσεις" ],
"How do you want Firefox to look?":[ "Τι εμφάνιση θέλετε να έχει το Firefox;" ],
Wild:[ "Άγρια" ],
Abstract:[ "Αφηρημένη" ],
Fashionable:[ "Μοδάτη" ],
Scenic:[ "Σκηνική" ],
Sporty:[ "Αθλητική" ],
Mystical:[ "Μυστική" ],
"Browse all themes":[ "Περιήγηση σε όλα τα θέματα" ],
"Downloading %(name)s.":[ "Γίνεται λήψη του %(name)s." ],
"Installing %(name)s.":[ "Γίνεται εγκατάσταση του %(name)s." ],
"%(name)s is installed and enabled. Click to uninstall.":[ "Το %(name)s έχει εγκατασταθεί και ενεργοποιηθεί. Κάντε κλικ για απεγκατάσταση." ],
"%(name)s is disabled. Click to enable.":[ "Το %(name)s έχει απενεργοποιηθεί. Κάντε κλικ για ενεργοποίηση." ],
"Uninstalling %(name)s.":[ "Γίνεται απεγκατάσταση του %(name)s." ],
"%(name)s is uninstalled. Click to install.":[ "Το %(name)s έχει απεγκατασταθεί. Κάντε κλικ για εγκατάσταση." ],
"Install state for %(name)s is unknown.":[ "Η κατάσταση εγκατάστασης για το %(name)s είναι άγνωστη." ],
Previous:[ "Προηγούμενη" ],
Next:[ "Επόμενη" ],
"Page %(currentPage)s of %(totalPages)s":[ "Σελίδα %(currentPage)s από %(totalPages)s" ],
"Your search for \"%(query)s\" returned %(count)s result.":[ "Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτέλεσμα.",
"Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτελέσματα." ],
"Searching...":[ "Αναζήτηση..." ],
"No results were found for \"%(query)s\".":[ "Δεν βρέθηκε κανένα αποτέλεσμα για το \"%(query)s\"." ],
"Please supply a valid search":[ "Παρακαλώ κάντε μια έγκυρη αναζήτηση" ] } },
_momentDefineLocale:function anonymous() {
//! moment.js locale configuration
//! locale : Greek [el]
//! author : Aggelos Karalias : https://github.com/mehiel
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
function isFunction(input) {
return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
var el = moment.defineLocale('el', {
monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),
monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),
months : function (momentToFormat, format) {
if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
return this._monthsGenitiveEl[momentToFormat.month()];
} else {
return this._monthsNominativeEl[momentToFormat.month()];
}
},
monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),
weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),
weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),
weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),
meridiem : function (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'μμ' : 'ΜΜ';
} else {
return isLower ? 'πμ' : 'ΠΜ';
}
},
isPM : function (input) {
return ((input + '').toLowerCase()[0] === 'μ');
},
meridiemParse : /[ΠΜ]\.?Μ?\.?/i,
longDateFormat : {
LT : 'h:mm A',
LTS : 'h:mm:ss A',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY h:mm A',
LLLL : 'dddd, D MMMM YYYY h:mm A'
},
calendarEl : {
sameDay : '[Σήμερα {}] LT',
nextDay : '[Αύριο {}] LT',
nextWeek : 'dddd [{}] LT',
lastDay : '[Χθες {}] LT',
lastWeek : function () {
switch (this.day()) {
case 6:
return '[το προηγούμενο] dddd [{}] LT';
default:
return '[την προηγούμενη] dddd [{}] LT';
}
},
sameElse : 'L'
},
calendar : function (key, mom) {
var output = this._calendarEl[key],
hours = mom && mom.hours();
if (isFunction(output)) {
output = output.apply(mom);
}
return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις'));
},
relativeTime : {
future : 'σε %s',
past : '%s πριν',
s : 'λίγα δευτερόλεπτα',
m : 'ένα λεπτό',
mm : '%d λεπτά',
h : 'μία ώρα',
hh : '%d ώρες',
d : 'μία μέρα',
dd : '%d μέρες',
M : 'ένας μήνας',
MM : '%d μήνες',
y : 'ένας χρόνος',
yy : '%d χρόνια'
},
ordinalParse: /\d{1,2}η/,
ordinal: '%dη',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4st is the first week of the year.
}
});
return el;
})));
} } | Java |
// Copyright Hugh Perkins 2015 hughperkins at gmail
//
// 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/.
// although this looks a bit odd perhaps, this way we dont need to change the existing
// qlearning api much, so dont need to break anything that works already
#pragma once
#include <stdexcept>
#include <iostream>
#include <string>
#include "qlearning/QLearner.h"
#include "trainers/Trainer.h"
class ScenarioProxy : public Scenario {
public:
const int numActions;
const int planes;
const int size;
// float *perception; // NOT owned by us, dont delete
// float lastReward;
// int thisAction;
// bool isReset;
ScenarioProxy( int numActions, int planes, int size ) :
numActions(numActions), planes(planes), size(size) {
}
virtual int getPerceptionSize() {
return size;
}
virtual int getPerceptionPlanes() {
return planes;
}
virtual void getPerception( float *perception ) {
// perception = this->perception;
throw std::runtime_error("getPerception not implemented");
}
virtual void reset() {
// noop?
throw std::runtime_error("reset not implemented");
}
virtual int getNumActions() {
// std::cout << "numActions: " << numActions << std::endl;
return numActions;
// throw runtime_error("getNumActions not implemented");
}
virtual float act( int index ) {
// this->thisAction = index;
// return lastReward;
throw std::runtime_error("act not implemented");
}
virtual bool hasFinished() {
// return isReset;
throw std::runtime_error("hasFinished not implemented");
}
};
// The advantage of this over the original QLearning is that it doesnt do any callbacks
// so it should be super-easy to wrap, using Lua, Python, etc ...
class QLearner2 {
QLearner *qlearner;
ScenarioProxy *scenario;
NeuralNet *net;
// int planes;
// int size;
// int numActions;
public:
QLearner2( Trainer *trainer, NeuralNet *net, int numActions, int planes, int size ) : net(net) {
scenario = new ScenarioProxy( numActions, planes, size );
qlearner = new QLearner( trainer, scenario, net );
}
~QLearner2() {
delete qlearner;
delete scenario;
}
// QLearner2 *setPlanes( int planes ) {
// this->planes = planes;
// scenario->planes = planes;
// return this;
// }
// QLearner2 *setSize( int size ) {
// this->size = size;
// scenario->size = size;
// return this;
// }
// QLearner2 *setNumActions( int numActions ) {
// this->numActions = numActions;
// scenario->numActions = numActions;
// return this;
// }
int step(double lastReward, bool wasReset, float *perception) {
// scenario->lastReward = lastReward;
// scenario->isReset = isReset;
// scenario->perception = currentPerception;
int action = qlearner->step( lastReward, wasReset, perception );
return action;
}
void setLambda( float lambda ) { qlearner->setLambda( lambda ); }
void setMaxSamples( int maxSamples ) { qlearner->setMaxSamples( maxSamples ); }
void setEpsilon( float epsilon ) { qlearner->setEpsilon( epsilon ); }
// void setLearningRate( float learningRate ) { qlearner->setLearningRate( learningRate ); }
};
| Java |
#include <iostream>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <syslog.h>
#include <dlfcn.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include "webserver_api_functions.h"
static void termination_handler(int signum) {
WebserverShutdownHandler();
}
static void sig_pipe_hanler(int signum) {
//printf("Sig Pipe\n");
}
DEFINE_WEBSOCKET_HANDLER( "TestSocket" , TestSocket ) {
switch (signal) {
case WEBSOCKET_CONNECT:
printf("Websocket API Connect TestSocket : %s \n", guid);
break;
case WEBSOCKET_DISCONNECT:
printf("Websocket API Disconnect TestSocket : %s \n", guid);
break;
case WEBSOCKET_MSG:
printf("Websocket API TestSocket Msg 1 %s\n", msg);
WebsocketSendTextFrame(guid, msg, strlen(msg));
break;
}
}
int main(int argc, char **argv) {
if (signal(SIGINT, termination_handler) == SIG_IGN ) signal(SIGINT, SIG_IGN);
if (signal(SIGHUP, termination_handler) == SIG_IGN ) signal(SIGHUP, SIG_IGN);
if (signal(SIGTERM, termination_handler) == SIG_IGN ) signal(SIGTERM, SIG_IGN);
if (signal(SIGPIPE, sig_pipe_hanler) == SIG_IGN ) signal(SIGPIPE, SIG_IGN);
if (0 == WebserverInit()) {
WebserverAddFileDir("", "www");
WebserverConfigSetInt("port",8080);
REGISTER_WEBSOCKET_HANDLER ( TestSocket );
WebserverStart();
}
WebserverShutdown();
return 0;
}
| Java |
/* 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/. */
/* A 32-bit implementation of the NIST P-256 elliptic curve. */
#include <string.h>
#include "prtypes.h"
#include "mpi.h"
#include "mpi-priv.h"
#include "ecp.h"
typedef PRUint8 u8;
typedef PRUint32 u32;
typedef PRUint64 u64;
/* Our field elements are represented as nine, unsigned 32-bit words. Freebl's
* MPI library calls them digits, but here they are called limbs, which is
* GMP's terminology.
*
* The value of an felem (field element) is:
* x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228)
*
* That is, each limb is alternately 29 or 28-bits wide in little-endian
* order.
*
* This means that an felem hits 2**257, rather than 2**256 as we would like. A
* 28, 29, ... pattern would cause us to hit 2**256, but that causes problems
* when multiplying as terms end up one bit short of a limb which would require
* much bit-shifting to correct.
*
* Finally, the values stored in an felem are in Montgomery form. So the value
* |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257.
*/
typedef u32 limb;
#define NLIMBS 9
typedef limb felem[NLIMBS];
static const limb kBottom28Bits = 0xfffffff;
static const limb kBottom29Bits = 0x1fffffff;
/* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and
* 28-bit words.
*/
static const felem kOne = {
2, 0, 0, 0xffff800,
0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff,
0
};
static const felem kZero = {0};
static const felem kP = {
0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff,
0, 0, 0x200000, 0xf000000,
0xfffffff
};
static const felem k2P = {
0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff,
0, 0, 0x400000, 0xe000000,
0x1fffffff
};
/* kPrecomputed contains precomputed values to aid the calculation of scalar
* multiples of the base point, G. It's actually two, equal length, tables
* concatenated.
*
* The first table contains (x,y) felem pairs for 16 multiples of the base
* point, G.
*
* Index | Index (binary) | Value
* 0 | 0000 | 0G (all zeros, omitted)
* 1 | 0001 | G
* 2 | 0010 | 2**64G
* 3 | 0011 | 2**64G + G
* 4 | 0100 | 2**128G
* 5 | 0101 | 2**128G + G
* 6 | 0110 | 2**128G + 2**64G
* 7 | 0111 | 2**128G + 2**64G + G
* 8 | 1000 | 2**192G
* 9 | 1001 | 2**192G + G
* 10 | 1010 | 2**192G + 2**64G
* 11 | 1011 | 2**192G + 2**64G + G
* 12 | 1100 | 2**192G + 2**128G
* 13 | 1101 | 2**192G + 2**128G + G
* 14 | 1110 | 2**192G + 2**128G + 2**64G
* 15 | 1111 | 2**192G + 2**128G + 2**64G + G
*
* The second table follows the same style, but the terms are 2**32G,
* 2**96G, 2**160G, 2**224G.
*
* This is ~2KB of data.
*/
static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = {
0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee,
0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3,
0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c,
0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22,
0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050,
0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b,
0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa,
0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2,
0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609,
0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581,
0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca,
0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33,
0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6,
0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd,
0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0,
0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881,
0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a,
0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26,
0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b,
0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023,
0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133,
0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa,
0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29,
0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc,
0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8,
0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59,
0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39,
0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689,
0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa,
0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3,
0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1,
0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f,
0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72,
0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d,
0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b,
0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a,
0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a,
0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f,
0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb,
0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc,
0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9,
0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce,
0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2,
0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca,
0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229,
0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57,
0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c,
0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa,
0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651,
0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec,
0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7,
0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c,
0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927,
0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298,
0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8,
0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2,
0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d,
0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4,
0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8,
0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78,
};
/* Field element operations:
*/
/* NON_ZERO_TO_ALL_ONES returns:
* 0xffffffff for 0 < x <= 2**31
* 0 for x == 0 or x > 2**31.
*
* x must be a u32 or an equivalent type such as limb.
*/
#define NON_ZERO_TO_ALL_ONES(x) ((((u32)(x) - 1) >> 31) - 1)
/* felem_reduce_carry adds a multiple of p in order to cancel |carry|,
* which is a term at 2**257.
*
* On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28.
* On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29.
*/
static void felem_reduce_carry(felem inout, limb carry)
{
const u32 carry_mask = NON_ZERO_TO_ALL_ONES(carry);
inout[0] += carry << 1;
inout[3] += 0x10000000 & carry_mask;
/* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the
* previous line therefore this doesn't underflow.
*/
inout[3] -= carry << 11;
inout[4] += (0x20000000 - 1) & carry_mask;
inout[5] += (0x10000000 - 1) & carry_mask;
inout[6] += (0x20000000 - 1) & carry_mask;
inout[6] -= carry << 22;
/* This may underflow if carry is non-zero but, if so, we'll fix it in the
* next line.
*/
inout[7] -= 1 & carry_mask;
inout[7] += carry << 25;
}
/* felem_sum sets out = in+in2.
*
* On entry, in[i]+in2[i] must not overflow a 32-bit word.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29
*/
static void felem_sum(felem out, const felem in, const felem in2)
{
limb carry = 0;
unsigned int i;
for (i = 0;; i++) {
out[i] = in[i] + in2[i];
out[i] += carry;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
out[i] = in[i] + in2[i];
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
#define two31m3 (((limb)1) << 31) - (((limb)1) << 3)
#define two30m2 (((limb)1) << 30) - (((limb)1) << 2)
#define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2)
#define two31m2 (((limb)1) << 31) - (((limb)1) << 2)
#define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2)
#define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2)
/* zero31 is 0 mod p.
*/
static const felem zero31 = {
two31m3, two30m2, two31m2, two30p13m2,
two31m2, two30m2, two31p24m2, two30m27m2,
two31m2
};
/* felem_diff sets out = in-in2.
*
* On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and
* in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_diff(felem out, const felem in, const felem in2)
{
limb carry = 0;
unsigned int i;
for (i = 0;; i++) {
out[i] = in[i] - in2[i];
out[i] += zero31[i];
out[i] += carry;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
out[i] = in[i] - in2[i];
out[i] += zero31[i];
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words
* with the same 29,28,... bit positions as an felem.
*
* The values in felems are in Montgomery form: x*R mod p where R = 2**257.
* Since we just multiplied two Montgomery values together, the result is
* x*y*R*R mod p. We wish to divide by R in order for the result also to be
* in Montgomery form.
*
* On entry: tmp[i] < 2**64
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29
*/
static void felem_reduce_degree(felem out, u64 tmp[17])
{
/* The following table may be helpful when reading this code:
*
* Limb number: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10...
* Width (bits): 29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29
* Start bit: 0 | 29| 57| 86|114|143|171|200|228|257|285
* (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285
*/
limb tmp2[18], carry, x, xMask;
unsigned int i;
/* tmp contains 64-bit words with the same 29,28,29-bit positions as an
* felem. So the top of an element of tmp might overlap with another
* element two positions down. The following loop eliminates this
* overlap.
*/
tmp2[0] = tmp[0] & kBottom29Bits;
/* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>32)" to try
* and hint to the compiler that it can do a single-word shift by selecting
* the right register rather than doing a double-word shift and truncating
* afterwards.
*/
tmp2[1] = ((limb) tmp[0]) >> 29;
tmp2[1] |= (((limb) (tmp[0] >> 32)) << 3) & kBottom28Bits;
tmp2[1] += ((limb) tmp[1]) & kBottom28Bits;
carry = tmp2[1] >> 28;
tmp2[1] &= kBottom28Bits;
for (i = 2; i < 17; i++) {
tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25;
tmp2[i] += ((limb) (tmp[i - 1])) >> 28;
tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 4) & kBottom29Bits;
tmp2[i] += ((limb) tmp[i]) & kBottom29Bits;
tmp2[i] += carry;
carry = tmp2[i] >> 29;
tmp2[i] &= kBottom29Bits;
i++;
if (i == 17)
break;
tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25;
tmp2[i] += ((limb) (tmp[i - 1])) >> 29;
tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 3) & kBottom28Bits;
tmp2[i] += ((limb) tmp[i]) & kBottom28Bits;
tmp2[i] += carry;
carry = tmp2[i] >> 28;
tmp2[i] &= kBottom28Bits;
}
tmp2[17] = ((limb) (tmp[15] >> 32)) >> 25;
tmp2[17] += ((limb) (tmp[16])) >> 29;
tmp2[17] += (((limb) (tmp[16] >> 32)) << 3);
tmp2[17] += carry;
/* Montgomery elimination of terms:
*
* Since R is 2**257, we can divide by R with a bitwise shift if we can
* ensure that the right-most 257 bits are all zero. We can make that true
* by adding multiplies of p without affecting the value.
*
* So we eliminate limbs from right to left. Since the bottom 29 bits of p
* are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.
* We can do that for 8 further limbs and then right shift to eliminate the
* extra factor of R.
*/
for (i = 0;; i += 2) {
tmp2[i + 1] += tmp2[i] >> 29;
x = tmp2[i] & kBottom29Bits;
xMask = NON_ZERO_TO_ALL_ONES(x);
tmp2[i] = 0;
/* The bounds calculations for this loop are tricky. Each iteration of
* the loop eliminates two words by adding values to words to their
* right.
*
* The following table contains the amounts added to each word (as an
* offset from the value of i at the top of the loop). The amounts are
* accounted for from the first and second half of the loop separately
* and are written as, for example, 28 to mean a value <2**28.
*
* Word: 3 4 5 6 7 8 9 10
* Added in top half: 28 11 29 21 29 28
* 28 29
* 29
* Added in bottom half: 29 10 28 21 28 28
* 29
*
* The value that is currently offset 7 will be offset 5 for the next
* iteration and then offset 3 for the iteration after that. Therefore
* the total value added will be the values added at 7, 5 and 3.
*
* The following table accumulates these values. The sums at the bottom
* are written as, for example, 29+28, to mean a value < 2**29+2**28.
*
* Word: 3 4 5 6 7 8 9 10 11 12 13
* 28 11 10 29 21 29 28 28 28 28 28
* 29 28 11 28 29 28 29 28 29 28
* 29 28 21 21 29 21 29 21
* 10 29 28 21 28 21 28
* 28 29 28 29 28 29 28
* 11 10 29 10 29 10
* 29 28 11 28 11
* 29 29
* --------------------------------------------
* 30+ 31+ 30+ 31+ 30+
* 28+ 29+ 28+ 29+ 21+
* 21+ 28+ 21+ 28+ 10
* 10 21+ 10 21+
* 11 11
*
* So the greatest amount is added to tmp2[10] and tmp2[12]. If
* tmp2[10/12] has an initial value of <2**29, then the maximum value
* will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32,
* as required.
*/
tmp2[i + 3] += (x << 10) & kBottom28Bits;
tmp2[i + 4] += (x >> 18);
tmp2[i + 6] += (x << 21) & kBottom29Bits;
tmp2[i + 7] += x >> 8;
/* At position 200, which is the starting bit position for word 7, we
* have a factor of 0xf000000 = 2**28 - 2**24.
*/
tmp2[i + 7] += 0x10000000 & xMask;
/* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */
tmp2[i + 8] += (x - 1) & xMask;
tmp2[i + 7] -= (x << 24) & kBottom28Bits;
tmp2[i + 8] -= x >> 4;
tmp2[i + 8] += 0x20000000 & xMask;
tmp2[i + 8] -= x;
tmp2[i + 8] += (x << 28) & kBottom29Bits;
tmp2[i + 9] += ((x >> 1) - 1) & xMask;
if (i+1 == NLIMBS)
break;
tmp2[i + 2] += tmp2[i + 1] >> 28;
x = tmp2[i + 1] & kBottom28Bits;
xMask = NON_ZERO_TO_ALL_ONES(x);
tmp2[i + 1] = 0;
tmp2[i + 4] += (x << 11) & kBottom29Bits;
tmp2[i + 5] += (x >> 18);
tmp2[i + 7] += (x << 21) & kBottom28Bits;
tmp2[i + 8] += x >> 7;
/* At position 199, which is the starting bit of the 8th word when
* dealing with a context starting on an odd word, we have a factor of
* 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th
* word from i+1 is i+8.
*/
tmp2[i + 8] += 0x20000000 & xMask;
tmp2[i + 9] += (x - 1) & xMask;
tmp2[i + 8] -= (x << 25) & kBottom29Bits;
tmp2[i + 9] -= x >> 4;
tmp2[i + 9] += 0x10000000 & xMask;
tmp2[i + 9] -= x;
tmp2[i + 10] += (x - 1) & xMask;
}
/* We merge the right shift with a carry chain. The words above 2**257 have
* widths of 28,29,... which we need to correct when copying them down.
*/
carry = 0;
for (i = 0; i < 8; i++) {
/* The maximum value of tmp2[i + 9] occurs on the first iteration and
* is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is
* therefore safe.
*/
out[i] = tmp2[i + 9];
out[i] += carry;
out[i] += (tmp2[i + 10] << 28) & kBottom29Bits;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
out[i] = tmp2[i + 9] >> 1;
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
out[8] = tmp2[17];
out[8] += carry;
carry = out[8] >> 29;
out[8] &= kBottom29Bits;
felem_reduce_carry(out, carry);
}
/* felem_square sets out=in*in.
*
* On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_square(felem out, const felem in)
{
u64 tmp[17];
tmp[0] = ((u64) in[0]) * in[0];
tmp[1] = ((u64) in[0]) * (in[1] << 1);
tmp[2] = ((u64) in[0]) * (in[2] << 1) +
((u64) in[1]) * (in[1] << 1);
tmp[3] = ((u64) in[0]) * (in[3] << 1) +
((u64) in[1]) * (in[2] << 1);
tmp[4] = ((u64) in[0]) * (in[4] << 1) +
((u64) in[1]) * (in[3] << 2) +
((u64) in[2]) * in[2];
tmp[5] = ((u64) in[0]) * (in[5] << 1) +
((u64) in[1]) * (in[4] << 1) +
((u64) in[2]) * (in[3] << 1);
tmp[6] = ((u64) in[0]) * (in[6] << 1) +
((u64) in[1]) * (in[5] << 2) +
((u64) in[2]) * (in[4] << 1) +
((u64) in[3]) * (in[3] << 1);
tmp[7] = ((u64) in[0]) * (in[7] << 1) +
((u64) in[1]) * (in[6] << 1) +
((u64) in[2]) * (in[5] << 1) +
((u64) in[3]) * (in[4] << 1);
/* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60,
* which is < 2**64 as required.
*/
tmp[8] = ((u64) in[0]) * (in[8] << 1) +
((u64) in[1]) * (in[7] << 2) +
((u64) in[2]) * (in[6] << 1) +
((u64) in[3]) * (in[5] << 2) +
((u64) in[4]) * in[4];
tmp[9] = ((u64) in[1]) * (in[8] << 1) +
((u64) in[2]) * (in[7] << 1) +
((u64) in[3]) * (in[6] << 1) +
((u64) in[4]) * (in[5] << 1);
tmp[10] = ((u64) in[2]) * (in[8] << 1) +
((u64) in[3]) * (in[7] << 2) +
((u64) in[4]) * (in[6] << 1) +
((u64) in[5]) * (in[5] << 1);
tmp[11] = ((u64) in[3]) * (in[8] << 1) +
((u64) in[4]) * (in[7] << 1) +
((u64) in[5]) * (in[6] << 1);
tmp[12] = ((u64) in[4]) * (in[8] << 1) +
((u64) in[5]) * (in[7] << 2) +
((u64) in[6]) * in[6];
tmp[13] = ((u64) in[5]) * (in[8] << 1) +
((u64) in[6]) * (in[7] << 1);
tmp[14] = ((u64) in[6]) * (in[8] << 1) +
((u64) in[7]) * (in[7] << 1);
tmp[15] = ((u64) in[7]) * (in[8] << 1);
tmp[16] = ((u64) in[8]) * in[8];
felem_reduce_degree(out, tmp);
}
/* felem_mul sets out=in*in2.
*
* On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and
* in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_mul(felem out, const felem in, const felem in2)
{
u64 tmp[17];
tmp[0] = ((u64) in[0]) * in2[0];
tmp[1] = ((u64) in[0]) * (in2[1] << 0) +
((u64) in[1]) * (in2[0] << 0);
tmp[2] = ((u64) in[0]) * (in2[2] << 0) +
((u64) in[1]) * (in2[1] << 1) +
((u64) in[2]) * (in2[0] << 0);
tmp[3] = ((u64) in[0]) * (in2[3] << 0) +
((u64) in[1]) * (in2[2] << 0) +
((u64) in[2]) * (in2[1] << 0) +
((u64) in[3]) * (in2[0] << 0);
tmp[4] = ((u64) in[0]) * (in2[4] << 0) +
((u64) in[1]) * (in2[3] << 1) +
((u64) in[2]) * (in2[2] << 0) +
((u64) in[3]) * (in2[1] << 1) +
((u64) in[4]) * (in2[0] << 0);
tmp[5] = ((u64) in[0]) * (in2[5] << 0) +
((u64) in[1]) * (in2[4] << 0) +
((u64) in[2]) * (in2[3] << 0) +
((u64) in[3]) * (in2[2] << 0) +
((u64) in[4]) * (in2[1] << 0) +
((u64) in[5]) * (in2[0] << 0);
tmp[6] = ((u64) in[0]) * (in2[6] << 0) +
((u64) in[1]) * (in2[5] << 1) +
((u64) in[2]) * (in2[4] << 0) +
((u64) in[3]) * (in2[3] << 1) +
((u64) in[4]) * (in2[2] << 0) +
((u64) in[5]) * (in2[1] << 1) +
((u64) in[6]) * (in2[0] << 0);
tmp[7] = ((u64) in[0]) * (in2[7] << 0) +
((u64) in[1]) * (in2[6] << 0) +
((u64) in[2]) * (in2[5] << 0) +
((u64) in[3]) * (in2[4] << 0) +
((u64) in[4]) * (in2[3] << 0) +
((u64) in[5]) * (in2[2] << 0) +
((u64) in[6]) * (in2[1] << 0) +
((u64) in[7]) * (in2[0] << 0);
/* tmp[8] has the greatest value but doesn't overflow. See logic in
* felem_square.
*/
tmp[8] = ((u64) in[0]) * (in2[8] << 0) +
((u64) in[1]) * (in2[7] << 1) +
((u64) in[2]) * (in2[6] << 0) +
((u64) in[3]) * (in2[5] << 1) +
((u64) in[4]) * (in2[4] << 0) +
((u64) in[5]) * (in2[3] << 1) +
((u64) in[6]) * (in2[2] << 0) +
((u64) in[7]) * (in2[1] << 1) +
((u64) in[8]) * (in2[0] << 0);
tmp[9] = ((u64) in[1]) * (in2[8] << 0) +
((u64) in[2]) * (in2[7] << 0) +
((u64) in[3]) * (in2[6] << 0) +
((u64) in[4]) * (in2[5] << 0) +
((u64) in[5]) * (in2[4] << 0) +
((u64) in[6]) * (in2[3] << 0) +
((u64) in[7]) * (in2[2] << 0) +
((u64) in[8]) * (in2[1] << 0);
tmp[10] = ((u64) in[2]) * (in2[8] << 0) +
((u64) in[3]) * (in2[7] << 1) +
((u64) in[4]) * (in2[6] << 0) +
((u64) in[5]) * (in2[5] << 1) +
((u64) in[6]) * (in2[4] << 0) +
((u64) in[7]) * (in2[3] << 1) +
((u64) in[8]) * (in2[2] << 0);
tmp[11] = ((u64) in[3]) * (in2[8] << 0) +
((u64) in[4]) * (in2[7] << 0) +
((u64) in[5]) * (in2[6] << 0) +
((u64) in[6]) * (in2[5] << 0) +
((u64) in[7]) * (in2[4] << 0) +
((u64) in[8]) * (in2[3] << 0);
tmp[12] = ((u64) in[4]) * (in2[8] << 0) +
((u64) in[5]) * (in2[7] << 1) +
((u64) in[6]) * (in2[6] << 0) +
((u64) in[7]) * (in2[5] << 1) +
((u64) in[8]) * (in2[4] << 0);
tmp[13] = ((u64) in[5]) * (in2[8] << 0) +
((u64) in[6]) * (in2[7] << 0) +
((u64) in[7]) * (in2[6] << 0) +
((u64) in[8]) * (in2[5] << 0);
tmp[14] = ((u64) in[6]) * (in2[8] << 0) +
((u64) in[7]) * (in2[7] << 1) +
((u64) in[8]) * (in2[6] << 0);
tmp[15] = ((u64) in[7]) * (in2[8] << 0) +
((u64) in[8]) * (in2[7] << 0);
tmp[16] = ((u64) in[8]) * (in2[8] << 0);
felem_reduce_degree(out, tmp);
}
static void felem_assign(felem out, const felem in)
{
memcpy(out, in, sizeof(felem));
}
/* felem_inv calculates |out| = |in|^{-1}
*
* Based on Fermat's Little Theorem:
* a^p = a (mod p)
* a^{p-1} = 1 (mod p)
* a^{p-2} = a^{-1} (mod p)
*/
static void felem_inv(felem out, const felem in)
{
felem ftmp, ftmp2;
/* each e_I will hold |in|^{2^I - 1} */
felem e2, e4, e8, e16, e32, e64;
unsigned int i;
felem_square(ftmp, in); /* 2^1 */
felem_mul(ftmp, in, ftmp); /* 2^2 - 2^0 */
felem_assign(e2, ftmp);
felem_square(ftmp, ftmp); /* 2^3 - 2^1 */
felem_square(ftmp, ftmp); /* 2^4 - 2^2 */
felem_mul(ftmp, ftmp, e2); /* 2^4 - 2^0 */
felem_assign(e4, ftmp);
felem_square(ftmp, ftmp); /* 2^5 - 2^1 */
felem_square(ftmp, ftmp); /* 2^6 - 2^2 */
felem_square(ftmp, ftmp); /* 2^7 - 2^3 */
felem_square(ftmp, ftmp); /* 2^8 - 2^4 */
felem_mul(ftmp, ftmp, e4); /* 2^8 - 2^0 */
felem_assign(e8, ftmp);
for (i = 0; i < 8; i++) {
felem_square(ftmp, ftmp);
} /* 2^16 - 2^8 */
felem_mul(ftmp, ftmp, e8); /* 2^16 - 2^0 */
felem_assign(e16, ftmp);
for (i = 0; i < 16; i++) {
felem_square(ftmp, ftmp);
} /* 2^32 - 2^16 */
felem_mul(ftmp, ftmp, e16); /* 2^32 - 2^0 */
felem_assign(e32, ftmp);
for (i = 0; i < 32; i++) {
felem_square(ftmp, ftmp);
} /* 2^64 - 2^32 */
felem_assign(e64, ftmp);
felem_mul(ftmp, ftmp, in); /* 2^64 - 2^32 + 2^0 */
for (i = 0; i < 192; i++) {
felem_square(ftmp, ftmp);
} /* 2^256 - 2^224 + 2^192 */
felem_mul(ftmp2, e64, e32); /* 2^64 - 2^0 */
for (i = 0; i < 16; i++) {
felem_square(ftmp2, ftmp2);
} /* 2^80 - 2^16 */
felem_mul(ftmp2, ftmp2, e16); /* 2^80 - 2^0 */
for (i = 0; i < 8; i++) {
felem_square(ftmp2, ftmp2);
} /* 2^88 - 2^8 */
felem_mul(ftmp2, ftmp2, e8); /* 2^88 - 2^0 */
for (i = 0; i < 4; i++) {
felem_square(ftmp2, ftmp2);
} /* 2^92 - 2^4 */
felem_mul(ftmp2, ftmp2, e4); /* 2^92 - 2^0 */
felem_square(ftmp2, ftmp2); /* 2^93 - 2^1 */
felem_square(ftmp2, ftmp2); /* 2^94 - 2^2 */
felem_mul(ftmp2, ftmp2, e2); /* 2^94 - 2^0 */
felem_square(ftmp2, ftmp2); /* 2^95 - 2^1 */
felem_square(ftmp2, ftmp2); /* 2^96 - 2^2 */
felem_mul(ftmp2, ftmp2, in); /* 2^96 - 3 */
felem_mul(out, ftmp2, ftmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */
}
/* felem_scalar_3 sets out=3*out.
*
* On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_scalar_3(felem out)
{
limb carry = 0;
unsigned int i;
for (i = 0;; i++) {
out[i] *= 3;
out[i] += carry;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
out[i] *= 3;
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* felem_scalar_4 sets out=4*out.
*
* On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_scalar_4(felem out)
{
limb carry = 0, next_carry;
unsigned int i;
for (i = 0;; i++) {
next_carry = out[i] >> 27;
out[i] <<= 2;
out[i] &= kBottom29Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 29);
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
next_carry = out[i] >> 26;
out[i] <<= 2;
out[i] &= kBottom28Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 28);
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* felem_scalar_8 sets out=8*out.
*
* On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_scalar_8(felem out)
{
limb carry = 0, next_carry;
unsigned int i;
for (i = 0;; i++) {
next_carry = out[i] >> 26;
out[i] <<= 3;
out[i] &= kBottom29Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 29);
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
next_carry = out[i] >> 25;
out[i] <<= 3;
out[i] &= kBottom28Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 28);
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of
* time depending on the value of |in|.
*/
static char felem_is_zero_vartime(const felem in)
{
limb carry;
int i;
limb tmp[NLIMBS];
felem_assign(tmp, in);
/* First, reduce tmp to a minimal form.
*/
do {
carry = 0;
for (i = 0;; i++) {
tmp[i] += carry;
carry = tmp[i] >> 29;
tmp[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
tmp[i] += carry;
carry = tmp[i] >> 28;
tmp[i] &= kBottom28Bits;
}
felem_reduce_carry(tmp, carry);
} while (carry);
/* tmp < 2**257, so the only possible zero values are 0, p and 2p.
*/
return memcmp(tmp, kZero, sizeof(tmp)) == 0 ||
memcmp(tmp, kP, sizeof(tmp)) == 0 ||
memcmp(tmp, k2P, sizeof(tmp)) == 0;
}
/* Group operations:
*
* Elements of the elliptic curve group are represented in Jacobian
* coordinates: (x, y, z). An affine point (x', y') is x'=x/z**2, y'=y/z**3 in
* Jacobian form.
*/
/* point_double sets {x_out,y_out,z_out} = 2*{x,y,z}.
*
* See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
*/
static void point_double(felem x_out, felem y_out, felem z_out,
const felem x, const felem y, const felem z)
{
felem delta, gamma, alpha, beta, tmp, tmp2;
felem_square(delta, z);
felem_square(gamma, y);
felem_mul(beta, x, gamma);
felem_sum(tmp, x, delta);
felem_diff(tmp2, x, delta);
felem_mul(alpha, tmp, tmp2);
felem_scalar_3(alpha);
felem_sum(tmp, y, z);
felem_square(tmp, tmp);
felem_diff(tmp, tmp, gamma);
felem_diff(z_out, tmp, delta);
felem_scalar_4(beta);
felem_square(x_out, alpha);
felem_diff(x_out, x_out, beta);
felem_diff(x_out, x_out, beta);
felem_diff(tmp, beta, x_out);
felem_mul(tmp, alpha, tmp);
felem_square(tmp2, gamma);
felem_scalar_8(tmp2);
felem_diff(y_out, tmp, tmp2);
}
/* point_add_mixed sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,1}.
* (i.e. the second point is affine.)
*
* See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
*
* Note that this function does not handle P+P, infinity+P nor P+infinity
* correctly.
*/
static void point_add_mixed(felem x_out, felem y_out, felem z_out,
const felem x1, const felem y1, const felem z1,
const felem x2, const felem y2)
{
felem z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp;
felem_square(z1z1, z1);
felem_sum(tmp, z1, z1);
felem_mul(u2, x2, z1z1);
felem_mul(z1z1z1, z1, z1z1);
felem_mul(s2, y2, z1z1z1);
felem_diff(h, u2, x1);
felem_sum(i, h, h);
felem_square(i, i);
felem_mul(j, h, i);
felem_diff(r, s2, y1);
felem_sum(r, r, r);
felem_mul(v, x1, i);
felem_mul(z_out, tmp, h);
felem_square(rr, r);
felem_diff(x_out, rr, j);
felem_diff(x_out, x_out, v);
felem_diff(x_out, x_out, v);
felem_diff(tmp, v, x_out);
felem_mul(y_out, tmp, r);
felem_mul(tmp, y1, j);
felem_diff(y_out, y_out, tmp);
felem_diff(y_out, y_out, tmp);
}
/* point_add sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,z2}.
*
* See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
*
* Note that this function does not handle P+P, infinity+P nor P+infinity
* correctly.
*/
static void point_add(felem x_out, felem y_out, felem z_out,
const felem x1, const felem y1, const felem z1,
const felem x2, const felem y2, const felem z2)
{
felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;
felem_square(z1z1, z1);
felem_square(z2z2, z2);
felem_mul(u1, x1, z2z2);
felem_sum(tmp, z1, z2);
felem_square(tmp, tmp);
felem_diff(tmp, tmp, z1z1);
felem_diff(tmp, tmp, z2z2);
felem_mul(z2z2z2, z2, z2z2);
felem_mul(s1, y1, z2z2z2);
felem_mul(u2, x2, z1z1);
felem_mul(z1z1z1, z1, z1z1);
felem_mul(s2, y2, z1z1z1);
felem_diff(h, u2, u1);
felem_sum(i, h, h);
felem_square(i, i);
felem_mul(j, h, i);
felem_diff(r, s2, s1);
felem_sum(r, r, r);
felem_mul(v, u1, i);
felem_mul(z_out, tmp, h);
felem_square(rr, r);
felem_diff(x_out, rr, j);
felem_diff(x_out, x_out, v);
felem_diff(x_out, x_out, v);
felem_diff(tmp, v, x_out);
felem_mul(y_out, tmp, r);
felem_mul(tmp, s1, j);
felem_diff(y_out, y_out, tmp);
felem_diff(y_out, y_out, tmp);
}
/* point_add_or_double_vartime sets {x_out,y_out,z_out} = {x1,y1,z1} +
* {x2,y2,z2}.
*
* See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
*
* This function handles the case where {x1,y1,z1}={x2,y2,z2}.
*/
static void point_add_or_double_vartime(
felem x_out, felem y_out, felem z_out,
const felem x1, const felem y1, const felem z1,
const felem x2, const felem y2, const felem z2)
{
felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;
char x_equal, y_equal;
felem_square(z1z1, z1);
felem_square(z2z2, z2);
felem_mul(u1, x1, z2z2);
felem_sum(tmp, z1, z2);
felem_square(tmp, tmp);
felem_diff(tmp, tmp, z1z1);
felem_diff(tmp, tmp, z2z2);
felem_mul(z2z2z2, z2, z2z2);
felem_mul(s1, y1, z2z2z2);
felem_mul(u2, x2, z1z1);
felem_mul(z1z1z1, z1, z1z1);
felem_mul(s2, y2, z1z1z1);
felem_diff(h, u2, u1);
x_equal = felem_is_zero_vartime(h);
felem_sum(i, h, h);
felem_square(i, i);
felem_mul(j, h, i);
felem_diff(r, s2, s1);
y_equal = felem_is_zero_vartime(r);
if (x_equal && y_equal) {
point_double(x_out, y_out, z_out, x1, y1, z1);
return;
}
felem_sum(r, r, r);
felem_mul(v, u1, i);
felem_mul(z_out, tmp, h);
felem_square(rr, r);
felem_diff(x_out, rr, j);
felem_diff(x_out, x_out, v);
felem_diff(x_out, x_out, v);
felem_diff(tmp, v, x_out);
felem_mul(y_out, tmp, r);
felem_mul(tmp, s1, j);
felem_diff(y_out, y_out, tmp);
felem_diff(y_out, y_out, tmp);
}
/* copy_conditional sets out=in if mask = 0xffffffff in constant time.
*
* On entry: mask is either 0 or 0xffffffff.
*/
static void copy_conditional(felem out, const felem in, limb mask)
{
int i;
for (i = 0; i < NLIMBS; i++) {
const limb tmp = mask & (in[i] ^ out[i]);
out[i] ^= tmp;
}
}
/* select_affine_point sets {out_x,out_y} to the index'th entry of table.
* On entry: index < 16, table[0] must be zero.
*/
static void select_affine_point(felem out_x, felem out_y,
const limb *table, limb index)
{
limb i, j;
memset(out_x, 0, sizeof(felem));
memset(out_y, 0, sizeof(felem));
for (i = 1; i < 16; i++) {
limb mask = i ^ index;
mask |= mask >> 2;
mask |= mask >> 1;
mask &= 1;
mask--;
for (j = 0; j < NLIMBS; j++, table++) {
out_x[j] |= *table & mask;
}
for (j = 0; j < NLIMBS; j++, table++) {
out_y[j] |= *table & mask;
}
}
}
/* select_jacobian_point sets {out_x,out_y,out_z} to the index'th entry of
* table. On entry: index < 16, table[0] must be zero.
*/
static void select_jacobian_point(felem out_x, felem out_y, felem out_z,
const limb *table, limb index)
{
limb i, j;
memset(out_x, 0, sizeof(felem));
memset(out_y, 0, sizeof(felem));
memset(out_z, 0, sizeof(felem));
/* The implicit value at index 0 is all zero. We don't need to perform that
* iteration of the loop because we already set out_* to zero.
*/
table += 3*NLIMBS;
for (i = 1; i < 16; i++) {
limb mask = i ^ index;
mask |= mask >> 2;
mask |= mask >> 1;
mask &= 1;
mask--;
for (j = 0; j < NLIMBS; j++, table++) {
out_x[j] |= *table & mask;
}
for (j = 0; j < NLIMBS; j++, table++) {
out_y[j] |= *table & mask;
}
for (j = 0; j < NLIMBS; j++, table++) {
out_z[j] |= *table & mask;
}
}
}
/* get_bit returns the bit'th bit of scalar. */
static char get_bit(const u8 scalar[32], int bit)
{
return ((scalar[bit >> 3]) >> (bit & 7)) & 1;
}
/* scalar_base_mult sets {nx,ny,nz} = scalar*G where scalar is a little-endian
* number. Note that the value of scalar must be less than the order of the
* group.
*/
static void scalar_base_mult(felem nx, felem ny, felem nz, const u8 scalar[32])
{
int i, j;
limb n_is_infinity_mask = -1, p_is_noninfinite_mask, mask;
u32 table_offset;
felem px, py;
felem tx, ty, tz;
memset(nx, 0, sizeof(felem));
memset(ny, 0, sizeof(felem));
memset(nz, 0, sizeof(felem));
/* The loop adds bits at positions 0, 64, 128 and 192, followed by
* positions 32,96,160 and 224 and does this 32 times.
*/
for (i = 0; i < 32; i++) {
if (i) {
point_double(nx, ny, nz, nx, ny, nz);
}
table_offset = 0;
for (j = 0; j <= 32; j += 32) {
char bit0 = get_bit(scalar, 31 - i + j);
char bit1 = get_bit(scalar, 95 - i + j);
char bit2 = get_bit(scalar, 159 - i + j);
char bit3 = get_bit(scalar, 223 - i + j);
limb index = bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3);
select_affine_point(px, py, kPrecomputed + table_offset, index);
table_offset += 30 * NLIMBS;
/* Since scalar is less than the order of the group, we know that
* {nx,ny,nz} != {px,py,1}, unless both are zero, which we handle
* below.
*/
point_add_mixed(tx, ty, tz, nx, ny, nz, px, py);
/* The result of point_add_mixed is incorrect if {nx,ny,nz} is zero
* (a.k.a. the point at infinity). We handle that situation by
* copying the point from the table.
*/
copy_conditional(nx, px, n_is_infinity_mask);
copy_conditional(ny, py, n_is_infinity_mask);
copy_conditional(nz, kOne, n_is_infinity_mask);
/* Equally, the result is also wrong if the point from the table is
* zero, which happens when the index is zero. We handle that by
* only copying from {tx,ty,tz} to {nx,ny,nz} if index != 0.
*/
p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index);
mask = p_is_noninfinite_mask & ~n_is_infinity_mask;
copy_conditional(nx, tx, mask);
copy_conditional(ny, ty, mask);
copy_conditional(nz, tz, mask);
/* If p was not zero, then n is now non-zero. */
n_is_infinity_mask &= ~p_is_noninfinite_mask;
}
}
}
/* point_to_affine converts a Jacobian point to an affine point. If the input
* is the point at infinity then it returns (0, 0) in constant time.
*/
static void point_to_affine(felem x_out, felem y_out,
const felem nx, const felem ny, const felem nz) {
felem z_inv, z_inv_sq;
felem_inv(z_inv, nz);
felem_square(z_inv_sq, z_inv);
felem_mul(x_out, nx, z_inv_sq);
felem_mul(z_inv, z_inv, z_inv_sq);
felem_mul(y_out, ny, z_inv);
}
/* scalar_mult sets {nx,ny,nz} = scalar*{x,y}. */
static void scalar_mult(felem nx, felem ny, felem nz,
const felem x, const felem y, const u8 scalar[32])
{
int i;
felem px, py, pz, tx, ty, tz;
felem precomp[16][3];
limb n_is_infinity_mask, index, p_is_noninfinite_mask, mask;
/* We precompute 0,1,2,... times {x,y}. */
memset(precomp, 0, sizeof(felem) * 3);
memcpy(&precomp[1][0], x, sizeof(felem));
memcpy(&precomp[1][1], y, sizeof(felem));
memcpy(&precomp[1][2], kOne, sizeof(felem));
for (i = 2; i < 16; i += 2) {
point_double(precomp[i][0], precomp[i][1], precomp[i][2],
precomp[i / 2][0], precomp[i / 2][1], precomp[i / 2][2]);
point_add_mixed(precomp[i + 1][0], precomp[i + 1][1], precomp[i + 1][2],
precomp[i][0], precomp[i][1], precomp[i][2], x, y);
}
memset(nx, 0, sizeof(felem));
memset(ny, 0, sizeof(felem));
memset(nz, 0, sizeof(felem));
n_is_infinity_mask = -1;
/* We add in a window of four bits each iteration and do this 64 times. */
for (i = 0; i < 64; i++) {
if (i) {
point_double(nx, ny, nz, nx, ny, nz);
point_double(nx, ny, nz, nx, ny, nz);
point_double(nx, ny, nz, nx, ny, nz);
point_double(nx, ny, nz, nx, ny, nz);
}
index = scalar[31 - i / 2];
if ((i & 1) == 1) {
index &= 15;
} else {
index >>= 4;
}
/* See the comments in scalar_base_mult about handling infinities. */
select_jacobian_point(px, py, pz, precomp[0][0], index);
point_add(tx, ty, tz, nx, ny, nz, px, py, pz);
copy_conditional(nx, px, n_is_infinity_mask);
copy_conditional(ny, py, n_is_infinity_mask);
copy_conditional(nz, pz, n_is_infinity_mask);
p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index);
mask = p_is_noninfinite_mask & ~n_is_infinity_mask;
copy_conditional(nx, tx, mask);
copy_conditional(ny, ty, mask);
copy_conditional(nz, tz, mask);
n_is_infinity_mask &= ~p_is_noninfinite_mask;
}
}
/* Interface with Freebl: */
/* BYTESWAP_MP_DIGIT_TO_LE swaps the bytes of a mp_digit to
* little-endian order.
*/
#ifdef IS_BIG_ENDIAN
#ifdef __APPLE__
#include <libkern/OSByteOrder.h>
#define BYTESWAP32(x) OSSwapInt32(x)
#define BYTESWAP64(x) OSSwapInt64(x)
#else
#define BYTESWAP32(x) \
(((x) >> 24) | (((x) >> 8) & 0xff00) | (((x) & 0xff00) << 8) | ((x) << 24))
#define BYTESWAP64(x) \
(((x) >> 56) | (((x) >> 40) & 0xff00) | \
(((x) >> 24) & 0xff0000) | (((x) >> 8) & 0xff000000) | \
(((x) & 0xff000000) << 8) | (((x) & 0xff0000) << 24) | \
(((x) & 0xff00) << 40) | ((x) << 56))
#endif
#ifdef MP_USE_UINT_DIGIT
#define BYTESWAP_MP_DIGIT_TO_LE(x) BYTESWAP32(x)
#else
#define BYTESWAP_MP_DIGIT_TO_LE(x) BYTESWAP64(x)
#endif
#endif /* IS_BIG_ENDIAN */
#ifdef MP_USE_UINT_DIGIT
static const mp_digit kRInvDigits[8] = {
0x80000000, 1, 0xffffffff, 0,
0x80000001, 0xfffffffe, 1, 0x7fffffff
};
#else
static const mp_digit kRInvDigits[4] = {
PR_UINT64(0x180000000), 0xffffffff,
PR_UINT64(0xfffffffe80000001), PR_UINT64(0x7fffffff00000001)
};
#endif
#define MP_DIGITS_IN_256_BITS (32/sizeof(mp_digit))
static const mp_int kRInv = {
MP_ZPOS,
MP_DIGITS_IN_256_BITS,
MP_DIGITS_IN_256_BITS,
(mp_digit*) kRInvDigits
};
static const limb kTwo28 = 0x10000000;
static const limb kTwo29 = 0x20000000;
/* to_montgomery sets out = R*in. */
static mp_err to_montgomery(felem out, const mp_int *in, const ECGroup *group)
{
/* There are no MPI functions for bitshift operations and we wish to shift
* in 257 bits left so we move the digits 256-bits left and then multiply
* by two.
*/
mp_int in_shifted;
int i;
mp_err res;
mp_init(&in_shifted);
s_mp_pad(&in_shifted, MP_USED(in) + MP_DIGITS_IN_256_BITS);
memcpy(&MP_DIGIT(&in_shifted, MP_DIGITS_IN_256_BITS),
MP_DIGITS(in),
MP_USED(in)*sizeof(mp_digit));
mp_mul_2(&in_shifted, &in_shifted);
MP_CHECKOK(group->meth->field_mod(&in_shifted, &in_shifted, group->meth));
for (i = 0;; i++) {
out[i] = MP_DIGIT(&in_shifted, 0) & kBottom29Bits;
mp_div_d(&in_shifted, kTwo29, &in_shifted, NULL);
i++;
if (i == NLIMBS)
break;
out[i] = MP_DIGIT(&in_shifted, 0) & kBottom28Bits;
mp_div_d(&in_shifted, kTwo28, &in_shifted, NULL);
}
CLEANUP:
mp_clear(&in_shifted);
return res;
}
/* from_montgomery sets out=in/R. */
static mp_err from_montgomery(mp_int *out, const felem in,
const ECGroup *group)
{
mp_int result, tmp;
mp_err res;
int i;
mp_init(&result);
mp_init(&tmp);
MP_CHECKOK(mp_add_d(&tmp, in[NLIMBS-1], &result));
for (i = NLIMBS-2; i >= 0; i--) {
if ((i & 1) == 0) {
MP_CHECKOK(mp_mul_d(&result, kTwo29, &tmp));
} else {
MP_CHECKOK(mp_mul_d(&result, kTwo28, &tmp));
}
MP_CHECKOK(mp_add_d(&tmp, in[i], &result));
}
MP_CHECKOK(mp_mul(&result, &kRInv, out));
MP_CHECKOK(group->meth->field_mod(out, out, group->meth));
CLEANUP:
mp_clear(&result);
mp_clear(&tmp);
return res;
}
/* scalar_from_mp_int sets out_scalar=n, where n < the group order. */
static void scalar_from_mp_int(u8 out_scalar[32], const mp_int *n)
{
/* We require that |n| is less than the order of the group and therefore it
* will fit into |out_scalar|. However, these is a timing side-channel here
* that we cannot avoid: if |n| is sufficiently small it may be one or more
* words too short and we'll copy less data.
*/
memset(out_scalar, 0, 32);
#ifdef IS_LITTLE_ENDIAN
memcpy(out_scalar, MP_DIGITS(n), MP_USED(n) * sizeof(mp_digit));
#else
{
mp_size i;
mp_digit swapped[MP_DIGITS_IN_256_BITS];
for (i = 0; i < MP_USED(n); i++) {
swapped[i] = BYTESWAP_MP_DIGIT_TO_LE(MP_DIGIT(n, i));
}
memcpy(out_scalar, swapped, MP_USED(n) * sizeof(mp_digit));
}
#endif
}
/* ec_GFp_nistp256_base_point_mul sets {out_x,out_y} = nG, where n is < the
* order of the group.
*/
static mp_err ec_GFp_nistp256_base_point_mul(const mp_int *n,
mp_int *out_x, mp_int *out_y,
const ECGroup *group)
{
u8 scalar[32];
felem x, y, z, x_affine, y_affine;
mp_err res;
/* FIXME(agl): test that n < order. */
scalar_from_mp_int(scalar, n);
scalar_base_mult(x, y, z, scalar);
point_to_affine(x_affine, y_affine, x, y, z);
MP_CHECKOK(from_montgomery(out_x, x_affine, group));
MP_CHECKOK(from_montgomery(out_y, y_affine, group));
CLEANUP:
return res;
}
/* ec_GFp_nistp256_point_mul sets {out_x,out_y} = n*{in_x,in_y}, where n is <
* the order of the group.
*/
static mp_err ec_GFp_nistp256_point_mul(const mp_int *n,
const mp_int *in_x, const mp_int *in_y,
mp_int *out_x, mp_int *out_y,
const ECGroup *group)
{
u8 scalar[32];
felem x, y, z, x_affine, y_affine, px, py;
mp_err res;
scalar_from_mp_int(scalar, n);
MP_CHECKOK(to_montgomery(px, in_x, group));
MP_CHECKOK(to_montgomery(py, in_y, group));
scalar_mult(x, y, z, px, py, scalar);
point_to_affine(x_affine, y_affine, x, y, z);
MP_CHECKOK(from_montgomery(out_x, x_affine, group));
MP_CHECKOK(from_montgomery(out_y, y_affine, group));
CLEANUP:
return res;
}
/* ec_GFp_nistp256_point_mul_vartime sets {out_x,out_y} = n1*G +
* n2*{in_x,in_y}, where n1 and n2 are < the order of the group.
*
* As indicated by the name, this function operates in variable time. This
* is safe because it's used for signature validation which doesn't deal
* with secrets.
*/
static mp_err ec_GFp_nistp256_points_mul_vartime(
const mp_int *n1, const mp_int *n2,
const mp_int *in_x, const mp_int *in_y,
mp_int *out_x, mp_int *out_y,
const ECGroup *group)
{
u8 scalar1[32], scalar2[32];
felem x1, y1, z1, x2, y2, z2, x_affine, y_affine, px, py;
mp_err res = MP_OKAY;
/* If n2 == NULL, this is just a base-point multiplication. */
if (n2 == NULL) {
return ec_GFp_nistp256_base_point_mul(n1, out_x, out_y, group);
}
/* If n1 == nULL, this is just an arbitary-point multiplication. */
if (n1 == NULL) {
return ec_GFp_nistp256_point_mul(n2, in_x, in_y, out_x, out_y, group);
}
/* If both scalars are zero, then the result is the point at infinity. */
if (mp_cmp_z(n1) == 0 && mp_cmp_z(n2) == 0) {
mp_zero(out_x);
mp_zero(out_y);
return res;
}
scalar_from_mp_int(scalar1, n1);
scalar_from_mp_int(scalar2, n2);
MP_CHECKOK(to_montgomery(px, in_x, group));
MP_CHECKOK(to_montgomery(py, in_y, group));
scalar_base_mult(x1, y1, z1, scalar1);
scalar_mult(x2, y2, z2, px, py, scalar2);
if (mp_cmp_z(n2) == 0) {
/* If n2 == 0, then {x2,y2,z2} is zero and the result is just
* {x1,y1,z1}. */
} else if (mp_cmp_z(n1) == 0) {
/* If n1 == 0, then {x1,y1,z1} is zero and the result is just
* {x2,y2,z2}. */
memcpy(x1, x2, sizeof(x2));
memcpy(y1, y2, sizeof(y2));
memcpy(z1, z2, sizeof(z2));
} else {
/* This function handles the case where {x1,y1,z1} == {x2,y2,z2}. */
point_add_or_double_vartime(x1, y1, z1, x1, y1, z1, x2, y2, z2);
}
point_to_affine(x_affine, y_affine, x1, y1, z1);
MP_CHECKOK(from_montgomery(out_x, x_affine, group));
MP_CHECKOK(from_montgomery(out_y, y_affine, group));
CLEANUP:
return res;
}
/* Wire in fast point multiplication for named curves. */
mp_err ec_group_set_gfp256_32(ECGroup *group, ECCurveName name)
{
if (name == ECCurve_NIST_P256) {
group->base_point_mul = &ec_GFp_nistp256_base_point_mul;
group->point_mul = &ec_GFp_nistp256_point_mul;
group->points_mul = &ec_GFp_nistp256_points_mul_vartime;
}
return MP_OKAY;
}
| Java |
namespace Infrastructure.DataAccess.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class usersupervisioninfoaddedtosysusage : DbMigration
{
public override void Up()
{
AddColumn("dbo.ItSystemUsage", "UserSupervisionDate", c => c.DateTime(nullable: false, precision: 7, storeType: "datetime2"));
AddColumn("dbo.ItSystemUsage", "UserSupervision", c => c.Int(nullable: false));
}
public override void Down()
{
DropColumn("dbo.ItSystemUsage", "UserSupervision");
DropColumn("dbo.ItSystemUsage", "UserSupervisionDate");
}
}
}
| Java |
/*
* Copyright © 2013-2020, The SeedStack authors <http://seedstack.org>
*
* 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/.
*/
package org.seedstack.i18n.rest.internal.infrastructure.csv;
import com.google.common.collect.Sets;
import org.seedstack.i18n.rest.internal.locale.LocaleFinder;
import org.seedstack.i18n.rest.internal.locale.LocaleRepresentation;
import org.seedstack.io.spi.Template;
import org.seedstack.io.spi.TemplateLoader;
import org.seedstack.io.supercsv.Column;
import org.seedstack.io.supercsv.SuperCsvTemplate;
import org.seedstack.jpa.JpaUnit;
import org.seedstack.seed.transaction.Transactional;
import org.supercsv.cellprocessor.Optional;
import javax.inject.Inject;
import java.util.List;
import java.util.Set;
/**
* @author [email protected]
*/
public class I18nCSVTemplateLoader implements TemplateLoader {
public static final String I18N_CSV_TEMPLATE = "i18nTranslations";
public static final String KEY = "key";
@Inject
private LocaleFinder localeFinder;
@JpaUnit("seed-i18n-domain")
@Transactional
@Override
public Template load(String name) {
List<LocaleRepresentation> availableLocales = localeFinder.findAvailableLocales();
SuperCsvTemplate superCsvTemplate = new SuperCsvTemplate(name);
superCsvTemplate.addColumn(new Column(KEY, KEY, new Optional(), new Optional()));
for (LocaleRepresentation availableLocale : availableLocales) {
superCsvTemplate.addColumn(new Column(availableLocale.getCode(), availableLocale.getCode(), new Optional(), new Optional()));
}
return superCsvTemplate;
}
@Override
public Set<String> names() {
return Sets.newHashSet(I18N_CSV_TEMPLATE);
}
@Override
public boolean contains(String name) {
return names().contains(name);
}
@Override
public String templateRenderer() {
return I18nCSVRenderer.I18N_RENDERER;
}
@Override
public String templateParser() {
return CSVParser.I18N_PARSER;
}
}
| Java |
<?php
declare(strict_types=1);
/*
* 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/.
*/
namespace ParkManager\Application\Command\User;
use Rollerworks\Component\SplitToken\SplitToken;
final class ConfirmPasswordReset
{
/**
* @param string $password The password in hashed format
*/
public function __construct(public SplitToken $token, public string $password)
{
}
}
| Java |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingPlatform : MonoBehaviour {
public float moveSpeed;
private float moveForce;
public float limit;
public bool vertical;
public bool movingPlus;
public Vector3 startPos;
Rigidbody2D rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
startPos = transform.position;
}
// Update is called once per frame
void Update () {
if (vertical == false) {
rb.velocity = new Vector2 (moveForce, rb.velocity.y);
} else {
rb.velocity = new Vector2 (rb.velocity.x, moveForce);
}
if (vertical == false) {
if (transform.localPosition.x >= startPos.x + limit) {
movingPlus = false;
}
if (transform.localPosition.x <= startPos.x - limit) {
movingPlus = true;
}
} else {
if (transform.localPosition.y >= startPos.y + limit) {
movingPlus = false;
}
if (transform.localPosition.y <= startPos.y - limit) {
movingPlus = true;
}
}
if (movingPlus == true)
{
moveForce = moveSpeed;
}
if (movingPlus == false)
{
moveForce = moveSpeed * -1;
}
}
}
| Java |
/* 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/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(env)]
#![feature(hash)]
#![feature(int_uint)]
#![feature(io)]
#![feature(optin_builtin_traits)]
#![feature(path)]
#![feature(plugin)]
#![feature(rustc_private)]
#![feature(std_misc)]
#![feature(unicode)]
#![feature(unsafe_destructor)]
#![allow(missing_copy_implementations)]
#[macro_use] extern crate log;
extern crate alloc;
#[macro_use] extern crate bitflags;
extern crate collections;
extern crate cssparser;
extern crate geom;
extern crate getopts;
extern crate layers;
extern crate libc;
#[no_link] #[macro_use] extern crate cssparser;
extern crate rand;
#[cfg(target_os="linux")]
extern crate regex;
extern crate "rustc-serialize" as rustc_serialize;
#[cfg(target_os="macos")]
extern crate task_info;
extern crate "time" as std_time;
extern crate text_writer;
extern crate selectors;
extern crate string_cache;
extern crate unicode;
extern crate url;
#[no_link] #[macro_use] #[plugin]
extern crate string_cache_macros;
extern crate lazy_static;
pub use selectors::smallvec;
use std::sync::Arc;
pub mod cache;
pub mod cursor;
pub mod debug_utils;
pub mod deque;
pub mod dlist;
pub mod fnv;
pub mod geometry;
pub mod logical_geometry;
pub mod memory;
pub mod namespace;
pub mod opts;
pub mod persistent_list;
pub mod range;
pub mod resource_files;
pub mod str;
pub mod task;
pub mod tid;
pub mod time;
pub mod taskpool;
pub mod task_state;
pub mod vec;
pub mod workqueue;
pub fn breakpoint() {
unsafe { ::std::intrinsics::breakpoint() };
}
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| Java |
import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def abstract_serial_server():
return AbstractSerialServer()
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def test_abract_serial_server_shutdown(abstract_serial_server):
assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True
| Java |
-- new sessions stored procedure
CREATE PROCEDURE `sessions_1` (
IN `uidArg` BINARY(16)
)
BEGIN
SELECT
tokenId,
uid,
createdAt,
uaBrowser,
uaBrowserVersion,
uaOS,
uaOSVersion,
uaDeviceType,
lastAccessTime
FROM sessionTokens
WHERE uid = uidArg;
END;
-- Schema patch-level increment.
UPDATE dbMetadata SET value = '17' WHERE name = 'schema-patch-level';
| Java |
// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "bvh4_factory.h"
#include "../bvh/bvh.h"
#include "../geometry/bezier1v.h"
#include "../geometry/bezier1i.h"
#include "../geometry/linei.h"
#include "../geometry/triangle.h"
#include "../geometry/trianglev.h"
#include "../geometry/trianglev_mb.h"
#include "../geometry/trianglei.h"
#include "../geometry/quadv.h"
#include "../geometry/quadi.h"
#include "../geometry/quadi_mb.h"
#include "../geometry/subdivpatch1cached.h"
#include "../geometry/object.h"
#include "../../common/accelinstance.h"
namespace embree
{
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iMBIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1_OBB);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1_OBB);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iMBIntersector1_OBB);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4Intersector1Moeller);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4XfmTriangle4Intersector1Moeller);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle8Intersector1Moeller);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vIntersector1Pluecker);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4iIntersector1Pluecker);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vMBIntersector1Moeller);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Subdivpatch1CachedIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4GridAOSIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualMBIntersector1);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4vIntersector1Moeller);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iIntersector1Pluecker);
DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iMBIntersector1Pluecker);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iIntersector4);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iMBIntersector4);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iMBIntersector4Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vIntersector4HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4iIntersector4HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vMBIntersector4HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iIntersector4HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iMBIntersector4HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4Subdivpatch1CachedIntersector4);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4GridAOSIntersector4);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualIntersector4Chunk);
DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualMBIntersector4Chunk);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iIntersector8);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iMBIntersector8);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iMBIntersector8Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vIntersector8HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4iIntersector8HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vMBIntersector8HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iIntersector8HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iMBIntersector8HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4Subdivpatch1CachedIntersector8);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4GridAOSIntersector8);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualIntersector8Chunk);
DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualMBIntersector8Chunk);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iIntersector16);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iMBIntersector16);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iMBIntersector16Single_OBB);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vIntersector16HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4iIntersector16HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vMBIntersector16HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoeller);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoellerNoFilter);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iIntersector16HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iMBIntersector16HybridPluecker);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4Subdivpatch1CachedIntersector16);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4GridAOSIntersector16);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualIntersector16Chunk);
DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualMBIntersector16Chunk);
DECLARE_BUILDER2(void,Scene,const createLineSegmentsAccelTy,BVH4BuilderTwoLevelLineSegmentsSAH);
DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderTwoLevelTriangleMeshSAH);
DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderInstancingTriangleMeshSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vBuilder_OBB_New);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iBuilder_OBB_New);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iMBBuilder_OBB_New);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vMBSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4vSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iMBSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSpatialSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSpatialSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSpatialSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSpatialSAH);
DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshBuilderSAH);
DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMBMeshBuilderSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderSAH);
DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4vMeshBuilderSAH);
DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMeshBuilderSAH);
DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMBMeshBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iMBSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualMBSceneBuilderSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivPatch1CachedBuilderBinnedSAH);
DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivGridEagerBuilderBinnedSAH);
DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshRefitSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshRefitSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshRefitSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshRefitSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshRefitSAH);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderMortonGeneral);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderMortonGeneral);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderMortonGeneral);
DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderMortonGeneral);
BVH4Factory::BVH4Factory (int features)
{
/* select builders */
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelLineSegmentsSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelTriangleMeshSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderInstancingTriangleMeshSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vBuilder_OBB_New);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iBuilder_OBB_New);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iMBBuilder_OBB_New);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSAH);
SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMBSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4vSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4iSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSpatialSAH);
SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSpatialSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSpatialSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSpatialSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderSAH);
SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4vMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBMeshBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMBSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualMBSceneBuilderSAH);
SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4SubdivPatch1CachedBuilderBinnedSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4SubdivGridEagerBuilderBinnedSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshRefitSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshRefitSAH);
SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshRefitSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshRefitSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshRefitSAH);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderMortonGeneral);
SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderMortonGeneral);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderMortonGeneral);
SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderMortonGeneral);
/* select intersectors1 */
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iIntersector1);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iMBIntersector1);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iMBIntersector1_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4Triangle4Intersector1Moeller);
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4XfmTriangle4Intersector1Moeller);
SELECT_SYMBOL_INIT_AVX_AVX2 (features,BVH4Triangle8Intersector1Moeller);
SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4vIntersector1Pluecker);
SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4iIntersector1Pluecker);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector1Moeller);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector1);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4GridAOSIntersector1);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector1);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector1);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector1Moeller);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iIntersector1Pluecker);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iMBIntersector1Pluecker);
#if defined (RTCORE_RAY_PACKETS)
/* select intersectors4 */
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iIntersector4);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iMBIntersector4);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single_OBB);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iMBIntersector4Single_OBB);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoeller);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoellerNoFilter);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoeller);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoellerNoFilter);
SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4vIntersector4HybridPluecker);
SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4iIntersector4HybridPluecker);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector4HybridMoeller);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller);
SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoellerNoFilter);
SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iIntersector4HybridPluecker);
SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iMBIntersector4HybridPluecker);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector4);
SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4GridAOSIntersector4);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector4Chunk);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector4Chunk);
SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller);
/* select intersectors8 */
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iIntersector8);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iMBIntersector8);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single_OBB);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single_OBB);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iMBIntersector8Single_OBB);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoeller);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoellerNoFilter);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoeller);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoellerNoFilter);
SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4vIntersector8HybridPluecker);
SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4iIntersector8HybridPluecker);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4vMBIntersector8HybridMoeller);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoeller);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoellerNoFilter);
SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iIntersector8HybridPluecker);
SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iMBIntersector8HybridPluecker);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector8);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4GridAOSIntersector8);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualIntersector8Chunk);
SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualMBIntersector8Chunk);
/* select intersectors16 */
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iIntersector16);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iMBIntersector16);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single_OBB);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single_OBB);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iMBIntersector16Single_OBB);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoeller);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoellerNoFilter);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoeller);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoellerNoFilter);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vIntersector16HybridPluecker);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4iIntersector16HybridPluecker);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vMBIntersector16HybridMoeller);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoeller);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoellerNoFilter);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iIntersector16HybridPluecker);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iMBIntersector16HybridPluecker);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Subdivpatch1CachedIntersector16);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4GridAOSIntersector16);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualIntersector16Chunk);
SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualMBIntersector16Chunk);
#endif
}
Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1vIntersector1;
intersectors.intersector4 = BVH4Bezier1vIntersector4Single;
intersectors.intersector8 = BVH4Bezier1vIntersector8Single;
intersectors.intersector16 = BVH4Bezier1vIntersector16Single;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1iIntersector1;
intersectors.intersector4 = BVH4Bezier1iIntersector4Single;
intersectors.intersector8 = BVH4Bezier1iIntersector8Single;
intersectors.intersector16 = BVH4Bezier1iIntersector16Single;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Line4iIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Line4iIntersector1;
intersectors.intersector4 = BVH4Line4iIntersector4;
intersectors.intersector8 = BVH4Line4iIntersector8;
intersectors.intersector16 = BVH4Line4iIntersector16;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Line4iMBIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Line4iMBIntersector1;
intersectors.intersector4 = BVH4Line4iMBIntersector4;
intersectors.intersector8 = BVH4Line4iMBIntersector8;
intersectors.intersector16 = BVH4Line4iMBIntersector16;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors_OBB(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1vIntersector1_OBB;
intersectors.intersector4 = BVH4Bezier1vIntersector4Single_OBB;
intersectors.intersector8 = BVH4Bezier1vIntersector8Single_OBB;
intersectors.intersector16 = BVH4Bezier1vIntersector16Single_OBB;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors_OBB(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1iIntersector1_OBB;
intersectors.intersector4 = BVH4Bezier1iIntersector4Single_OBB;
intersectors.intersector8 = BVH4Bezier1iIntersector8Single_OBB;
intersectors.intersector16 = BVH4Bezier1iIntersector16Single_OBB;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Bezier1iMBIntersectors_OBB(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Bezier1iMBIntersector1_OBB;
intersectors.intersector4 = BVH4Bezier1iMBIntersector4Single_OBB;
intersectors.intersector8 = BVH4Bezier1iMBIntersector8Single_OBB;
intersectors.intersector16 = BVH4Bezier1iMBIntersector16Single_OBB;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4Intersector1Moeller;
intersectors.intersector4_filter = BVH4Triangle4Intersector4HybridMoeller;
intersectors.intersector4_nofilter = BVH4Triangle4Intersector4HybridMoellerNoFilter;
intersectors.intersector8_filter = BVH4Triangle4Intersector8HybridMoeller;
intersectors.intersector8_nofilter = BVH4Triangle4Intersector8HybridMoellerNoFilter;
intersectors.intersector16_filter = BVH4Triangle4Intersector16HybridMoeller;
intersectors.intersector16_nofilter = BVH4Triangle4Intersector16HybridMoellerNoFilter;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsInstancing(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4XfmTriangle4Intersector1Moeller;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Triangle8IntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle8Intersector1Moeller;
intersectors.intersector4_filter = BVH4Triangle8Intersector4HybridMoeller;
intersectors.intersector4_nofilter = BVH4Triangle8Intersector4HybridMoellerNoFilter;
intersectors.intersector8_filter = BVH4Triangle8Intersector8HybridMoeller;
intersectors.intersector8_nofilter = BVH4Triangle8Intersector8HybridMoellerNoFilter;
intersectors.intersector16_filter = BVH4Triangle8Intersector16HybridMoeller;
intersectors.intersector16_nofilter = BVH4Triangle8Intersector16HybridMoellerNoFilter;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Triangle4vIntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4vIntersector1Pluecker;
intersectors.intersector4 = BVH4Triangle4vIntersector4HybridPluecker;
intersectors.intersector8 = BVH4Triangle4vIntersector8HybridPluecker;
intersectors.intersector16 = BVH4Triangle4vIntersector16HybridPluecker;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Triangle4iIntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4iIntersector1Pluecker;
intersectors.intersector4 = BVH4Triangle4iIntersector4HybridPluecker;
intersectors.intersector8 = BVH4Triangle4iIntersector8HybridPluecker;
intersectors.intersector16 = BVH4Triangle4iIntersector16HybridPluecker;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Triangle4vMBIntersectorsHybrid(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Triangle4vMBIntersector1Moeller;
intersectors.intersector4 = BVH4Triangle4vMBIntersector4HybridMoeller;
intersectors.intersector8 = BVH4Triangle4vMBIntersector8HybridMoeller;
intersectors.intersector16 = BVH4Triangle4vMBIntersector16HybridMoeller;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Quad4vIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Quad4vIntersector1Moeller;
intersectors.intersector4_filter = BVH4Quad4vIntersector4HybridMoeller;
intersectors.intersector4_nofilter = BVH4Quad4vIntersector4HybridMoellerNoFilter;
intersectors.intersector8_filter = BVH4Quad4vIntersector8HybridMoeller;
intersectors.intersector8_nofilter = BVH4Quad4vIntersector8HybridMoellerNoFilter;
intersectors.intersector16_filter = BVH4Quad4vIntersector16HybridMoeller;
intersectors.intersector16_nofilter = BVH4Quad4vIntersector16HybridMoellerNoFilter;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Quad4iIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Quad4iIntersector1Pluecker;
intersectors.intersector4 = BVH4Quad4iIntersector4HybridPluecker;
intersectors.intersector8 = BVH4Quad4iIntersector8HybridPluecker;
intersectors.intersector16= BVH4Quad4iIntersector16HybridPluecker;
return intersectors;
}
Accel::Intersectors BVH4Factory::BVH4Quad4iMBIntersectors(BVH4* bvh)
{
Accel::Intersectors intersectors;
intersectors.ptr = bvh;
intersectors.intersector1 = BVH4Quad4iMBIntersector1Pluecker;
intersectors.intersector4 = BVH4Quad4iMBIntersector4HybridPluecker;
intersectors.intersector8 = BVH4Quad4iMBIntersector8HybridPluecker;
intersectors.intersector16= BVH4Quad4iMBIntersector16HybridPluecker;
return intersectors;
}
void BVH4Factory::createLineSegmentsLine4i(LineSegments* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Line4i::type,mesh->parent);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Line4iMeshRefitSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break;
default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag");
}
}
void BVH4Factory::createTriangleMeshTriangle4Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Triangle4::type,mesh->parent);
builder = mesh->parent->device->bvh4_factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0);
}
#if defined (__TARGET_AVX__)
void BVH4Factory::createTriangleMeshTriangle8Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
accel = new BVH4(Triangle8::type,mesh->parent);
builder = mesh->parent->device->bvh4_factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0);
}
#endif
void BVH4Factory::createTriangleMeshTriangle4vMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Triangle4v::type,mesh->parent);
builder = mesh->parent->device->bvh4_factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0);
}
void BVH4Factory::createTriangleMeshTriangle4iMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Triangle4i::type,mesh->parent);
builder = mesh->parent->device->bvh4_factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0);
}
void BVH4Factory::createTriangleMeshTriangle4(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Triangle4::type,mesh->parent);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4MeshBuilderSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4MeshRefitSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0); break;
default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag");
}
}
#if defined (__TARGET_AVX__)
void BVH4Factory::createTriangleMeshTriangle8(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Triangle8::type,mesh->parent);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle8MeshBuilderSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle8MeshRefitSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0); break;
default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag");
}
}
#endif
void BVH4Factory::createTriangleMeshTriangle4v(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Triangle4v::type,mesh->parent);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4vMeshBuilderSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4vMeshRefitSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0); break;
default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag");
}
}
void BVH4Factory::createTriangleMeshTriangle4i(TriangleMesh* mesh, AccelData*& accel, Builder*& builder)
{
BVH4Factory* factory = mesh->parent->device->bvh4_factory;
accel = new BVH4(Triangle4i::type,mesh->parent);
switch (mesh->flags) {
case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4iMeshBuilderSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4iMeshRefitSAH(accel,mesh,0); break;
case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0); break;
default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag");
}
}
Accel* BVH4Factory::BVH4Bezier1v(Scene* scene)
{
BVH4* accel = new BVH4(Bezier1v::type,scene);
Accel::Intersectors intersectors = BVH4Bezier1vIntersectors(accel);
Builder* builder = BVH4Bezier1vSceneBuilderSAH(accel,scene,0);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Bezier1i(Scene* scene)
{
BVH4* accel = new BVH4(Bezier1i::type,scene);
Accel::Intersectors intersectors = BVH4Bezier1iIntersectors(accel);
Builder* builder = BVH4Bezier1iSceneBuilderSAH(accel,scene,0);
scene->needBezierVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Line4i(Scene* scene)
{
BVH4* accel = new BVH4(Line4i::type,scene);
Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel);
Builder* builder = nullptr;
if (scene->device->line_builder == "default" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0);
else if (scene->device->line_builder == "sah" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0);
else if (scene->device->line_builder == "dynamic" ) builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->line_builder+" for BVH4<Line4i>");
scene->needLineVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Line4iMB(Scene* scene)
{
BVH4* accel = new BVH4(Line4i::type,scene);
Accel::Intersectors intersectors = BVH4Line4iMBIntersectors(accel);
Builder* builder = BVH4Line4iMBSceneBuilderSAH(accel,scene,0);
scene->needLineVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Line4iTwolevel(Scene* scene)
{
BVH4* accel = new BVH4(Line4i::type,scene);
Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel);
Builder* builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4OBBBezier1v(Scene* scene, bool highQuality)
{
BVH4* accel = new BVH4(Bezier1v::type,scene);
Accel::Intersectors intersectors = BVH4Bezier1vIntersectors_OBB(accel);
Builder* builder = BVH4Bezier1vBuilder_OBB_New(accel,scene,0);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4OBBBezier1i(Scene* scene, bool highQuality)
{
BVH4* accel = new BVH4(Bezier1i::type,scene);
Accel::Intersectors intersectors = BVH4Bezier1iIntersectors_OBB(accel);
Builder* builder = BVH4Bezier1iBuilder_OBB_New(accel,scene,0);
scene->needBezierVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4OBBBezier1iMB(Scene* scene, bool highQuality)
{
BVH4* accel = new BVH4(Bezier1i::type,scene);
Accel::Intersectors intersectors = BVH4Bezier1iMBIntersectors_OBB(accel);
Builder* builder = BVH4Bezier1iMBBuilder_OBB_New(accel,scene,0);
scene->needBezierVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4IntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4IntersectorsHybrid(accel);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>");
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4);
else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4Morton);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4>");
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4Factory::BVH4Triangle8(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle8IntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle8IntersectorsHybrid(accel);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle8>");
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle8SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8);
else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8Morton);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle8>");
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4Factory::BVH4Triangle4v(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4v::type,scene);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>");
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4vSceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v);
else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4vMorton);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4v>");
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4i(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4i::type,scene);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4iIntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4iIntersectorsHybrid(accel);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4i>");
Builder* builder = nullptr;
if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4iSceneBuilderSpatialSAH(accel,scene,0);
else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY);
else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i);
else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4iMorton);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4i>");
scene->needTriangleVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4vMB(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4vMB::type,scene);
Accel::Intersectors intersectors;
if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel);
else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4vMB>");
Builder* builder = nullptr;
if (scene->device->tri_builder_mb == "default" ) builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0);
else if (scene->device->tri_builder_mb == "sah") builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0);
else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder_mb+" for BVH4<Triangle4vMB>");
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4InstancedBVH4Triangle4ObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsInstancing(accel);
Builder* builder = BVH4BuilderInstancingTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4Twolevel(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4);
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4Factory::BVH4Triangle8Twolevel(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene);
Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel);
Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8);
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4Factory::BVH4Triangle4vTwolevel(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4v::type,scene);
Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4iTwolevel(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4i::type,scene);
Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel);
Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4SpatialSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene);
Builder* builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4Factory::BVH4Triangle8SpatialSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene);
Builder* builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4Factory::BVH4Triangle4ObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4::type,scene);
Builder* builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#if defined (__TARGET_AVX__)
Accel* BVH4Factory::BVH4Triangle8ObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle8::type,scene);
Builder* builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
#endif
Accel* BVH4Factory::BVH4Triangle4vObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4v::type,scene);
Builder* builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4iObjectSplit(Scene* scene)
{
BVH4* accel = new BVH4(Triangle4i::type,scene);
Builder* builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel);
scene->needTriangleVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4SubdivPatch1Cached(Scene* scene)
{
BVH4* accel = new BVH4(SubdivPatch1Cached::type,scene);
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4Subdivpatch1CachedIntersector1;
intersectors.intersector4 = BVH4Subdivpatch1CachedIntersector4;
intersectors.intersector8 = BVH4Subdivpatch1CachedIntersector8;
intersectors.intersector16 = BVH4Subdivpatch1CachedIntersector16;
Builder* builder = BVH4SubdivPatch1CachedBuilderBinnedSAH(accel,scene,0);
scene->needSubdivIndices = false;
scene->needSubdivVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4SubdivGridEager(Scene* scene)
{
BVH4* accel = new BVH4(SubdivPatch1Eager::type,scene);
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4GridAOSIntersector1;
intersectors.intersector4 = BVH4GridAOSIntersector4;
intersectors.intersector8 = BVH4GridAOSIntersector8;
intersectors.intersector16 = BVH4GridAOSIntersector16;
Builder* builder = BVH4SubdivGridEagerBuilderBinnedSAH(accel,scene,0);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4UserGeometry(Scene* scene)
{
BVH4* accel = new BVH4(Object::type,scene);
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4VirtualIntersector1;
intersectors.intersector4 = BVH4VirtualIntersector4Chunk;
intersectors.intersector8 = BVH4VirtualIntersector8Chunk;
intersectors.intersector16 = BVH4VirtualIntersector16Chunk;
Builder* builder = BVH4VirtualSceneBuilderSAH(accel,scene,0);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4UserGeometryMB(Scene* scene)
{
BVH4* accel = new BVH4(Object::type,scene);
Accel::Intersectors intersectors;
intersectors.ptr = accel;
intersectors.intersector1 = BVH4VirtualMBIntersector1;
intersectors.intersector4 = BVH4VirtualMBIntersector4Chunk;
intersectors.intersector8 = BVH4VirtualMBIntersector8Chunk;
intersectors.intersector16 = BVH4VirtualMBIntersector16Chunk;
Builder* builder = BVH4VirtualMBSceneBuilderSAH(accel,scene,0);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4ObjectSplit(TriangleMesh* mesh)
{
BVH4* accel = new BVH4(Triangle4::type,mesh->parent);
Builder* builder = BVH4Triangle4MeshBuilderSAH(accel,mesh,0);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4vObjectSplit(TriangleMesh* mesh)
{
BVH4* accel = new BVH4(Triangle4v::type,mesh->parent);
Builder* builder = BVH4Triangle4vMeshBuilderSAH(accel,mesh,0);
Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Triangle4Refit(TriangleMesh* mesh)
{
BVH4* accel = new BVH4(Triangle4::type,mesh->parent);
Builder* builder = BVH4Triangle4MeshRefitSAH(accel,mesh,0);
Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Quad4v(Scene* scene)
{
BVH4* accel = new BVH4(Quad4v::type,scene);
Builder* builder = BVH4Quad4vSceneBuilderSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Quad4vIntersectors(accel);
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Quad4i(Scene* scene)
{
BVH4* accel = new BVH4(Quad4i::type,scene);
Builder* builder = BVH4Quad4iSceneBuilderSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Quad4iIntersectors(accel);
scene->needQuadVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
Accel* BVH4Factory::BVH4Quad4iMB(Scene* scene)
{
BVH4* accel = new BVH4(Quad4iMB::type,scene);
Builder* builder = BVH4Quad4iMBSceneBuilderSAH(accel,scene,0);
Accel::Intersectors intersectors = BVH4Quad4iMBIntersectors(accel);
scene->needQuadVertices = true;
return new AccelInstance(accel,builder,intersectors);
}
}
| Java |
/* 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/>. */
.frames ul .frames-group .group,
.frames ul .frames-group .group .location {
font-weight: 500;
cursor: default;
}
.frames ul .frames-group.expanded .group,
.frames ul .frames-group.expanded .group .location {
color: var(--theme-highlight-blue);
}
.frames ul .frames-group.expanded .react path {
fill: var(--theme-highlight-blue);
}
.frames ul .frames-group .frames-list li {
padding-left: 30px;
}
.frames ul .frames-group .frames-list {
border-top: 1px solid var(--theme-splitter-color);
border-bottom: 1px solid var(--theme-splitter-color);
}
.frames ul .frames-group.expanded .badge {
color: var(--theme-highlight-blue);
}
| Java |
/**
* Nooku Platform - http://www.nooku.org/platform
*
* @copyright Copyright (C) 2011 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link https://github.com/nooku/nooku-platform for the canonical source repository
*/
if(!Attachments) var Attachments = {};
Attachments.List = new Class({
element : null,
initialize: function(options) {
this.element = document.id(options.container);
this.url = options.action;
this.token = options.token;
this.coordinates = '';
this.trueSize = '';
if(!this.element) {
return;
}
this.addCrop();
var that = this;
this.element.getElements('a[data-action]').each(function(a) {
if(a.get('data-action'))
{
a.addEvent('click', function(e) {
e.stop();
that.execute(this.get('data-action'), this.get('data-id'), this.get('data-row'));
});
}
});
},
addCrop: function()
{
var target = jQuery('#target');
var img = new Image(), self = this;
img.onload = function() {
self.trueSize = [this.width, this.height];
if (target.length) {
target.Jcrop({
boxWidth: 600,
boxHeight: 600,
trueSize: self.trueSize,
aspectRatio: 4 / 3,
minSize: [200, 150],
setSelect: [0, 0, 200, 150],
onSelect: self.setCoordinates.bind(self),
onChange: self.setCoordinates.bind(self)
});
}
};
var source = target.attr("src");
if (source) {
img.src = source;
}
},
setCoordinates: function(c)
{
this.coordinates = c;
},
execute: function(action, id, row)
{
var method = '_action' + action.capitalize();
if($type(this[method]) == 'function')
{
this.action = action;
var uri = new URI(this.url);
uri.setData('id', id);
this[method].call(this, uri);
}
},
_actionDelete: function(uri)
{
var form = new Kodekit.Form({
method: 'post',
url: uri.toString(),
params: {
_action: 'delete',
csrf_token: this.token
}
});
form.submit();
},
_actionCrop: function(uri)
{
jQuery.ajax({
url: uri.toString(),
dataType: 'json',
method: 'post',
data: {
_action: 'edit',
csrf_token: this.token,
x1: this.coordinates.x,
y1: this.coordinates.y,
x2: this.coordinates.x2,
y2: this.coordinates.y2
}
}).then(function(data, textStatus, xhr) {
if (xhr.status === 204) {
jQuery.ajax({
url: uri.toString(),
dataType: 'json',
method: 'get'
}).then(function(data, textStatus, xhr) {
if (xhr.status === 200 && typeof data.item === 'object') {
var thumbnail = data.item.thumbnail,
element = window.parent.jQuery('.thumbnail[data-id="'+data.item.id+'"] img'),
source = element.attr('src');
thumbnail = source.substring(0, source.lastIndexOf('/'))+'/'+thumbnail;
element.attr('src', thumbnail);
if (window.parent.SqueezeBox) {
window.parent.SqueezeBox.close();
}
}
});
} else {
alert('Unable to crop thumbnail');
}
});
}
}); | Java |
/*! JointJS v3.4.1 (2021-08-18) - JavaScript diagramming library
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/.
*/
this.joint = this.joint || {};
this.joint.shapes = this.joint.shapes || {};
(function (exports, basic_mjs, Element_mjs, Link_mjs) {
'use strict';
var State = basic_mjs.Circle.define('fsa.State', {
attrs: {
circle: { 'stroke-width': 3 },
text: { 'font-weight': '800' }
}
});
var StartState = Element_mjs.Element.define('fsa.StartState', {
size: { width: 20, height: 20 },
attrs: {
circle: {
transform: 'translate(10, 10)',
r: 10,
fill: '#000000'
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><circle/></g></g>',
});
var EndState = Element_mjs.Element.define('fsa.EndState', {
size: { width: 20, height: 20 },
attrs: {
'.outer': {
transform: 'translate(10, 10)',
r: 10,
fill: '#ffffff',
stroke: '#000000'
},
'.inner': {
transform: 'translate(10, 10)',
r: 6,
fill: '#000000'
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
});
var Arrow = Link_mjs.Link.define('fsa.Arrow', {
attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }},
smooth: true
});
exports.Arrow = Arrow;
exports.EndState = EndState;
exports.StartState = StartState;
exports.State = State;
}(this.joint.shapes.fsa = this.joint.shapes.fsa || {}, joint.shapes.basic, joint.dia, joint.dia));
| Java |
<!doctype html>
<script>
var searchParams = new URL(location).searchParams;
var test = searchParams.get("test");
window.onportalactivate = function(e) {
if (test == "adopt-once") {
var portal = e.adoptPredecessor();
document.body.appendChild(portal);
if (portal instanceof HTMLPortalElement) {
portal.postMessage("adopted", "*");
}
}
if (test == "adopt-twice") {
var portal = e.adoptPredecessor();
document.body.appendChild(portal);
try {
e.adoptPredecessor();
} catch(e) {
if (e.name == "InvalidStateError") {
portal.postMessage("passed", "*");
}
}
}
if (test == "adopt-after-event") {
setTimeout(function() {
try {
e.adoptPredecessor();
} catch(e) {
if (e.name == "InvalidStateError") {
var bc_test = new BroadcastChannel(`test-${test}`);
bc_test.postMessage("passed");
bc_test.close();
}
}
});
}
}
</script>
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<title>HYPERNOM</title>
<!--
Nom all the cells of each 4d platonic solid, by mapping your head rotations to S^3.
By Henry Segerman, Vi Hart, and Andrea Hawksley, using Marc ten Bosch's 4D graphics shader, Mozilla's webVR stuff, and threejs.
http://www.segerman.org/
http://vihart.com
https://github.com/hawksley
http://www.marctenbosch.com
https://github.com/MozVR/vr-web-examples/tree/master/threejs-vr-boilerplate
http://threejs.org
-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
background-color: #000;
color: #fff;
margin: 0px;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body style="cursor:pointer">
<audio id='music' src="media/monkeygif.mp3"/>
<audio id='nom1' src="media/nom1.ogg" >
<audio id='nom2' src="media/nom2.ogg" >
<audio id='nom3' src="media/nom3.ogg" >
<audio id='nom4' src="media/nom4.ogg" >
<audio id='nom5' src="media/nom5.ogg" >
<audio id='win' src="media/win.ogg" >
</body>
<!--
three.js 3d library
-->
<script src="js/lib/three.min.js"></script>
<script src="js/lib/threex.dynamictexture.js"></script>
<!--
library for fast quaternion rotation
-->
<script src="js/lib/gl-matrix.js"></script>
<script src="js/sphMath.js"></script>
<!--
VRControls.js acquires positional information from connected VR devices and applies the transformations to a three.js camera object.
-->
<script src="js/vr/PhoneVR.js"></script>
<script src="js/vr/VRControlsHyperNom.js"></script>
<!--
VREffect.js handles stereo camera setup and rendering.
-->
<script src="js/vr/VREffect.js"></script>
<!-- Quaternions for the centers of the cells -->
<script src="js/centers_600_cell.js"></script>
<script src="js/centers_5_cell.js"></script>
<script src="js/centers_8_cell.js"></script>
<script src="js/centers_16_cell.js"></script>
<script src="js/centers_24_cell.js"></script>
<script src="js/centers_120_cell.js"></script>
<script src="js/loaders/OBJLoader.js"></script>
<!--font from http://mrdoob.github.com/three.js/examples/fonts/helvetiker_regular.typeface.js -->
<script src="lib/helvetiker.js"></script>
<script type="x-shader/x-vertex" id="vertexShader">
// This shader moves vertices around
// Quaternion Multiplication
vec4 quatMult( in vec4 p, in vec4 q )
{
vec4 r;
r.w = + p.w*q.w - p.x*q.x - p.y*q.y - p.z*q.z;
r.x = + p.w*q.x + p.x*q.w + p.y*q.z - p.z*q.y;
r.y = + p.w*q.y - p.x*q.z + p.y*q.w + p.z*q.x;
r.z = + p.w*q.z + p.x*q.y - p.y*q.x + p.z*q.w;
return r;
}
vec4 quatInv( in vec4 p )
{
vec4 r;
r.x = -p.x;
r.y = -p.y;
r.z = -p.z;
r.w = p.w;
return r;
}
// Project the vector p to the 3-space perpendicular to q
vec4 projVecPerp( in vec4 p, in vec4 q )
{
vec4 r;
float pDotq = dot(p,q);
float qDotq = dot(q,q);
float foo = pDotq / qDotq;
r = p - foo*q;
return r;
}
// point on geod in S3 from p in direction of q going distance dist
vec4 pointOnS3Geod( in vec4 p, in vec4 q, in float dist)
{
vec4 Q = normalize( q - dot(p,q) * p );
return cos(dist)*p + sin(dist)*Q;
}
// input
uniform float time; // global time in seconds
uniform vec4 quatPerCell; // quaternion that moves this monkey into 4-space, set once per monkey
// uniform int fogType; // which type of fog to use
uniform vec2 mousePos;
uniform vec4 travelDir; //quaternion for which way we are rotating
uniform vec4 colourDir; //quaternion for which way we are colouring
uniform mat4 HopfColorMatrix; //rotates colourDir to lie along (0,0,z,w)
uniform vec4 moveQuat; //quaternion for head
uniform mat3 rotMatrix; //rotate tetrahedral cells into correct orientation
uniform float modelScale; //scale model by this
// Hopf fibration coloring
// returns a color based on the 4D normal
vec3 HopfColor( in vec4 nBase ) /// head foot are all same colour
{
/////////first rotate the 4D normal to a space aligned with the polychoron
vec4 n = HopfColorMatrix * nBase;
// compute the color
float x = n.x;
float y = n.y;
float u = n.z;
float v = n.w;
float r = 2. * (u*x + v*y);
float g = 2. * (u*y - v*x);
float b = x*x + y*y - u*u - v*v;
/// first two coords are 2*z*conj(w), where z = x+iy, w = u+iv
/// rotate [0,0,-1] to [-1,-1,-1]/sqrt(3)
mat3 RotDownToDiag = mat3( vec3(0.707107, -0.707107, 0.), ///// input columns not rows?!?!?!
vec3(0.408248, 0.408248, -0.816497), //Because line n+3 is RotDownToDiag*newCol, not newCol*RotDownToDiag.
vec3(0.57735, 0.57735, 0.57735) ); //This basically lets the shader do matrix multiplication via dot products, which is relatively efficient.
vec3 newCol = vec3(r,g,b);
newCol = RotDownToDiag * newCol;
return vec3(newCol.x*0.5 + 0.5,newCol.y*0.5 + 0.5,newCol.z*0.5 + 0.5);
}
// output
varying vec3 vColor; // this shader computes the color of each vertex
// this gets called once per vertex of the monkey mesh (and numCells times since there are numCells monkeys)
void main()
{
// base position
// turn a 3D position of a model into a 4D position by adding a 1 as the w component then normalizing to get onto the unit 3-sphere
// vec4 p3sphere = normalize( vec4(position.zyx, 1.0) );
vec3 posn = position.zyx;
posn = rotMatrix * posn;
vec4 p3sphere = normalize( vec4(modelScale * posn, 1.0) );
// then rotate using this cell's quaternion to place in 4D
vec4 pt0 = quatMult( quatPerCell, p3sphere ); //position at time = 0
// this is the normal to the point
// same concept as for the position, but we add a 0 as the w component
vec4 n3sphere = vec4( normal.zyx, 0.0);
// above is normal on a cubical cell of the hypercube, below we get the corresponding
// normal on the 3-sphere
n3sphere = projVecPerp( n3sphere, p3sphere );
// rotate the normal using this monkey's quaternion
vec4 nt0 = quatMult(quatPerCell, n3sphere );
// // also rotate everything over time
// vec4 quatOverTime = pointOnS3Geod( vec4(0,0,0,1), travelDir, 0.5*time );
// vec4 quatOverTime = vec4(0,0,0,1);
vec4 quatOverTime = moveQuat;
vec4 p = quatMult( quatOverTime, pt0 );
vec4 n = quatMult( quatOverTime, nt0 );
// stereographic projection from 4D to 3D
vec3 pos3 = vec3( p.x / (1.0-p.w), p.y / (1.0-p.w), p.z / (1.0-p.w) );
// compute the color from the normal
//// using HopfColor again...
vec3 nColor = HopfColor(nt0);
//// or the transported back to 1 normal
// vec4 nTransported = quatMult(quatInv(pt0), nt0);
// vec3 nColor = vec3(0.5,0.5,0.5) + 0.5*normalize( vec3( nTransported.x, nTransported.y, nTransported.z) );
vec3 pColor = HopfColor(pt0);
vColor = -0.5*(nColor-vec3(0.5,0.5,0.5)) + 1.0*(pColor-vec3(0.5,0.5,0.5)) + vec3(0.5,0.5,0.5);
// vColor = pColor;
// vColor = nColor;
// take the final 3D position and project it onto the screen
// gl_Position = projectionMatrix * modelViewMatrix * vec4( pos3 + vec3(0.0,-0.6,-1.5), 1.0 );
// gl_Position = projectionMatrix * modelViewMatrix * vec4( pos3 + vec3(0.0,-0.7,-2.3), 1.0 );
gl_Position = modelViewMatrix * vec4( pos3 , 1.0 ); //truncate before the projectionMatrix transform (continued on line 253)
//Okay, now a slightly tricky thing:
//The camera's going to cull any vertices that are closer than 0.2, or further away than 25, from the camera.
//(in practice, this seems to be slightly different. I'm not sure why.)
//When this happens, it creates the black triangle of death, which pulls the viewer out of the virtual reality.
//To get around this, we're going to flatten out each vertex just before it reaches 0.2 or 25, moving it to where it would be.
//So, essentially, this is like replacing actual stars with a correctly painted planetarium.
//In case there's some weird z-layering going on, we're going to map -0.3,0 to -0.3, -0.2, preserving order.
float oldz=gl_Position.z;
if(oldz>-0.3 && oldz<0.0){
//map [-0.3, 0.0] to [-0.3,-0.2]
float newz=(oldz*0.3333333 - 0.2);
gl_Position.x=gl_Position.x*newz/(oldz);
gl_Position.y=gl_Position.y*newz/(oldz);
gl_Position.z=newz;
gl_Position.w=1.0;
}
gl_Position=projectionMatrix * gl_Position;
// do fog
// if ( fogType == 1 )
// {
// ramp fog
// compute distance to camera from 0 to 1
float zz = gl_Position.z / gl_Position.w;
// go from 1 to 0 instead (0 is furthest and 1 is where the camera is )
// ( note that the computed distance is not linear )
float fogScale = 1. - zz;
// anything closer than 0.1 gets regular color
if ( fogScale > 0.1 )
fogScale = 1.0;
// everything else ramps from 0 to 1
else
fogScale = fogScale / 0.1;
// mutliply color by this value to make it go to black
vColor *= fogScale; //2015-02-17: fog re-enabled
// }
// else if ( fogType == 2 )
// {
// // near fog
// float zz = gl_Position.z / gl_Position.w;
// // go from 1 to 0, and make the curve less straight
// float fogScale = pow( 1. - zz, 0.7 );
// // everything closer than 0.2 gets regular color
// // but everything else stays the same, creating a discontinuity
// if ( fogScale > 0.2 ) fogScale = 1.0;
// // mutliply color by this value to make it go to black
// vColor *= fogScale;
// } else if (fogType == 3 ){
// vColor.r *= mousePos.x/1000.;
// vColor.g *= mousePos.y/1000.;
// vColor.b *= abs(1. - (mousePos.x + mousePos.y)/1000.);
// }
}
</script>
<script type="x-shader/x-vertex" id="fragmentShader">
// this gets called once per pixel
varying vec3 vColor;
void main()
{
// just use the color we computed and assign it to this pixel
gl_FragColor = vec4( vColor, 1. );
}
</script>
<script type="text/javascript" id="mainCode" src="js/hypernom.js"></script>
</html>
| Java |
.pinboard-open-btn {
margin-top: -1px;
background-color: #e6eef5 !important;
color: #252c33 !important;
}
#pinboard-panel {
background-color: #e6eef5;
color: #252c33;
flex: auto;
-webkit-flex: auto;
display: flex;
display: -webkit-flex;
flex-flow: row;
-webkit-flex-flow: row;
}
#pinboard-panel .header {
padding-left: 2px;
height: 18px;
}
/*
* Pinned jobs container
*/
#pinned-job-list {
position: relative;
flex: auto;
-webkit-flex: auto;
margin: 7px 7px 10px;
}
#pinned-job-list .content {
position: absolute;
width: 100%;
height: 100%;
padding: 2px;
overflow: auto;
background-color: #FFFFFF;
}
.pinned-job {
margin-bottom: 2px;
padding: 1px 2px;
width: 3.5em;
}
.pinned-job-close-btn {
padding: 1px 2px 1px 2px;
border-color: #fafafa #fafafa #fafafa transparent;
}
.pinboard-preload-txt {
color: #bfbfbf;
}
/*
* Related bugs container
*/
#pinboard-related-bugs {
position: relative;
width: 200px;
flex: none;
-webkit-flex: none;
margin: 7px 7px 10px;
}
#pinboard-related-bugs .content {
position: absolute;
height: 100%;
width: 200px;
padding: 2px;
overflow-x: hidden;
color: black;
background-color: #FFFFFF;
}
.add-related-bugs-icon {
margin-right: 2px;
font-size: 17px;
color: #98c3da;
}
.add-related-bugs-form {
position: relative;
top: -18px;
left: 20px;
}
.add-related-bugs-input {
width: 12em;
}
.pinboard-related-bug-preload-txt {
vertical-align: top;
}
.pinboard-related-bugs-btn {
margin-bottom: -1px;
}
.pinboard-related-bugs-btn:hover > .related-bugs-link {
color: #2a6496;
text-decoration: underline;
}
/* Spin button suppression on chrome (bug 1045611) */
#pinboard-related-bugs form input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Spin button suppression on firefox (bug 1045611) */
#pinboard-related-bugs form input[type=number] {
-moz-appearance: textfield;
}
/*
* Classification container
*/
#pinboard-classification {
flex: none;
-webkit-flex: none;
width: 185px;
padding: 5px;
}
.pinboard-label {
color: #777;
}
#pinboard-classification-content {
color: black;
}
#pinboard-classification select {
width: 177px;
}
.add-classification-input {
width: 177px;
height: 20px;
padding: 0 0 0 3px;
border-radius: 0;
font-size: 12px;
}
/*
* Save container and dropdown menu controls
*/
#pinboard-controls {
flex: none;
-webkit-flex: none;
height: 43px;
margin: 20px;
}
#pinboard-controls .dropdown-menu {
z-index: 2000;
}
#pinboard-controls .save-btn-dropdown {
margin-left: -1px;
padding-top: 1px;
display: inline;
width: 24px;
float: right;
}
#pinboard-controls .save-btn {
float: left;
display: inline;
width: 70px;
}
.save-btn {
width: 81px;
}
.save-btn-dropdown {
width: 18px;
}
.btn-group + .btn + .save-btn-dropdown {
margin-left: -5px;
}
| Java |
<form class="form-horizontal well" ng-submit="create(procedure)" >
<fieldset>
<legend>Create Procedure</legend>
<div class="form-group">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputMessage" placeholder="message" ng-model="procedure.message" >
</div>
</div>
<div class="form-group">
<label for="inputSource" class="col-lg-2 control-label">Source</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputSource" placeholder="source" ng-model="procedure.source" >
</div>
</div>
<div class="form-group">
<label for="inputType" class="col-lg-2 control-label">Type</label>
<div class="col-lg-10">
<select id="inputType" class="form-control" placeholder="type" ng-model="procedure.type">
<option>Crown Procedure</option>
<option>Surface Procedure</option>
<option>Ground Procedure</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputEnvironment" class="col-lg-2 control-label">Environment</label>
<div class="col-lg-10">
<select id="inputEnvironment" class="form-control" placeholder="environment" ng-model="procedure.environment">
<option>Production</option>
<option>Staging</option>
<option>Development</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputNetwork" class="col-lg-2 control-label">Network</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputNetwork" placeholder="network" ng-model="procedure.network" >
</div>
</div>
<div class="form-group">
<label for="inputDevice" class="col-lg-2 control-label">Device</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputDevice" placeholder="device" ng-model="procedure.device" >
</div>
</div>
<div class="form-group">
<label for="inputApplication" class="col-lg-2 control-label">Application</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputApplication" placeholder="application" ng-model="procedure.application" >
</div>
</div>
<div class="form-group">
<label for="inputStatus" class="col-lg-2 control-label">Status</label>
<div class="col-lg-10">
<select id="inputStatus" class="form-control" placeholder="status" ng-model="procedure.status">
<option>Draft</option>
<option>Active</option>
<option>Inactive</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputDescription" class="col-lg-2 control-label">Description</label>
<div class="col-lg-10">
<div text-angular ng-model="procedure.description" ></div>
</div>
</div>
<div class="form-group">
<label for="inputSteps" class="col-lg-2 control-label">Detailed Steps</label>
<div class="col-lg-10">
<div text-angular ng-model="procedure.steps" ></div>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<a href="#/procedures" type="reset" class="btn btn-sm btn-default">Cancel</a>
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
</div>
</fieldset>
</form>
| Java |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
panel_file = open('panels.txt','r')
name_file = open('testName.txt','r')
sample_type_file = open("sampleType.txt")
test_panel_results = open("output/testPanelResults.txt", 'w')
panel = []
type = []
test_names = []
def get_split_names( name ):
split_name_list = name.split("/")
for i in range(0, len(split_name_list)):
split_name_list[i] = split_name_list[i].strip()
return split_name_list
def esc_char(name):
if "'" in name:
return "$$" + name + "$$"
else:
return "'" + name + "'"
for line in panel_file:
panel.append(line.strip())
panel_file.close()
for line in sample_type_file:
type.append(line.strip())
sample_type_file.close()
for line in name_file:
test_names.append(line.strip())
name_file.close()
test_panel_results.write("Below should be pasted to TestPanel.csv\n\n")
for row in range(0, len(test_names)):
if len(panel[row]) > 1:
test_description = esc_char(test_names[row] + "(" + type[row] + ")")
test_panel_results.write("nextval( 'panel_item_seq' ) , (select id from panel where name = '" + panel[row] + "')")
test_panel_results.write(" , (select id from test where description = " + test_description + ") , null , now() \n")
test_panel_results.close()
print "Done look for results in testPanelResults.txt" | Java |
/*
This file is part of SUPPL - the supplemental library for DOS
Copyright (C) 1996-2000 Steffen Kaiser
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* $RCSfile: eestrcon.c,v $
$Locker: $ $Name: $ $State: Exp $
char *EStrConcat(int argcnt, ...)
Concats up to argcnt strings together and malloc() a buffer that will
receive the result.
If one of the string == NULL, this string is ignored.
On failure, the program is terminated with the "out of memory" error.
Return:
the malloc'ed buffer
ob(ject): EStrConcat
su(bsystem): error
ty(pe): H
sh(ort description): Concat several strings together
lo(ng description): Concats several strings together, by using the
\tok{StrConcat()} function, and terminates the program on failure
with the error message: "Out of memory"
pr(erequistes):
re(lated to): StrConcat
se(condary subsystems): dynstr
in(itialized by):
wa(rning):
bu(gs):
va(lue): constructed dynamic string
fi(le): eestrcon.c
*/
#include "initsupl.loc"
#ifndef _MICROC_
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#endif
#include "dynstr.h"
#include "msgs.h"
#include "suppldbg.h"
#ifdef RCS_Version
static char const rcsid[] =
"$Id: eestrcon.c,v 1.1 2006/06/17 03:25:02 blairdude Exp $";
#endif
#ifdef _MICROC_
register char *EStrConcat(int argcnt)
{ unsigned cnt, *poi;
unsigned Xcnt, *Xpoi;
unsigned length;
char *h, *p;
DBG_ENTER1
cnt = nargs();
DBG_ENTER2("EStrConcat", "error")
DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, cnt) )
Xpoi = poi = cnt * 2 - 2 + &argcnt;
Xcnt = cnt = min(cnt, *poi);
for(length = 1; cnt--;)
if(*--poi) length += strlen(*poi);
chkHeap
if((h = p = malloc(length)) == 0)
Esuppl_noMem();
chkHeap
while(Xcnt--)
if(*--Xpoi)
p = stpcpy(p, *Xpoi);
chkHeap
DBG_RETURN_S( h)
}
#else /* !_MICROC_ */
char *EStrConcat(int argcnt, ...)
{ va_list strings;
char *p, *s;
size_t length, l;
DBG_ENTER("EStrConcat", Suppl_error)
DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, argcnt) )
va_start(strings, argcnt);
chkHeap
p = Estrdup("");
chkHeap
length = 1;
while(argcnt--) {
s = va_arg(strings, char *);
if(s && *s) {
l = length - 1;
Eresize(p, length += strlen(s));
strcpy(p + l, s);
}
}
va_end(strings);
chkHeap
DBG_RETURN_S( p)
}
#endif /* _MICROC_ */
| Java |
/* 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/. */
import { createStore, applyMiddleware } from 'redux';
import threadDispatcher from '../../common/thread-middleware';
import handleMessages from '../../common/message-handler';
import messages from './messages-worker';
import reducers from './reducers';
import thunk from 'redux-thunk';
const store = createStore(
// Reducers:
reducers,
// Initial State:
{},
// Enhancers:
applyMiddleware(
...[
thunk,
threadDispatcher(self, 'toContent'),
].filter(fn => fn)
)
);
handleMessages(self, store, messages);
| Java |
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* 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/. */
//-----------------------------------------------------------------------------
var BUGNUMBER = 474935;
var summary = 'Do not assert: !ti->typeMap.matches(ti_other->typeMap)';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var a = ["", 0, 0, 0, 0, 0, "", "", 0, "", 0, ""];
var i = 0;
var g = 0;
for each (let e in a) {
"" + [e];
if (i == 3 || i == 7) {
for each (g in [1]) {
}
}
++i;
}
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| Java |
package command
import (
"strings"
"testing"
"time"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/mitchellh/cli"
)
func TestMonitor_Update_Eval(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
mon := newMonitor(ui, nil, fullId)
// Evals triggered by jobs log
state := &evalState{
status: structs.EvalStatusPending,
job: "job1",
}
mon.update(state)
out := ui.OutputWriter.String()
if !strings.Contains(out, "job1") {
t.Fatalf("missing job\n\n%s", out)
}
ui.OutputWriter.Reset()
// Evals trigerred by nodes log
state = &evalState{
status: structs.EvalStatusPending,
node: "12345678-abcd-efab-cdef-123456789abc",
}
mon.update(state)
out = ui.OutputWriter.String()
if !strings.Contains(out, "12345678-abcd-efab-cdef-123456789abc") {
t.Fatalf("missing node\n\n%s", out)
}
// Transition to pending should not be logged
if strings.Contains(out, structs.EvalStatusPending) {
t.Fatalf("should skip status\n\n%s", out)
}
ui.OutputWriter.Reset()
// No logs sent if no update
mon.update(state)
if out := ui.OutputWriter.String(); out != "" {
t.Fatalf("expected no output\n\n%s", out)
}
// Status change sends more logs
state = &evalState{
status: structs.EvalStatusComplete,
node: "12345678-abcd-efab-cdef-123456789abc",
}
mon.update(state)
out = ui.OutputWriter.String()
if !strings.Contains(out, structs.EvalStatusComplete) {
t.Fatalf("missing status\n\n%s", out)
}
}
func TestMonitor_Update_Allocs(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
mon := newMonitor(ui, nil, fullId)
// New allocations write new logs
state := &evalState{
allocs: map[string]*allocState{
"alloc1": &allocState{
id: "87654321-abcd-efab-cdef-123456789abc",
group: "group1",
node: "12345678-abcd-efab-cdef-123456789abc",
desired: structs.AllocDesiredStatusRun,
client: structs.AllocClientStatusPending,
index: 1,
},
},
}
mon.update(state)
// Logs were output
out := ui.OutputWriter.String()
if !strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, "group1") {
t.Fatalf("missing group\n\n%s", out)
}
if !strings.Contains(out, "12345678-abcd-efab-cdef-123456789abc") {
t.Fatalf("missing node\n\n%s", out)
}
if !strings.Contains(out, "created") {
t.Fatalf("missing created\n\n%s", out)
}
ui.OutputWriter.Reset()
// No change yields no logs
mon.update(state)
if out := ui.OutputWriter.String(); out != "" {
t.Fatalf("expected no output\n\n%s", out)
}
ui.OutputWriter.Reset()
// Alloc updates cause more log lines
state = &evalState{
allocs: map[string]*allocState{
"alloc1": &allocState{
id: "87654321-abcd-efab-cdef-123456789abc",
group: "group1",
node: "12345678-abcd-efab-cdef-123456789abc",
desired: structs.AllocDesiredStatusRun,
client: structs.AllocClientStatusRunning,
index: 2,
},
},
}
mon.update(state)
// Updates were logged
out = ui.OutputWriter.String()
if !strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, "pending") {
t.Fatalf("missing old status\n\n%s", out)
}
if !strings.Contains(out, "running") {
t.Fatalf("missing new status\n\n%s", out)
}
}
func TestMonitor_Update_AllocModification(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
mon := newMonitor(ui, nil, fullId)
// New allocs with a create index lower than the
// eval create index are logged as modifications
state := &evalState{
index: 2,
allocs: map[string]*allocState{
"alloc3": &allocState{
id: "87654321-abcd-bafe-cdef-123456789abc",
node: "12345678-abcd-efab-cdef-123456789abc",
group: "group2",
index: 1,
},
},
}
mon.update(state)
// Modification was logged
out := ui.OutputWriter.String()
if !strings.Contains(out, "87654321-abcd-bafe-cdef-123456789abc") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, "group2") {
t.Fatalf("missing group\n\n%s", out)
}
if !strings.Contains(out, "12345678-abcd-efab-cdef-123456789abc") {
t.Fatalf("missing node\n\n%s", out)
}
if !strings.Contains(out, "modified") {
t.Fatalf("missing modification\n\n%s", out)
}
}
func TestMonitor_Monitor(t *testing.T) {
t.Parallel()
srv, client, _ := testServer(t, false, nil)
defer srv.Shutdown()
// Create the monitor
ui := new(cli.MockUi)
mon := newMonitor(ui, client, fullId)
// Submit a job - this creates a new evaluation we can monitor
job := testJob("job1")
resp, _, err := client.Jobs().Register(job, nil)
if err != nil {
t.Fatalf("err: %s", err)
}
// Start monitoring the eval
var code int
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
code = mon.monitor(resp.EvalID, false)
}()
// Wait for completion
select {
case <-doneCh:
case <-time.After(5 * time.Second):
t.Fatalf("eval monitor took too long")
}
// Check the return code. We should get exit code 2 as there
// would be a scheduling problem on the test server (no clients).
if code != 2 {
t.Fatalf("expect exit 2, got: %d", code)
}
// Check the output
out := ui.OutputWriter.String()
if !strings.Contains(out, resp.EvalID) {
t.Fatalf("missing eval\n\n%s", out)
}
if !strings.Contains(out, "finished with status") {
t.Fatalf("missing final status\n\n%s", out)
}
}
func TestMonitor_MonitorWithPrefix(t *testing.T) {
t.Parallel()
srv, client, _ := testServer(t, false, nil)
defer srv.Shutdown()
// Create the monitor
ui := new(cli.MockUi)
mon := newMonitor(ui, client, shortId)
// Submit a job - this creates a new evaluation we can monitor
job := testJob("job1")
resp, _, err := client.Jobs().Register(job, nil)
if err != nil {
t.Fatalf("err: %s", err)
}
// Start monitoring the eval
var code int
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
code = mon.monitor(resp.EvalID[:8], true)
}()
// Wait for completion
select {
case <-doneCh:
case <-time.After(5 * time.Second):
t.Fatalf("eval monitor took too long")
}
// Check the return code. We should get exit code 2 as there
// would be a scheduling problem on the test server (no clients).
if code != 2 {
t.Fatalf("expect exit 2, got: %d", code)
}
// Check the output
out := ui.OutputWriter.String()
if !strings.Contains(out, resp.EvalID[:8]) {
t.Fatalf("missing eval\n\n%s", out)
}
if strings.Contains(out, resp.EvalID) {
t.Fatalf("expected truncated eval id, got: %s", out)
}
if !strings.Contains(out, "finished with status") {
t.Fatalf("missing final status\n\n%s", out)
}
// Fail on identifier with too few characters
code = mon.monitor(resp.EvalID[:1], true)
if code != 1 {
t.Fatalf("expect exit 1, got: %d", code)
}
if out := ui.ErrorWriter.String(); !strings.Contains(out, "must contain at least two characters.") {
t.Fatalf("expected too few characters error, got: %s", out)
}
ui.ErrorWriter.Reset()
code = mon.monitor(resp.EvalID[:3], true)
if code != 2 {
t.Fatalf("expect exit 2, got: %d", code)
}
if out := ui.OutputWriter.String(); !strings.Contains(out, "Monitoring evaluation") {
t.Fatalf("expected evaluation monitoring output, got: %s", out)
}
}
func TestMonitor_DumpAllocStatus(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
// Create an allocation and dump its status to the UI
alloc := &api.Allocation{
ID: "87654321-abcd-efab-cdef-123456789abc",
TaskGroup: "group1",
ClientStatus: structs.AllocClientStatusRunning,
Metrics: &api.AllocationMetric{
NodesEvaluated: 10,
NodesFiltered: 5,
NodesExhausted: 1,
DimensionExhausted: map[string]int{
"cpu": 1,
},
ConstraintFiltered: map[string]int{
"$attr.kernel.name = linux": 1,
},
ClassExhausted: map[string]int{
"web-large": 1,
},
},
}
dumpAllocStatus(ui, alloc, fullId)
// Check the output
out := ui.OutputWriter.String()
if !strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, structs.AllocClientStatusRunning) {
t.Fatalf("missing status\n\n%s", out)
}
if !strings.Contains(out, "5/10") {
t.Fatalf("missing filter stats\n\n%s", out)
}
if !strings.Contains(
out, `Constraint "$attr.kernel.name = linux" filtered 1 nodes`) {
t.Fatalf("missing constraint\n\n%s", out)
}
if !strings.Contains(out, "Resources exhausted on 1 nodes") {
t.Fatalf("missing resource exhaustion\n\n%s", out)
}
if !strings.Contains(out, `Class "web-large" exhausted on 1 nodes`) {
t.Fatalf("missing class exhaustion\n\n%s", out)
}
if !strings.Contains(out, `Dimension "cpu" exhausted on 1 nodes`) {
t.Fatalf("missing dimension exhaustion\n\n%s", out)
}
ui.OutputWriter.Reset()
// Dumping alloc status with no eligible nodes adds a warning
alloc.Metrics.NodesEvaluated = 0
dumpAllocStatus(ui, alloc, shortId)
// Check the output
out = ui.OutputWriter.String()
if !strings.Contains(out, "No nodes were eligible") {
t.Fatalf("missing eligibility warning\n\n%s", out)
}
if strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") {
t.Fatalf("expected truncated id, got %s", out)
}
if !strings.Contains(out, "87654321") {
t.Fatalf("expected alloc id, got %s", out)
}
}
| Java |
#!/bin/bash
# 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 https://mozilla.org/MPL/2.0/.
set -ex
# required env vars: CLUSTER_NAME, CONFIG_BRANCH, CONFIG_REPO, NAMESPACE,
# DEPLOYMENT_YAML, DEPLOYMENT_LOG_BASE_URL, DEPLOYMENT_NAME, DEPLOYMENT_VERSION
. ${BASH_SOURCE%/*}/../docker/bin/set_git_env_vars.sh # sets DEPLOYMENT_DOCKER_IMAGE
pushd $(mktemp -d)
git clone --depth=1 -b ${CONFIG_BRANCH:=master} ${CONFIG_REPO} config_checkout
cd config_checkout
set -u
for CLUSTER in ${CLUSTERS:=iowa-a}; do
for DEPLOYMENT in {clock-,canary-,}deploy.yaml daemonset.yaml; do
DEPLOYMENT_FILE=${CLUSTER}/${NAMESPACE:=bedrock-dev}/${DEPLOYMENT}
if [[ -f ${DEPLOYMENT_FILE} ]]; then
sed -i -e "s|image: .*|image: ${DEPLOYMENT_DOCKER_IMAGE}|" ${DEPLOYMENT_FILE}
git add ${DEPLOYMENT_FILE}
fi
done
done
TEST_IMAGE=mozmeao/bedrock_test:${GIT_COMMIT}
sed -i -e "s|TEST_IMAGE: .*|TEST_IMAGE: ${TEST_IMAGE}|;s|image: mozmeao/bedrock_test.*|image: ${TEST_IMAGE}|" .gitlab-ci.yml
git add .gitlab-ci.yml
git commit -m "${NAMESPACE}: set image to ${DEPLOYMENT_DOCKER_IMAGE} in ${CLUSTERS}" || echo "nothing new to commit"
git push
| Java |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ResponseMode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ResponseMode">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="D"/>
* <enumeration value="I"/>
* <enumeration value="Q"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ResponseMode")
@XmlEnum
public enum ResponseMode {
D,
I,
Q;
public String value() {
return name();
}
public static ResponseMode fromValue(String v) {
return valueOf(v);
}
}
| Java |
#if BUILD_UNIT_TESTS
#include "augs/misc/enum/enum_map.h"
#include <Catch/single_include/catch2/catch.hpp>
TEST_CASE("EnumMap") {
enum class tenum {
_0,
_1,
_2,
_3,
_4,
COUNT
};
augs::enum_map<tenum, int> mm;
mm[tenum::_0] = 0;
mm[tenum::_1] = 1;
mm[tenum::_2] = 2;
int cnt = 0;
for (const auto&& m : mm) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == cnt++);
}
REQUIRE(3 == cnt);
for (const auto&& m : reverse(mm)) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == --cnt);
}
REQUIRE(0 == cnt);
{
augs::enum_map<tenum, int> emp;
for (const auto&& abc : emp) {
REQUIRE(false);
(void)abc;
}
for (const auto&& abc : reverse(emp)) {
REQUIRE(false);
(void)abc;
}
REQUIRE(emp.size() == 0);
emp[tenum::_0] = 48;
REQUIRE(emp.size() == 1);
for (const auto&& m : reverse(emp)) {
REQUIRE(48 == m.second);
}
emp.clear();
REQUIRE(emp.size() == 0);
emp[tenum::_1] = 84;
REQUIRE(emp.size() == 1);
for (const auto&& m : reverse(emp)) {
REQUIRE(84 == m.second);
}
emp[tenum::_0] = 0;
emp[tenum::_1] = 1;
emp[tenum::_2] = 2;
REQUIRE(emp.size() == 3);
for (const auto&& m : emp) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == cnt++);
}
REQUIRE(3 == cnt);
for (const auto&& m : reverse(emp)) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == --cnt);
}
emp.clear();
REQUIRE(emp.size() == 0);
emp[tenum::_4] = 4;
emp[tenum::_3] = 3;
emp[tenum::_1] = 1;
emp[tenum::_0] = 0;
auto it = emp.rbegin();
REQUIRE((*it).second == 4);
REQUIRE((*++it).second == 3);
REQUIRE((*++it).second == 1);
REQUIRE((*++it).second == 0);
REQUIRE(++it == emp.rend());
}
}
#endif
| Java |
//#############################################################################
//# #
//# 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: 12/10/2015, 13:28
*
*/
package ims.core.clinical.domain.objects;
/**
*
* @author John MacEnri
* Generated.
*/
public class NonUniqueTaxonomyMap extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1003100071;
private static final long serialVersionUID = 1003100071L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
private ims.domain.lookups.LookupInstance taxonomyName;
private String taxonomyCode;
private java.util.Date effectiveFrom;
private java.util.Date effectiveTo;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public NonUniqueTaxonomyMap (Integer id, int ver)
{
super(id, ver);
isComponentClass=true;
}
public NonUniqueTaxonomyMap ()
{
super();
isComponentClass=true;
}
public NonUniqueTaxonomyMap (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
isComponentClass=true;
}
public Class getRealDomainClass()
{
return ims.core.clinical.domain.objects.NonUniqueTaxonomyMap.class;
}
public ims.domain.lookups.LookupInstance getTaxonomyName() {
return taxonomyName;
}
public void setTaxonomyName(ims.domain.lookups.LookupInstance taxonomyName) {
this.taxonomyName = taxonomyName;
}
public String getTaxonomyCode() {
return taxonomyCode;
}
public void setTaxonomyCode(String taxonomyCode) {
if ( null != taxonomyCode && taxonomyCode.length() > 30 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for taxonomyCode. Tried to set value: "+
taxonomyCode);
}
this.taxonomyCode = taxonomyCode;
}
public java.util.Date getEffectiveFrom() {
return effectiveFrom;
}
public void setEffectiveFrom(java.util.Date effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
public java.util.Date getEffectiveTo() {
return effectiveTo;
}
public void setEffectiveTo(java.util.Date effectiveTo) {
this.effectiveTo = effectiveTo;
}
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*taxonomyName* :");
if (taxonomyName != null)
auditStr.append(taxonomyName.getText());
auditStr.append("; ");
auditStr.append("\r\n*taxonomyCode* :");
auditStr.append(taxonomyCode);
auditStr.append("; ");
auditStr.append("\r\n*effectiveFrom* :");
auditStr.append(effectiveFrom);
auditStr.append("; ");
auditStr.append("\r\n*effectiveTo* :");
auditStr.append(effectiveTo);
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(" 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>");
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getTaxonomyName() != null)
{
sb.append("<taxonomyName>");
sb.append(this.getTaxonomyName().toXMLString());
sb.append("</taxonomyName>");
}
if (this.getTaxonomyCode() != null)
{
sb.append("<taxonomyCode>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTaxonomyCode().toString()));
sb.append("</taxonomyCode>");
}
if (this.getEffectiveFrom() != null)
{
sb.append("<effectiveFrom>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveFrom()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveFrom>");
}
if (this.getEffectiveTo() != null)
{
sb.append("<effectiveTo>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveTo()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveTo>");
}
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);
NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(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);
NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(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 NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(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 getNonUniqueTaxonomyMapfromXML(doc.getRootElement(), factory, domMap);
}
public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(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 (!NonUniqueTaxonomyMap.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!NonUniqueTaxonomyMap.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the NonUniqueTaxonomyMap 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 (NonUniqueTaxonomyMap)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(NonUniqueTaxonomyMap.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
NonUniqueTaxonomyMap ret = null;
if (ret == null)
{
ret = new NonUniqueTaxonomyMap();
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, NonUniqueTaxonomyMap obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("taxonomyName");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setTaxonomyName(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("taxonomyCode");
if(fldEl != null)
{
obj.setTaxonomyCode(new String(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveFrom");
if(fldEl != null)
{
obj.setEffectiveFrom(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveTo");
if(fldEl != null)
{
obj.setEffectiveTo(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
/**
equals
*/
public boolean equals(Object obj)
{
if (null == obj)
{
return false;
}
if(!(obj instanceof NonUniqueTaxonomyMap))
{
return false;
}
NonUniqueTaxonomyMap compareObj=(NonUniqueTaxonomyMap)obj;
if((taxonomyCode==null ? compareObj.taxonomyCode == null : taxonomyCode.equals(compareObj.taxonomyCode))&&
(taxonomyName==null ? compareObj.taxonomyName==null : taxonomyName.equals(compareObj.taxonomyName))&&
(effectiveFrom==null? compareObj.effectiveFrom==null : effectiveFrom.equals(compareObj.effectiveFrom))&&
(effectiveTo==null? compareObj.effectiveTo==null : effectiveTo.equals(compareObj.effectiveTo)))
return true;
return super.equals(obj);
}
/**
toString
*/
public String toString()
{
StringBuffer objStr = new StringBuffer();
if (taxonomyName != null)
objStr.append(taxonomyName.getText() + "-");
objStr.append(taxonomyCode);
return objStr.toString();
}
/**
hashcode
*/
public int hashCode()
{
int hash = 0;
if (taxonomyName!= null) hash += taxonomyName.hashCode()* 10011;
if (taxonomyCode!= null) hash += taxonomyCode.hashCode();
if (effectiveFrom!= null) hash += effectiveFrom.hashCode();
if (effectiveTo!= null) hash += effectiveTo.hashCode();
return hash;
}
public static class FieldNames
{
public static final String ID = "id";
public static final String TaxonomyName = "taxonomyName";
public static final String TaxonomyCode = "taxonomyCode";
public static final String EffectiveFrom = "effectiveFrom";
public static final String EffectiveTo = "effectiveTo";
}
}
| Java |
/*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.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.gui.plotter.mathplot;
import org.math.plot.Plot3DPanel;
import org.math.plot.PlotPanel;
import com.rapidminer.datatable.DataTable;
import com.rapidminer.gui.plotter.PlotterConfigurationModel;
/** The abstract super class for all 3D plotters using the JMathPlot library.
*
* @author Ingo Mierswa
*/
public abstract class JMathPlotter3D extends JMathPlotter {
private static final long serialVersionUID = -8695197842788069313L;
public JMathPlotter3D(PlotterConfigurationModel settings) {
super(settings);
}
public JMathPlotter3D(PlotterConfigurationModel settings, DataTable dataTable) {
super(settings, dataTable);
}
@Override
public PlotPanel createPlotPanel() { return new Plot3DPanel(); }
@Override
public int getNumberOfOptionIcons() {
return 5;
}
}
| Java |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.analysis;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.analysis.Analyzer;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.CloseableComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.indices.analysis.IndicesAnalysisService;
import java.util.Map;
import static com.google.common.collect.Maps.newHashMap;
/**
*
*/
public class AnalysisService extends AbstractIndexComponent implements CloseableComponent {
private final ImmutableMap<String, NamedAnalyzer> analyzers;
private final ImmutableMap<String, TokenizerFactory> tokenizers;
private final ImmutableMap<String, CharFilterFactory> charFilters;
private final ImmutableMap<String, TokenFilterFactory> tokenFilters;
private final NamedAnalyzer defaultAnalyzer;
private final NamedAnalyzer defaultIndexAnalyzer;
private final NamedAnalyzer defaultSearchAnalyzer;
private final NamedAnalyzer defaultSearchQuoteAnalyzer;
public AnalysisService(Index index) {
this(index, ImmutableSettings.Builder.EMPTY_SETTINGS, null, null, null, null, null);
}
@Inject
public AnalysisService(Index index, @IndexSettings Settings indexSettings, @Nullable IndicesAnalysisService indicesAnalysisService,
@Nullable Map<String, AnalyzerProviderFactory> analyzerFactoryFactories,
@Nullable Map<String, TokenizerFactoryFactory> tokenizerFactoryFactories,
@Nullable Map<String, CharFilterFactoryFactory> charFilterFactoryFactories,
@Nullable Map<String, TokenFilterFactoryFactory> tokenFilterFactoryFactories) {
super(index, indexSettings);
Map<String, TokenizerFactory> tokenizers = newHashMap();
if (tokenizerFactoryFactories != null) {
Map<String, Settings> tokenizersSettings = indexSettings.getGroups("index.analysis.tokenizer");
for (Map.Entry<String, TokenizerFactoryFactory> entry : tokenizerFactoryFactories.entrySet()) {
String tokenizerName = entry.getKey();
TokenizerFactoryFactory tokenizerFactoryFactory = entry.getValue();
Settings tokenizerSettings = tokenizersSettings.get(tokenizerName);
if (tokenizerSettings == null) {
tokenizerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
TokenizerFactory tokenizerFactory = tokenizerFactoryFactory.create(tokenizerName, tokenizerSettings);
tokenizers.put(tokenizerName, tokenizerFactory);
tokenizers.put(Strings.toCamelCase(tokenizerName), tokenizerFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltTokenizerFactoryFactory> entry : indicesAnalysisService.tokenizerFactories().entrySet()) {
String name = entry.getKey();
if (!tokenizers.containsKey(name)) {
tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!tokenizers.containsKey(name)) {
tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.tokenizers = ImmutableMap.copyOf(tokenizers);
Map<String, CharFilterFactory> charFilters = newHashMap();
if (charFilterFactoryFactories != null) {
Map<String, Settings> charFiltersSettings = indexSettings.getGroups("index.analysis.char_filter");
for (Map.Entry<String, CharFilterFactoryFactory> entry : charFilterFactoryFactories.entrySet()) {
String charFilterName = entry.getKey();
CharFilterFactoryFactory charFilterFactoryFactory = entry.getValue();
Settings charFilterSettings = charFiltersSettings.get(charFilterName);
if (charFilterSettings == null) {
charFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
CharFilterFactory tokenFilterFactory = charFilterFactoryFactory.create(charFilterName, charFilterSettings);
charFilters.put(charFilterName, tokenFilterFactory);
charFilters.put(Strings.toCamelCase(charFilterName), tokenFilterFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltCharFilterFactoryFactory> entry : indicesAnalysisService.charFilterFactories().entrySet()) {
String name = entry.getKey();
if (!charFilters.containsKey(name)) {
charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!charFilters.containsKey(name)) {
charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.charFilters = ImmutableMap.copyOf(charFilters);
Map<String, TokenFilterFactory> tokenFilters = newHashMap();
if (tokenFilterFactoryFactories != null) {
Map<String, Settings> tokenFiltersSettings = indexSettings.getGroups("index.analysis.filter");
for (Map.Entry<String, TokenFilterFactoryFactory> entry : tokenFilterFactoryFactories.entrySet()) {
String tokenFilterName = entry.getKey();
TokenFilterFactoryFactory tokenFilterFactoryFactory = entry.getValue();
Settings tokenFilterSettings = tokenFiltersSettings.get(tokenFilterName);
if (tokenFilterSettings == null) {
tokenFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
TokenFilterFactory tokenFilterFactory = tokenFilterFactoryFactory.create(tokenFilterName, tokenFilterSettings);
tokenFilters.put(tokenFilterName, tokenFilterFactory);
tokenFilters.put(Strings.toCamelCase(tokenFilterName), tokenFilterFactory);
}
}
// pre initialize the globally registered ones into the map
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltTokenFilterFactoryFactory> entry : indicesAnalysisService.tokenFilterFactories().entrySet()) {
String name = entry.getKey();
if (!tokenFilters.containsKey(name)) {
tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!tokenFilters.containsKey(name)) {
tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.tokenFilters = ImmutableMap.copyOf(tokenFilters);
Map<String, AnalyzerProvider> analyzerProviders = newHashMap();
if (analyzerFactoryFactories != null) {
Map<String, Settings> analyzersSettings = indexSettings.getGroups("index.analysis.analyzer");
for (Map.Entry<String, AnalyzerProviderFactory> entry : analyzerFactoryFactories.entrySet()) {
String analyzerName = entry.getKey();
AnalyzerProviderFactory analyzerFactoryFactory = entry.getValue();
Settings analyzerSettings = analyzersSettings.get(analyzerName);
if (analyzerSettings == null) {
analyzerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
AnalyzerProvider analyzerFactory = analyzerFactoryFactory.create(analyzerName, analyzerSettings);
analyzerProviders.put(analyzerName, analyzerFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltAnalyzerProviderFactory> entry : indicesAnalysisService.analyzerProviderFactories().entrySet()) {
String name = entry.getKey();
if (!analyzerProviders.containsKey(name)) {
analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!analyzerProviders.containsKey(name)) {
analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
if (!analyzerProviders.containsKey("default")) {
analyzerProviders.put("default", new StandardAnalyzerProvider(index, indexSettings, null, "default", ImmutableSettings.Builder.EMPTY_SETTINGS));
}
if (!analyzerProviders.containsKey("default_index")) {
analyzerProviders.put("default_index", analyzerProviders.get("default"));
}
if (!analyzerProviders.containsKey("default_search")) {
analyzerProviders.put("default_search", analyzerProviders.get("default"));
}
if (!analyzerProviders.containsKey("default_search_quoted")) {
analyzerProviders.put("default_search_quoted", analyzerProviders.get("default_search"));
}
Map<String, NamedAnalyzer> analyzers = newHashMap();
for (AnalyzerProvider analyzerFactory : analyzerProviders.values()) {
if (analyzerFactory instanceof CustomAnalyzerProvider) {
((CustomAnalyzerProvider) analyzerFactory).build(this);
}
Analyzer analyzerF = analyzerFactory.get();
if (analyzerF == null) {
throw new ElasticSearchIllegalArgumentException("analyzer [" + analyzerFactory.name() + "] created null analyzer");
}
NamedAnalyzer analyzer;
// if we got a named analyzer back, use it...
if (analyzerF instanceof NamedAnalyzer) {
analyzer = (NamedAnalyzer) analyzerF;
} else {
analyzer = new NamedAnalyzer(analyzerFactory.name(), analyzerFactory.scope(), analyzerF);
}
analyzers.put(analyzerFactory.name(), analyzer);
analyzers.put(Strings.toCamelCase(analyzerFactory.name()), analyzer);
String strAliases = indexSettings.get("index.analysis.analyzer." + analyzerFactory.name() + ".alias");
if (strAliases != null) {
for (String alias : Strings.commaDelimitedListToStringArray(strAliases)) {
analyzers.put(alias, analyzer);
}
}
String[] aliases = indexSettings.getAsArray("index.analysis.analyzer." + analyzerFactory.name() + ".alias");
for (String alias : aliases) {
analyzers.put(alias, analyzer);
}
}
defaultAnalyzer = analyzers.get("default");
if (defaultAnalyzer == null) {
throw new ElasticSearchIllegalArgumentException("no default analyzer configured");
}
defaultIndexAnalyzer = analyzers.containsKey("default_index") ? analyzers.get("default_index") : analyzers.get("default");
defaultSearchAnalyzer = analyzers.containsKey("default_search") ? analyzers.get("default_search") : analyzers.get("default");
defaultSearchQuoteAnalyzer = analyzers.containsKey("default_search_quote") ? analyzers.get("default_search_quote") : defaultSearchAnalyzer;
this.analyzers = ImmutableMap.copyOf(analyzers);
}
public void close() {
for (NamedAnalyzer analyzer : analyzers.values()) {
if (analyzer.scope() == AnalyzerScope.INDEX) {
try {
analyzer.close();
} catch (NullPointerException e) {
// because analyzers are aliased, they might be closed several times
// an NPE is thrown in this case, so ignore....
} catch (Exception e) {
logger.debug("failed to close analyzer " + analyzer);
}
}
}
}
public NamedAnalyzer analyzer(String name) {
return analyzers.get(name);
}
public NamedAnalyzer defaultAnalyzer() {
return defaultAnalyzer;
}
public NamedAnalyzer defaultIndexAnalyzer() {
return defaultIndexAnalyzer;
}
public NamedAnalyzer defaultSearchAnalyzer() {
return defaultSearchAnalyzer;
}
public NamedAnalyzer defaultSearchQuoteAnalyzer() {
return defaultSearchQuoteAnalyzer;
}
public TokenizerFactory tokenizer(String name) {
return tokenizers.get(name);
}
public CharFilterFactory charFilter(String name) {
return charFilters.get(name);
}
public TokenFilterFactory tokenFilter(String name) {
return tokenFilters.get(name);
}
}
| Java |
<?php
/**
* Smarty Internal Plugin Compile Make_Nocache
* Compiles the {make_nocache} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Make_Nocache Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Make_Nocache extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $option_flags = [];
/**
* Array of names of required attribute required by tag
*
* @var array
*/
public $required_attributes = ['var'];
/**
* Shorttag attribute order defined by its names
*
* @var array
*/
public $shorttag_order = ['var'];
/**
* Compiles code for the {make_nocache} tag
*
* @param array $args array with attributes from parser
* @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
* @throws \SmartyCompilerException
*/
public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($compiler->template->caching) {
$output = "<?php \$_smarty_tpl->smarty->ext->_make_nocache->save(\$_smarty_tpl, {$_attr[ 'var' ]});\n?>\n";
$compiler->has_code = true;
$compiler->suppressNocacheProcessing = true;
return $output;
} else {
return true;
}
}
}
| Java |
<?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>.
*/
// spanish translation: Salva Gómez <salva.gomez at gmail.com>, 2015
$mess=array(
"Generic Conf Features" => "Configuraciones genéricas",
"Let user create repositories" => "Permitir al usuario crear repositorios",
"Remember guest preferences" => "Recordar preferencias de invitado",
"If the 'guest' user is enabled, remember her preferences accross sessions." => "Si el usuario 'Invitado' está habilitado, recordar sus preferencias a través de sesiones.",
"Configurations Management" => "Gestión de configuraciones",
"Sets how the application core data (users,roles,etc) is stored." => "Establece cómo se almacenan los datos básicos de aplicación (usuarios, roles, etc.)",
"Default start repository" => "Repositorio de inicio por defecto",
"Default repository" => "Repositorio por defecto",
"Maximum number of shared users per user" => "Número máximo de usuarios compartidos por usuario",
"Shared users limit" => "Límite de usuarios compartidos",
"Core SQL Connexion" => "Conexión SQL Principal",
"SQL Connexion" => "Conexión SQL",
"Simple SQL Connexion definition that can be used by other sql-based plugins" => "Definición de conexión SQL simple que puede ser utilizada por otros plugins basados en SQL",
"Preferences Saving" => "Preferencias de guardado",
"Skip user history" => "Omitir preferencias de interfaz",
"Use this option to avoid automatic reloading of the interface state (last folder, opened tabs, etc)" => "Utilice esta opción para evitar la carga automática del estado de la interfaz (última carpeta, pestañas abiertas, etc)",
"Internal / External Users" => "Usuarios internos / externos",
"Maximum number of users displayed in the users autocompleter" => "Número máximo de usuarios mostrados en la lista autocompletada de usuarios",
"Users completer limit" => "Límite del completador de usuarios",
"Minimum number of characters to trigger the auto completion feature" => "Número mínimo de caracteres para activar la función de autocompletado",
"Users completer min chars" => "Número mínimo de caracteres del completador de usuarios",
"Do not display real login in parenthesis" => "No mostrar el nombre de inicio de sesión real entre paréntesis",
"Hide real login" => "Ocultar nombre de inicio de sesión real",
"See existing users" => "Ver usuarios existentes",
"Allow the users to pick an existing user when sharing a folder" => "Permitir a los usuarios elegir un usuario existente al compartir una carpeta",
"Create external users" => "Crear usuarios externos",
"Allow the users to create a new user when sharing a folder" => "Permitir a los usuarios crear un nuevo usuario al compartir una carpeta",
"External users parameters" => "Parámetros de usuarios externos",
"List of parameters to be edited when creating a new shared user." => "Lista de parámetros a editar al crear un nuevo usuario compartido.",
"Configuration Store Instance" => "Instancia de almacenamiento de la configuración",
"Instance" => "Instancia",
"Choose the configuration plugin" => "Seleccionar el plugin de configuración",
"Name" => "Nombre",
"Full name displayed to others" => "Mostrar el nombre completo a los demás",
"Avatar" => "Avatar",
"Image displayed next to the user name" => "Imágen mostrada junto al nombre de usuario",
"Email" => "Correo electrónico",
"Address used for notifications" => "Dirección utilizada para las notificaciones",
"Country" => "País",
"Language" => "Idioma",
"User Language" => "Idioma del usuario",
"Role Label" => "Etiqueta de rol",
"Users Lock Action" => "Acción de bloqueo de usuarios",
"If set, this action will be triggered automatically at users login. Can be logout (to lock out the users), pass_change (to force password change), or anything else" => "Si se establece, esta acción se activará automáticamente en el inicio de sesión de los usuarios. Puede ser cerrar la sesión (para bloquear a los usuarios), cambiar contraseña (para forzar el cambio de contraseña), o cualquier otra cosa",
"Worskpace creation delegation" => "Delegación de la creación de repositorios",
"Let user create repositories from templates" => "Permitir al usuario crear repositorios usando plantillas",
"Whether users can create their own repositories, based on predefined templates." => "Si los usuarios pueden crear sus propios repositorios, hacerlo basándose en plantillas predefinidas.",
"Users Directory Listing" => "Listado del directorio de usuarios",
"Share with existing users from all groups" => "Compartir con los usuarios existentes de todos los grupos",
"Allow to search users from other groups through auto completer (can be handy if previous option is set to false) and share workspaces with them" => "Permitir de buscar usuarios de otros grupos a través de autocompletar (puede ser útil si la opción anterior se establece en False) y compartir repositorios con ellos",
"List existing from all groups" => "Listar existentes de todos los grupos",
"If previous option is set to True, directly display a full list of users from all groups" => "Si la opción anterior se establece en True, mostrar directamente una lista completa de los usuarios de todos los grupos",
"Roles / Groups Directory Listing" => "Listado de roles / directorio de grupos",
"Display roles and/or groups" => "Mostrar roles y/o grupos",
"Users only (do not list groups nor roles)" => "Sólo usuarios (no listar grupos ni roles)",
"Allow Group Listing" => "Permitir el listado de grupos",
"Allow Role Listing" => "Permitir el listado de roles",
"Role/Group Listing" => "Listado de roles/grupos",
"List Roles By" => "Listar roles por",
"All roles" => "Todos los roles",
"User roles only" => "Sólo roles de usuario",
"role prefix" => "Prefijo del rol",
"Excluded Roles" => "Roles excluidos",
"Included Roles" => "Roles incluidos",
"Some roles should be disappered in the list. list separated by ',' or start with 'preg:' for regex." => "Roles ocultos en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.",
"Some roles should be shown in the list. list separated by ',' or start with 'preg:' for regex." => "Roles que deben mostrarse en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.",
"External Users Creation" => "Creación de usuarios externos",
"Always override other roles, included group roles." => "Ignorar siempre otros roles, incluido los roles de grupo.",
"Always Override" => "Ignorar Siempre",
"Do not load groups and users list if no regexp is entered. Avoid sending large search on LDAP." => "No cargar la lista de grupos y usuarios si no se introduce una regexp. Evita enviar búsquedas largas a LDAP.",
"Make regexp mandatory" => "Regexp obligatorio",
);
| Java |
<!-- title: crm -->
<div class="dev-header">
<a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;">
Version 6.7.7</a>
<a class="btn btn-default btn-sm" href="https://github.com/frappe/erpnext/tree/develop/crm"
target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a>
</div>
<h3>Package Contents</h3>
{index}
<!-- autodoc --> | Java |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Profiler;
use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
/**
* Profile.
*
* @author Fabien Potencier <[email protected]>
*/
class Profile
{
private $token;
/**
* @var DataCollectorInterface[]
*/
private $collectors = array();
private $ip;
private $method;
private $url;
private $time;
/**
* @var Profile
*/
private $parent;
/**
* @var Profile[]
*/
private $children = array();
/**
* Constructor.
*
* @param string $token The token
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* Returns the parent profile.
*
* @return Profile The parent profile
*/
public function getParent()
{
return $this->parent;
}
/**
* Sets the parent token
*
* @param Profile $parent The parent Profile
*/
public function setParent( Profile $parent )
{
$this->parent = $parent;
}
/**
* Returns the parent token.
*
* @return null|string The parent token
*/
public function getParentToken()
{
return $this->parent ? $this->parent->getToken() : null;
}
/**
* Gets the token.
*
* @return string The token
*/
public function getToken()
{
return $this->token;
}
/**
* Sets the token.
*
* @param string $token The token
*/
public function setToken( $token )
{
$this->token = $token;
}
/**
* Returns the IP.
*
* @return string The IP
*/
public function getIp()
{
return $this->ip;
}
/**
* Sets the IP.
*
* @param string $ip
*/
public function setIp($ip)
{
$this->ip = $ip;
}
/**
* Returns the request method.
*
* @return string The request method
*/
public function getMethod()
{
return $this->method;
}
public function setMethod($method)
{
$this->method = $method;
}
/**
* Returns the URL.
*
* @return string The URL
*/
public function getUrl()
{
return $this->url;
}
public function setUrl($url)
{
$this->url = $url;
}
/**
* Returns the time.
*
* @return string The time
*/
public function getTime()
{
if (null === $this->time) {
return 0;
}
return $this->time;
}
public function setTime($time)
{
$this->time = $time;
}
/**
* Finds children profilers.
*
* @return Profile[] An array of Profile
*/
public function getChildren()
{
return $this->children;
}
/**
* Sets children profiler.
*
* @param Profile[] $children An array of Profile
*/
public function setChildren(array $children)
{
$this->children = array();
foreach ($children as $child) {
$this->addChild($child);
}
}
/**
* Adds the child token
*
* @param Profile $child The child Profile
*/
public function addChild(Profile $child)
{
$this->children[] = $child;
$child->setParent($this);
}
/**
* Gets a Collector by name.
*
* @param string $name A collector name
*
* @return DataCollectorInterface A DataCollectorInterface instance
*
* @throws \InvalidArgumentException if the collector does not exist
*/
public function getCollector($name)
{
if (!isset($this->collectors[$name])) {
throw new \InvalidArgumentException(sprintf('Collector "%s" does not exist.', $name));
}
return $this->collectors[$name];
}
/**
* Gets the Collectors associated with this profile.
*
* @return DataCollectorInterface[]
*/
public function getCollectors()
{
return $this->collectors;
}
/**
* Sets the Collectors associated with this profile.
*
* @param DataCollectorInterface[] $collectors
*/
public function setCollectors(array $collectors)
{
$this->collectors = array();
foreach ($collectors as $collector) {
$this->addCollector($collector);
}
}
/**
* Adds a Collector.
*
* @param DataCollectorInterface $collector A DataCollectorInterface instance
*/
public function addCollector(DataCollectorInterface $collector)
{
$this->collectors[$collector->getName()] = $collector;
}
/**
* Returns true if a Collector for the given name exists.
*
* @param string $name A collector name
*
* @return bool
*/
public function hasCollector($name)
{
return isset($this->collectors[$name]);
}
public function __sleep()
{
return array('token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time');
}
}
| Java |
# session module tests
#
# Copyright (C) 2012-2013 Mohammed Morsi <[email protected]>
# Licensed under the AGPLv3 http://www.gnu.org/licenses/agpl.txt
require 'spec_helper'
require 'timecop'
require 'users/session'
module Users
describe Session do
after(:all) do
Timecop.return
end
describe "#initialize" do
it "sets attributes" do
id = Motel.gen_uuid
u = User.new :id => 'user1'
s = Session.new :id => id, :user => u, :endpoint_id => 'node1'
s.id.should == id
s.user.id.should == 'user1'
s.refreshed_time.should_not be_nil
s.endpoint_id.should == 'node1'
end
end
describe "#timed_out" do
before(:each) do
Timecop.freeze
@u = User.new :id => 'user1'
@s = Session.new :id => 'id', :user => @u
end
after(:each) do
Timecop.travel
end
context "timeout has passed" do
it "returns true" do
Timecop.freeze Session::SESSION_EXPIRATION + 1
@s.timed_out?.should be_true
end
end
context "timeout has not passed" do
it "returns false" do
@s.timed_out?.should be_false
@s.instance_variable_get(:@refreshed_time).should == Time.now
end
end
context "user is permenant" do
it "always returns false" do
@u.permenant = true
Timecop.freeze Session::SESSION_EXPIRATION + 1
@s.timed_out?.should be_false
end
end
end
describe "#to_json" do
it "returns json representation of session" do
u = User.new :id => 'user1'
s = Session.new :id => '1234', :user => u, :endpoint_id => 'node1'
j = s.to_json
j.should include('"json_class":"Users::Session"')
j.should include('"id":"1234"')
j.should include('"json_class":"Users::User"')
j.should include('"id":"user1"')
j.should include('"refreshed_time":')
j.should include('"endpoint_id":"node1"')
end
end
describe "#json_create" do
it "returns session from json format" do
j = '{"json_class":"Users::Session","data":{"user":{"json_class":"Users::User","data":{"id":"user1","email":null,"roles":null,"permenant":false,"npc":false,"attributes":null,"password":null,"registration_code":null}},"id":"1234","refreshed_time":"2013-05-30 00:43:54 -0400"}}'
s = ::RJR::JSONParser.parse(j)
s.class.should == Users::Session
s.id.should == "1234"
s.user.id.should == 'user1'
s.refreshed_time.should_not be_nil
end
end
end # describe Session
end # module Users
| Java |
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' },
block: { id: 'account.block', defaultMessage: 'Block @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
open: { id: 'status.open', defaultMessage: 'Expand this status' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
});
@injectIntl
export default class StatusActionBar extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onMention: PropTypes.func,
onMute: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onMuteConversation: PropTypes.func,
me: PropTypes.number.isRequired,
withDismiss: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
// Avoid checking props that are functions (and whose equality will always
// evaluate to false. See react-immutable-pure-component for usage.
updateOnProps = [
'status',
'me',
'withDismiss',
]
handleReplyClick = () => {
this.props.onReply(this.props.status, this.context.router.history);
}
handleFavouriteClick = () => {
this.props.onFavourite(this.props.status);
}
handleReblogClick = (e) => {
this.props.onReblog(this.props.status, e);
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router.history);
}
handleMuteClick = () => {
this.props.onMute(this.props.status.get('account'));
}
handleBlockClick = () => {
this.props.onBlock(this.props.status.get('account'));
}
handleOpen = () => {
this.context.router.history.push(`/statuses/${this.props.status.get('id')}`);
}
handleReport = () => {
this.props.onReport(this.props.status);
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
render () {
const { status, me, intl, withDismiss } = this.props;
const reblogDisabled = status.get('visibility') === 'private' || status.get('visibility') === 'direct';
const mutingConversation = status.get('muted');
let menu = [];
let reblogIcon = 'retweet';
let replyIcon;
let replyTitle;
menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen });
menu.push(null);
if (withDismiss) {
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
}
if (status.getIn(['account', 'id']) === me) {
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick });
menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick });
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
}
if (status.get('visibility') === 'direct') {
reblogIcon = 'envelope';
} else if (status.get('visibility') === 'private') {
reblogIcon = 'lock';
}
if (status.get('in_reply_to_id', null) === null) {
replyIcon = 'reply';
replyTitle = intl.formatMessage(messages.reply);
} else {
replyIcon = 'reply-all';
replyTitle = intl.formatMessage(messages.replyAll);
}
return (
<div className='status__action-bar'>
<IconButton className='status__action-bar-button' title={replyTitle} icon={replyIcon} onClick={this.handleReplyClick} />
<IconButton className='status__action-bar-button' disabled={reblogDisabled} active={status.get('reblogged')} title={reblogDisabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} />
<IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} />
<div className='status__action-bar-dropdown'>
<DropdownMenu items={menu} icon='ellipsis-h' size={18} direction='right' ariaLabel='More' />
</div>
</div>
);
}
}
| Java |
# -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from shoop.admin.form_part import FormPart, TemplatedFormDef
from shoop.core.models import Shop
from shoop.discount_pricing.models import DiscountedProductPrice
class DiscountPricingForm(forms.Form):
def __init__(self, **kwargs):
self.product = kwargs.pop("product")
super(DiscountPricingForm, self).__init__(**kwargs)
self.shops = []
if self.product:
self._build_fields()
def _build_fields(self):
self.shops = list(Shop.objects.all())
prices_by_shop_and_group = dict(
(shop_id, price)
for (shop_id, price)
in DiscountedProductPrice.objects.filter(product=self.product)
.values_list("shop_id", "price_value")
)
for shop in self.shops:
name = self._get_field_name(shop)
price = prices_by_shop_and_group.get(shop.id)
price_field = forms.DecimalField(
min_value=0, initial=price,
label=_("Price (%s)") % shop, required=False
)
self.fields[name] = price_field
def _get_field_name(self, shop):
return "s_%d" % shop.id
def _process_single_save(self, shop):
name = self._get_field_name(shop)
value = self.cleaned_data.get(name)
clear = (value is None or value < 0)
if clear:
DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete()
else:
(spp, created) = DiscountedProductPrice.objects.get_or_create(
product=self.product, shop=shop,
defaults={'price_value': value})
if not created:
spp.price_value = value
spp.save()
def save(self):
if not self.has_changed(): # No changes, so no need to do anything.
return
for shop in self.shops:
self._process_single_save(shop)
def get_shop_field(self, shop):
name = self._get_field_name(shop)
return self[name]
class DiscountPricingFormPart(FormPart):
priority = 10
def get_form_defs(self):
yield TemplatedFormDef(
name="discount_pricing",
form_class=DiscountPricingForm,
template_name="shoop/admin/discount_pricing/form_part.jinja",
required=False,
kwargs={"product": self.object}
)
def form_valid(self, form):
form["discount_pricing"].save()
| Java |
/*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* 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 theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at [email protected]).
*
* 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: [email protected]
******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.03 at 10:12:07 AM MEZ
//
package com.lp.server.schema.opentrans.cc.orderresponse;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for _XML_XML_COST_CATEGORY_ID complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="_XML_XML_COST_CATEGORY_ID">
* <simpleContent>
* <extension base="<http://www.opentrans.org/XMLSchema/1.0>typeCOST_CATEGORY_ID">
* <attGroup ref="{http://www.opentrans.org/XMLSchema/1.0}ComIbmMrmNamespaceInfo154"/>
* <attribute name="type">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <minLength value="1"/>
* <maxLength value="32"/>
* <enumeration value="cost_center"/>
* <enumeration value="project"/>
* </restriction>
* </simpleType>
* </attribute>
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "_XML_XML_COST_CATEGORY_ID", propOrder = {
"value"
})
public class XMLXMLCOSTCATEGORYID {
@XmlValue
protected String value;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String type;
@XmlAttribute(name = "xsi_schemaLocation")
protected String xsiSchemaLocation;
@XmlAttribute(name = "xmlns_xsd")
protected String xmlnsXsd;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the xsiSchemaLocation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXsiSchemaLocation() {
if (xsiSchemaLocation == null) {
return "openbase_1_0.mxsd";
} else {
return xsiSchemaLocation;
}
}
/**
* Sets the value of the xsiSchemaLocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXsiSchemaLocation(String value) {
this.xsiSchemaLocation = value;
}
/**
* Gets the value of the xmlnsXsd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlnsXsd() {
if (xmlnsXsd == null) {
return "http://www.w3.org/2001/XMLSchema";
} else {
return xmlnsXsd;
}
}
/**
* Sets the value of the xmlnsXsd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlnsXsd(String value) {
this.xmlnsXsd = value;
}
}
| Java |
-- uncomment for testing
/*
DECLARE @id int = 1
*/
SELECT * FROM Products WHERE Id = @id
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>api Package — ally-py 1.0b1 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
VERSION: '1.0b1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="ally-py 1.0b1 documentation" href="index.html" />
<link rel="up" title="person Package" href="superdesk.person.html" />
<link rel="next" title="impl Package" href="superdesk.person.impl.html" />
<link rel="prev" title="person Package" href="superdesk.person.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="superdesk.person.impl.html" title="impl Package"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="superdesk.person.html" title="person Package"
accesskey="P">previous</a> |</li>
<li><a href="index.html">ally-py 1.0b1 documentation</a> »</li>
<li><a href="superdesk.html" >superdesk Package</a> »</li>
<li><a href="superdesk.person.html" accesskey="U">person Package</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="api-package">
<h1>api Package<a class="headerlink" href="#api-package" title="Permalink to this headline">¶</a></h1>
<div class="section" id="person-module">
<h2><tt class="xref py py-mod docutils literal"><span class="pre">person</span></tt> Module<a class="headerlink" href="#person-module" title="Permalink to this headline">¶</a></h2>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">api Package</a><ul>
<li><a class="reference internal" href="#person-module"><tt class="docutils literal"><span class="pre">person</span></tt> Module</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="superdesk.person.html"
title="previous chapter">person Package</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="superdesk.person.impl.html"
title="next chapter">impl Package</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/superdesk.person.api.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="superdesk.person.impl.html" title="impl Package"
>next</a> |</li>
<li class="right" >
<a href="superdesk.person.html" title="person Package"
>previous</a> |</li>
<li><a href="index.html">ally-py 1.0b1 documentation</a> »</li>
<li><a href="superdesk.html" >superdesk Package</a> »</li>
<li><a href="superdesk.person.html" >person Package</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2012, Gabriel Nistor.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html> | Java |
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2019. (c) 2019.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
*
************************************************************************
*/
package org.opencadc.proxy;
import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.reg.client.RegistryClient;
import java.net.URI;
import java.net.URL;
import org.junit.Test;
import org.junit.Assert;
import static org.mockito.Mockito.*;
public class ProxyServletTest {
@Test
public void lookupServiceURL() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "cookie");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.COOKIE,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
Assert.assertEquals("URLs do not match.", lookedUpServiceURL, result);
}
@Test
public void lookupServiceURLWithPath() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon");
serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.ANON,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
final URL expected = new URL("https://www.services.com/myservice/alt-site");
Assert.assertEquals("URLs do not match.", expected, result);
}
@Test
public void lookupServiceURLWithPathQuery() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon");
serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site");
serviceParameterMap.put(ServiceParameterName.EXTRA_QUERY, "myquery=a&g=j");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.ANON,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
final URL expected = new URL("https://www.services.com/myservice/alt-site?myquery=a&g=j");
Assert.assertEquals("URLs do not match.", expected, result);
}
}
| Java |
import ITEM_QUALITIES from '../ITEM_QUALITIES';
export default {
// Shared legendaries
SOUL_OF_THE_SHADOWBLADE: {
id: 150936,
name: 'Soul of the Shadowblade',
icon: 'inv_jewelry_ring_56',
quality: ITEM_QUALITIES.LEGENDARY,
},
MANTLE_OF_THE_MASTER_ASSASSIN: {
id: 144236,
name: 'Mantle of the Master Assassin',
icon: 'inv_shoulder_leather_raidrogue_k_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
INSIGNIA_OF_RAVENHOLDT: {
id: 137049,
name: 'Insignia of Ravenholdt',
icon: 'inv_misc_epicring_a2',
quality: ITEM_QUALITIES.LEGENDARY,
},
WILL_OF_VALEERA: {
id: 137069,
name: 'Will of Valeera',
icon: 'inv_pants_cloth_02',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_DREADLORDS_DECEIT: {
id: 137021,
name: 'The Dreadlord\'s Deceit',
icon: 'inv_cape_pandaria_d_03',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Assassination legendaries
DUSKWALKERS_FOOTPADS: {
id: 137030,
name: 'Duskwalker\'s Footpads',
icon: 'inv_boots_leather_8',
quality: ITEM_QUALITIES.LEGENDARY,
},
ZOLDYCK_FAMILY_TRAINING_SHACKLES: {
id: 137098,
name: 'Zoldyck Family Training Shackles',
icon: 'inv_bracer_leather_raiddruid_i_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_EMPTY_CROWN: {
id: 151815,
name: 'The Empty Crown',
icon: 'inv_crown_02',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Outlaw legendaries
THRAXIS_TRICKSY_TREADS: {
id: 137031,
name: 'Thraxi\'s Tricksy Treads',
icon: 'inv_boots_leather_03a',
quality: ITEM_QUALITIES.LEGENDARY,
},
GREENSKINS_WATERLOGGED_WRISTCUFFS: {
id: 137099,
name: 'Greenskin\'s Waterlogged Wristcuffs',
icon: 'inv_bracer_leather_raidrogue_k_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
SHIVARRAN_SYMMETRY: {
id: 141321,
name: 'Shivarran Symmetry',
icon: 'inv_gauntlets_83',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_CURSE_OF_RESTLESSNESS: {
id: 151817,
name: 'The Curse of Restlessness',
icon: 'inv_qiraj_draperegal',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Subtlety legendaries
SHADOW_SATYRS_WALK: {
id: 137032,
name: 'Shadow Satyr\'s Walk',
icon: 'inv_boots_mail_dungeonmail_c_04',
quality: ITEM_QUALITIES.LEGENDARY,
},
DENIAL_OF_THE_HALF_GIANTS: {
id: 137100,
name: 'Denial of the Half-Giants',
icon: 'inv_bracer_leather_panda_b_02_crimson',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_FIRST_OF_THE_DEAD: {
id: 151818,
name: 'The First of the Dead',
icon: 'inv_glove_cloth_raidwarlockmythic_q_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
};
| Java |
module Merb::Maintainer::BillingHelper
def get_stats(metric, dom)
today = Date.today
date_this_month = Date.new(today.year, today.month, dom)
data = []
data_length = 30
data << get_stat(metric, date_this_month) if dom < today.mday
(1..(data_length-data.length)).each do |i|
date = date_this_month << i
data << get_stat(metric, date)
end
data
end
# to add a new metric to the billing section, add a case below
def get_stat(metric, date)
case metric
when "active_loans"
count = repository.adapter.query(%Q{
SELECT COUNT(date) FROM loan_history lh,
(SELECT max(date) AS mdt, loan_id FROM loan_history lh2 WHERE date <= '#{date.strftime}' GROUP BY loan_id) AS md
WHERE lh.date = md.mdt AND lh.loan_id = md.loan_id AND lh.status IN (2,4,5,6);
}).first
when "total_loans"
count = Loan.count(:applied_on.lte => date)
when "total_clients"
count = Client.count(:date_joined.lte => date)
end
{
:date => date.strftime(DATE_FORMAT_READABLE),
:count => count
}
end
end
| Java |
/***************************************************************************
constraintteachersmaxgapsperdayform.cpp - description
-------------------
begin : Jan 21, 2008
copyright : (C) 2008 by Lalescu Liviu
email : Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <QMessageBox>
#include "longtextmessagebox.h"
#include "constraintteachersmaxgapsperdayform.h"
#include "addconstraintteachersmaxgapsperdayform.h"
#include "modifyconstraintteachersmaxgapsperdayform.h"
#include <QListWidget>
#include <QScrollBar>
#include <QAbstractItemView>
ConstraintTeachersMaxGapsPerDayForm::ConstraintTeachersMaxGapsPerDayForm(QWidget* parent): QDialog(parent)
{
setupUi(this);
currentConstraintTextEdit->setReadOnly(true);
modifyConstraintPushButton->setDefault(true);
constraintsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
connect(constraintsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int)));
connect(addConstraintPushButton, SIGNAL(clicked()), this, SLOT(addConstraint()));
connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
connect(removeConstraintPushButton, SIGNAL(clicked()), this, SLOT(removeConstraint()));
connect(modifyConstraintPushButton, SIGNAL(clicked()), this, SLOT(modifyConstraint()));
connect(constraintsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint()));
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
this->filterChanged();
}
ConstraintTeachersMaxGapsPerDayForm::~ConstraintTeachersMaxGapsPerDayForm()
{
saveFETDialogGeometry(this);
}
bool ConstraintTeachersMaxGapsPerDayForm::filterOk(TimeConstraint* ctr)
{
if(ctr->type==CONSTRAINT_TEACHERS_MAX_GAPS_PER_DAY)
return true;
else
return false;
}
void ConstraintTeachersMaxGapsPerDayForm::filterChanged()
{
this->visibleConstraintsList.clear();
constraintsListWidget->clear();
for(int i=0; i<gt.rules.timeConstraintsList.size(); i++){
TimeConstraint* ctr=gt.rules.timeConstraintsList[i];
if(filterOk(ctr)){
visibleConstraintsList.append(ctr);
constraintsListWidget->addItem(ctr->getDescription(gt.rules));
}
}
if(constraintsListWidget->count()>0)
constraintsListWidget->setCurrentRow(0);
else
constraintChanged(-1);
}
void ConstraintTeachersMaxGapsPerDayForm::constraintChanged(int index)
{
if(index<0){
currentConstraintTextEdit->setPlainText("");
return;
}
assert(index<this->visibleConstraintsList.size());
TimeConstraint* ctr=this->visibleConstraintsList.at(index);
assert(ctr!=NULL);
currentConstraintTextEdit->setPlainText(ctr->getDetailedDescription(gt.rules));
}
void ConstraintTeachersMaxGapsPerDayForm::addConstraint()
{
AddConstraintTeachersMaxGapsPerDayForm form(this);
setParentAndOtherThings(&form, this);
form.exec();
filterChanged();
constraintsListWidget->setCurrentRow(constraintsListWidget->count()-1);
}
void ConstraintTeachersMaxGapsPerDayForm::modifyConstraint()
{
int valv=constraintsListWidget->verticalScrollBar()->value();
int valh=constraintsListWidget->horizontalScrollBar()->value();
int i=constraintsListWidget->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this->visibleConstraintsList.at(i);
ModifyConstraintTeachersMaxGapsPerDayForm form(this, (ConstraintTeachersMaxGapsPerDay*)ctr);
setParentAndOtherThings(&form, this);
form.exec();
filterChanged();
constraintsListWidget->verticalScrollBar()->setValue(valv);
constraintsListWidget->horizontalScrollBar()->setValue(valh);
if(i>=constraintsListWidget->count())
i=constraintsListWidget->count()-1;
if(i>=0)
constraintsListWidget->setCurrentRow(i);
else
this->constraintChanged(-1);
}
void ConstraintTeachersMaxGapsPerDayForm::removeConstraint()
{
int i=constraintsListWidget->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this->visibleConstraintsList.at(i);
QString s;
s=tr("Remove constraint?");
s+="\n\n";
s+=ctr->getDetailedDescription(gt.rules);
QListWidgetItem* item;
switch( LongTextMessageBox::confirmation( this, tr("FET confirmation"),
s, tr("Yes"), tr("No"), 0, 0, 1 ) ){
case 0: // The user clicked the OK button or pressed Enter
gt.rules.removeTimeConstraint(ctr);
visibleConstraintsList.removeAt(i);
constraintsListWidget->setCurrentRow(-1);
item=constraintsListWidget->takeItem(i);
delete item;
break;
case 1: // The user clicked the Cancel button or pressed Escape
break;
}
if(i>=constraintsListWidget->count())
i=constraintsListWidget->count()-1;
if(i>=0)
constraintsListWidget->setCurrentRow(i);
else
this->constraintChanged(-1);
}
| Java |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
import base64
import netsvc
from osv import osv
from osv import fields
from tools.translate import _
import tools
def _reopen(self, wizard_id, res_model, res_id):
return {'type': 'ir.actions.act_window',
'view_mode': 'form',
'view_type': 'form',
'res_id': wizard_id,
'res_model': self._name,
'target': 'new',
# save original model in context, otherwise
# it will be lost on the action's context switch
'context': {'mail.compose.target.model': res_model,
'mail.compose.target.id': res_id,}
}
class mail_compose_message(osv.osv_memory):
_inherit = 'mail.compose.message'
def _get_templates(self, cr, uid, context=None):
"""
Return Email Template of particular Model.
"""
if context is None:
context = {}
record_ids = []
email_template= self.pool.get('email.template')
model = False
if context.get('message_id'):
mail_message = self.pool.get('mail.message')
message_data = mail_message.browse(cr, uid, int(context.get('message_id')), context)
model = message_data.model
elif context.get('mail.compose.target.model') or context.get('active_model'):
model = context.get('mail.compose.target.model', context.get('active_model'))
if model:
record_ids = email_template.search(cr, uid, [('model', '=', model)])
return email_template.name_get(cr, uid, record_ids, context) + [(False,'')]
return []
_columns = {
'use_template': fields.boolean('Use Template'),
'template_id': fields.selection(_get_templates, 'Template',
size=-1 # means we want an int db column
),
}
_defaults = {
'template_id' : lambda self, cr, uid, context={} : context.get('mail.compose.template_id', False)
}
def on_change_template(self, cr, uid, ids, use_template, template_id, email_from=None, email_to=None, context=None):
if context is None:
context = {}
values = {}
if template_id:
res_id = context.get('mail.compose.target.id') or context.get('active_id') or False
if context.get('mail.compose.message.mode') == 'mass_mail':
# use the original template values - to be rendered when actually sent
# by super.send_mail()
values = self.pool.get('email.template').read(cr, uid, template_id, self.fields_get_keys(cr, uid), context)
report_xml_pool = self.pool.get('ir.actions.report.xml')
template = self.pool.get('email.template').get_email_template(cr, uid, template_id, res_id, context)
values['attachments'] = False
attachments = {}
if template.report_template:
report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
# Ensure report is rendered using template's language
ctx = context.copy()
if template.lang:
ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context)
service = netsvc.LocalService(report_service)
(result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)
result = base64.b64encode(result)
if not report_name:
report_name = report_service
ext = "." + format
if not report_name.endswith(ext):
report_name += ext
attachments[report_name] = result
# Add document attachments
for attach in template.attachment_ids:
# keep the bytes as fetched from the db, base64 encoded
attachments[attach.datas_fname] = attach.datas
values['attachments'] = attachments
if values['attachments']:
attachment = values.pop('attachments')
attachment_obj = self.pool.get('ir.attachment')
att_ids = []
for fname, fcontent in attachment.iteritems():
data_attach = {
'name': fname,
'datas': fcontent,
'datas_fname': fname,
'description': fname,
'res_model' : self._name,
'res_id' : ids[0] if ids else False
}
att_ids.append(attachment_obj.create(cr, uid, data_attach))
values['attachment_ids'] = att_ids
else:
# render the mail as one-shot
values = self.pool.get('email.template').generate_email(cr, uid, template_id, res_id, context=context)
# retrofit generated attachments in the expected field format
if values['attachments']:
attachment = values.pop('attachments')
attachment_obj = self.pool.get('ir.attachment')
att_ids = []
for fname, fcontent in attachment.iteritems():
data_attach = {
'name': fname,
'datas': fcontent,
'datas_fname': fname,
'description': fname,
'res_model' : self._name,
'res_id' : ids[0] if ids else False
}
att_ids.append(attachment_obj.create(cr, uid, data_attach))
values['attachment_ids'] = att_ids
else:
# restore defaults
values = self.default_get(cr, uid, self.fields_get_keys(cr, uid), context)
values.update(use_template=use_template, template_id=template_id)
return {'value': values}
def template_toggle(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context=context):
had_template = record.use_template
record.write({'use_template': not(had_template)})
if had_template:
# equivalent to choosing an empty template
onchange_defaults = self.on_change_template(cr, uid, record.id, not(had_template),
False, email_from=record.email_from,
email_to=record.email_to, context=context)
record.write(onchange_defaults['value'])
return _reopen(self, record.id, record.model, record.res_id)
def save_as_template(self, cr, uid, ids, context=None):
if context is None:
context = {}
email_template = self.pool.get('email.template')
model_pool = self.pool.get('ir.model')
for record in self.browse(cr, uid, ids, context=context):
model = record.model or context.get('active_model')
model_ids = model_pool.search(cr, uid, [('model', '=', model)])
model_id = model_ids and model_ids[0] or False
model_name = ''
if model_id:
model_name = model_pool.browse(cr, uid, model_id, context=context).name
template_name = "%s: %s" % (model_name, tools.ustr(record.subject))
values = {
'name': template_name,
'email_from': record.email_from or False,
'subject': record.subject or False,
'body_text': record.body_text or False,
'email_to': record.email_to or False,
'email_cc': record.email_cc or False,
'email_bcc': record.email_bcc or False,
'reply_to': record.reply_to or False,
'model_id': model_id or False,
'attachment_ids': [(6, 0, [att.id for att in record.attachment_ids])]
}
template_id = email_template.create(cr, uid, values, context=context)
record.write({'template_id': template_id,
'use_template': True})
# _reopen same wizard screen with new template preselected
return _reopen(self, record.id, model, record.res_id)
# override the basic implementation
def render_template(self, cr, uid, template, model, res_id, context=None):
return self.pool.get('email.template').render_template(cr, uid, template, model, res_id, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| Java |
package org.osforce.connect.service.system;
import org.osforce.connect.entity.system.ProjectFeature;
/**
*
* @author gavin
* @since 1.0.0
* @create Feb 12, 2011 - 9:23:35 PM
* <a href="http://www.opensourceforce.org">开源力量</a>
*/
public interface ProjectFeatureService {
ProjectFeature getProjectFeature(Long featureId);
ProjectFeature getProjectFeature(String code, Long projectId);
void createProjectFeature(ProjectFeature feature);
void updateProjectFeature(ProjectFeature feature);
void deleteProjectFeature(Long featureId);
}
| Java |
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.IfcGeometricModelResource
{
public enum IfcBooleanOperator
{
[Description("The operation of constructing the regularized set theoretic union of the volumes " +
"defined by two solids.")]
UNION = 1,
[Description("The operation of constructing the regularised set theoretic intersection of the v" +
"olumes defined by two solids.")]
INTERSECTION = 2,
[Description("The regularised set theoretic difference between the volumes defined by two solid" +
"s.")]
DIFFERENCE = 3,
}
}
| Java |
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "rocksdb/sst_file_writer.h"
#include <vector>
#include "db/dbformat.h"
#include "rocksdb/table.h"
#include "table/block_based_table_builder.h"
#include "table/sst_file_writer_collectors.h"
#include "util/file_reader_writer.h"
#include "util/sync_point.h"
namespace rocksdb {
const std::string ExternalSstFilePropertyNames::kVersion =
"rocksdb.external_sst_file.version";
const std::string ExternalSstFilePropertyNames::kGlobalSeqno =
"rocksdb.external_sst_file.global_seqno";
#ifndef ROCKSDB_LITE
const size_t kFadviseTrigger = 1024 * 1024; // 1MB
struct SstFileWriter::Rep {
Rep(const EnvOptions& _env_options, const Options& options,
const Comparator* _user_comparator, ColumnFamilyHandle* _cfh,
bool _invalidate_page_cache)
: env_options(_env_options),
ioptions(options),
mutable_cf_options(options),
internal_comparator(_user_comparator),
cfh(_cfh),
invalidate_page_cache(_invalidate_page_cache),
last_fadvise_size(0) {}
std::unique_ptr<WritableFileWriter> file_writer;
std::unique_ptr<TableBuilder> builder;
EnvOptions env_options;
ImmutableCFOptions ioptions;
MutableCFOptions mutable_cf_options;
InternalKeyComparator internal_comparator;
ExternalSstFileInfo file_info;
InternalKey ikey;
std::string column_family_name;
ColumnFamilyHandle* cfh;
// If true, We will give the OS a hint that this file pages is not needed
// everytime we write 1MB to the file
bool invalidate_page_cache;
// the size of the file during the last time we called Fadvise to remove
// cached pages from page cache.
uint64_t last_fadvise_size;
};
SstFileWriter::SstFileWriter(const EnvOptions& env_options,
const Options& options,
const Comparator* user_comparator,
ColumnFamilyHandle* column_family,
bool invalidate_page_cache)
: rep_(new Rep(env_options, options, user_comparator, column_family,
invalidate_page_cache)) {
rep_->file_info.file_size = 0;
}
SstFileWriter::~SstFileWriter() {
if (rep_->builder) {
// User did not call Finish() or Finish() failed, we need to
// abandon the builder.
rep_->builder->Abandon();
}
delete rep_;
}
Status SstFileWriter::Open(const std::string& file_path) {
Rep* r = rep_;
Status s;
std::unique_ptr<WritableFile> sst_file;
s = r->ioptions.env->NewWritableFile(file_path, &sst_file, r->env_options);
if (!s.ok()) {
return s;
}
CompressionType compression_type;
if (r->ioptions.bottommost_compression != kDisableCompressionOption) {
compression_type = r->ioptions.bottommost_compression;
} else if (!r->ioptions.compression_per_level.empty()) {
// Use the compression of the last level if we have per level compression
compression_type = *(r->ioptions.compression_per_level.rbegin());
} else {
compression_type = r->mutable_cf_options.compression;
}
std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
int_tbl_prop_collector_factories;
// SstFileWriter properties collector to add SstFileWriter version.
int_tbl_prop_collector_factories.emplace_back(
new SstFileWriterPropertiesCollectorFactory(2 /* version */,
0 /* global_seqno*/));
// User collector factories
auto user_collector_factories =
r->ioptions.table_properties_collector_factories;
for (size_t i = 0; i < user_collector_factories.size(); i++) {
int_tbl_prop_collector_factories.emplace_back(
new UserKeyTablePropertiesCollectorFactory(
user_collector_factories[i]));
}
int unknown_level = -1;
uint32_t cf_id;
if (r->cfh != nullptr) {
// user explicitly specified that this file will be ingested into cfh,
// we can persist this information in the file.
cf_id = r->cfh->GetID();
r->column_family_name = r->cfh->GetName();
} else {
r->column_family_name = "";
cf_id = TablePropertiesCollectorFactory::Context::kUnknownColumnFamily;
}
TableBuilderOptions table_builder_options(
r->ioptions, r->internal_comparator, &int_tbl_prop_collector_factories,
compression_type, r->ioptions.compression_opts,
nullptr /* compression_dict */, false /* skip_filters */,
r->column_family_name, unknown_level);
r->file_writer.reset(
new WritableFileWriter(std::move(sst_file), r->env_options));
// TODO(tec) : If table_factory is using compressed block cache, we will
// be adding the external sst file blocks into it, which is wasteful.
r->builder.reset(r->ioptions.table_factory->NewTableBuilder(
table_builder_options, cf_id, r->file_writer.get()));
r->file_info.file_path = file_path;
r->file_info.file_size = 0;
r->file_info.num_entries = 0;
r->file_info.sequence_number = 0;
r->file_info.version = 2;
return s;
}
Status SstFileWriter::Add(const Slice& user_key, const Slice& value) {
Rep* r = rep_;
if (!r->builder) {
return Status::InvalidArgument("File is not opened");
}
if (r->file_info.num_entries == 0) {
r->file_info.smallest_key.assign(user_key.data(), user_key.size());
} else {
if (r->internal_comparator.user_comparator()->Compare(
user_key, r->file_info.largest_key) <= 0) {
// Make sure that keys are added in order
return Status::InvalidArgument("Keys must be added in order");
}
}
// TODO(tec) : For external SST files we could omit the seqno and type.
r->ikey.Set(user_key, 0 /* Sequence Number */,
ValueType::kTypeValue /* Put */);
r->builder->Add(r->ikey.Encode(), value);
// update file info
r->file_info.num_entries++;
r->file_info.largest_key.assign(user_key.data(), user_key.size());
r->file_info.file_size = r->builder->FileSize();
InvalidatePageCache(false /* closing */);
return Status::OK();
}
Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) {
Rep* r = rep_;
if (!r->builder) {
return Status::InvalidArgument("File is not opened");
}
if (r->file_info.num_entries == 0) {
return Status::InvalidArgument("Cannot create sst file with no entries");
}
Status s = r->builder->Finish();
r->file_info.file_size = r->builder->FileSize();
if (s.ok()) {
s = r->file_writer->Sync(r->ioptions.use_fsync);
InvalidatePageCache(true /* closing */);
if (s.ok()) {
s = r->file_writer->Close();
}
}
if (!s.ok()) {
r->ioptions.env->DeleteFile(r->file_info.file_path);
}
if (file_info != nullptr) {
*file_info = r->file_info;
}
r->builder.reset();
return s;
}
void SstFileWriter::InvalidatePageCache(bool closing) {
Rep* r = rep_;
if (r->invalidate_page_cache == false) {
// Fadvise disabled
return;
}
uint64_t bytes_since_last_fadvise =
r->builder->FileSize() - r->last_fadvise_size;
if (bytes_since_last_fadvise > kFadviseTrigger || closing) {
TEST_SYNC_POINT_CALLBACK("SstFileWriter::InvalidatePageCache",
&(bytes_since_last_fadvise));
// Tell the OS that we dont need this file in page cache
r->file_writer->InvalidateCache(0, 0);
r->last_fadvise_size = r->builder->FileSize();
}
}
uint64_t SstFileWriter::FileSize() {
return rep_->file_info.file_size;
}
#endif // !ROCKSDB_LITE
} // namespace rocksdb
| Java |
const LdapStrategy = require('./LdapStrategy');
const MoodleStrategy = require('./MoodleStrategy');
const IservStrategy = require('./IservStrategy');
const TSPStrategy = require('./TSPStrategy');
const ApiKeyStrategy = require('./ApiKeyStrategy');
module.exports = {
LdapStrategy,
MoodleStrategy,
IservStrategy,
TSPStrategy,
ApiKeyStrategy,
};
| Java |
/*
Copyright (C) 2014-2016 Leosac
This file is part of Leosac.
Leosac 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.
Leosac 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 "AccessOverview.hpp"
#include "core/auth/Door.hpp"
#include "core/auth/Door_odb.h"
#include "core/auth/User_odb.h"
#include "tools/JSONUtils.hpp"
#include "tools/db/DBService.hpp"
using namespace Leosac;
using namespace Leosac::Module;
using namespace Leosac::Module::WebSockAPI;
AccessOverview::AccessOverview(RequestContext ctx)
: MethodHandler(ctx)
{
}
MethodHandlerUPtr AccessOverview::create(RequestContext ctx)
{
return std::make_unique<AccessOverview>(ctx);
}
json AccessOverview::process_impl(const json &)
{
json rep;
DBPtr db = ctx_.dbsrv->db();
odb::transaction t(db->begin());
// todo: This probably doesn't scale very well...
auto doors = db->query<Auth::Door>();
// Since we'll be looping over users multiple time, we cannot use
// an odb::result object.
auto users_odb = db->query<Auth::User>();
// So we'll have to convert this to a vector of User, instead of
// odb::result::iterator.
std::vector<Auth::UserPtr> users;
for (auto itr_odb(users_odb.begin()); itr_odb != users_odb.end(); ++itr_odb)
users.push_back(itr_odb.load());
for (const auto &door : doors)
{
std::set<Auth::UserId> unique_user_ids;
json door_info = {{"door_id", door.id()}, {"user_ids", json::array()}};
for (const auto &lazy_mapping : door.lazy_mapping())
{
auto mapping = lazy_mapping.load();
for (const auto &user_ptr : users)
{
// Check the std::set in case the user is already authorized to
// access the door.
if (unique_user_ids.count(user_ptr->id()))
{
continue;
}
if (mapping->has_user_indirect(user_ptr))
{
unique_user_ids.insert(user_ptr->id());
}
}
}
for (const auto &id : unique_user_ids)
door_info["user_ids"].push_back(id);
rep.push_back(door_info);
}
return rep;
}
std::vector<ActionActionParam>
AccessOverview::required_permission(const json &) const
{
std::vector<ActionActionParam> perm_;
SecurityContext::ActionParam ap;
perm_.push_back({SecurityContext::Action::ACCESS_OVERVIEW, ap});
return perm_;
}
| Java |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedules', '0005_auto_20171010_1722'),
]
operations = [
migrations.CreateModel(
name='ScheduleExperience',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('experience_type', models.PositiveSmallIntegerField(default=0, choices=[(0, b'Recurring Nudge and Upgrade Reminder'), (1, b'Course Updates')])),
('schedule', models.OneToOneField(related_name='experience', to='schedules.Schedule', on_delete=models.CASCADE)),
],
),
]
| Java |
# -*- coding: utf-8 -*-
# Copyright 2017 KMEE
# Hendrix Costa <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.addons.financial.tests.financial_test_classes import \
FinancialTestCase
class ManualFinancialProcess(FinancialTestCase):
def setUp(self):
self.financial_model = self.env['financial.move']
super(ManualFinancialProcess, self).setUp()
def test_01_check_return_views(self):
"""Check if view is correctly called for python code"""
# test for len(financial.move) == 1
financial_move_id = self.financial_model.search([], limit=1)
action = financial_move_id.action_view_financial('2receive')
self.assertEqual(
action.get('display_name'),
'financial.move.debt.2receive.form (in financial)')
self.assertEqual(
action.get('res_id'), financial_move_id.id)
action = financial_move_id.action_view_financial('2pay')
self.assertEqual(
action.get('display_name'),
'financial.move.debt.2pay.form (in financial)')
self.assertEqual(
action.get('res_id'), financial_move_id.id)
# test for len(financial.move) > 1
financial_move_id = self.financial_model.search([], limit=2)
action = financial_move_id.action_view_financial('2pay')
self.assertEqual(action.get('domain')[0][2], financial_move_id.ids)
# test for len(financial.move) < 1
action = self.financial_model.action_view_financial('2pay')
self.assertEqual(action.get('type'), 'ir.actions.act_window_close')
| Java |
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from django.utils.translation import ugettext_lazy as _
from shuup.core.models import Category
from shuup.xtheme import TemplatedPlugin
from shuup.xtheme.plugins.forms import GenericPluginForm, TranslatableField
class CategoryLinksConfigForm(GenericPluginForm):
"""
A configuration form for the CategoryLinksPlugin
"""
def populate(self):
"""
A custom populate method to display category choices
"""
for field in self.plugin.fields:
if isinstance(field, tuple):
name, value = field
value.initial = self.plugin.config.get(name, value.initial)
self.fields[name] = value
self.fields["categories"] = forms.ModelMultipleChoiceField(
queryset=Category.objects.all_visible(customer=None),
required=False,
initial=self.plugin.config.get("categories", None),
)
def clean(self):
"""
A custom clean method to save category configuration information in a serializable form
"""
cleaned_data = super(CategoryLinksConfigForm, self).clean()
categories = cleaned_data.get("categories", [])
cleaned_data["categories"] = [category.pk for category in categories if hasattr(category, "pk")]
return cleaned_data
class CategoryLinksPlugin(TemplatedPlugin):
"""
A plugin for displaying links to visible categories on the shop front
"""
identifier = "category_links"
name = _("Category Links")
template_name = "shuup/xtheme/plugins/category_links.jinja"
editor_form_class = CategoryLinksConfigForm
fields = [
("title", TranslatableField(label=_("Title"), required=False, initial="")),
("show_all_categories", forms.BooleanField(
label=_("Show all categories"),
required=False,
initial=True,
help_text=_("All categories are shown, even if not selected"),
)),
"categories",
]
def get_context_data(self, context):
"""
A custom get_context_data method to return only visible categories
for request customer.
"""
selected_categories = self.config.get("categories", [])
show_all_categories = self.config.get("show_all_categories", True)
request = context.get("request")
categories = Category.objects.all_visible(
customer=getattr(request, "customer"),
shop=getattr(request, "shop")
)
if not show_all_categories:
categories = categories.filter(id__in=selected_categories)
return {
"title": self.get_translated_value("title"),
"categories": categories,
}
| Java |
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
RailsFrance::Application.initialize!
| Java |
package functionaltests.job;
import java.io.Serializable;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable;
import org.junit.Test;
import functionaltests.utils.SchedulerFunctionalTest;
import static org.junit.Assert.*;
/**
* Test provokes scenario when task gets 'NOT_RESTARTED' status:
* - task is submitted and starts execution
* - user requests to restart task with some delay
* - before task was restarted job is killed
*
*/
public class TestTaskNotRestarted extends SchedulerFunctionalTest {
public static class TestJavaTask extends JavaExecutable {
@Override
public Serializable execute(TaskResult... results) throws Throwable {
Thread.sleep(Long.MAX_VALUE);
return "OK";
}
}
@Test
public void test() throws Exception {
Scheduler scheduler = schedulerHelper.getSchedulerInterface();
JobId jobId = scheduler.submit(createJob());
JobState jobState;
schedulerHelper.waitForEventTaskRunning(jobId, "task1");
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.RUNNING, jobState.getTasks().get(0).getStatus());
scheduler.restartTask(jobId, "task1", Integer.MAX_VALUE);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.WAITING_ON_ERROR, jobState.getTasks().get(0).getStatus());
scheduler.killJob(jobId);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.NOT_RESTARTED, jobState.getTasks().get(0).getStatus());
}
private TaskFlowJob createJob() throws Exception {
TaskFlowJob job = new TaskFlowJob();
job.setName(this.getClass().getSimpleName());
JavaTask javaTask = new JavaTask();
javaTask.setExecutableClassName(TestJavaTask.class.getName());
javaTask.setName("task1");
javaTask.setMaxNumberOfExecution(10);
job.addTask(javaTask);
return job;
}
}
| Java |
body {
padding: 50px;
}
.room-actions {
margin-right: -14px;
}
.room-actions .btn {
margin: -17px 0 1px;
padding: 5px 4px;
font-size:10px;
}
| Java |
/*!
Chosen, a Select Box Enhancer for jQuery and Prototype
by Patrick Filler for Harvest, http://getharvest.com
Version 1.2.0
Full source at https://github.com/harvesthq/chosen
Copyright (c) 2011-2014 Harvest http://getharvest.com
MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md
This file is generated by `grunt build`, do not edit it by hand.
*/
/* @group Base */
.chosen-container {
position: relative;
display: inline-block;
vertical-align: middle;
/*font-size: 13px;*/
zoom: 1;
*display: inline;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.chosen-container * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.chosen-container .chosen-drop {
position: absolute;
top: 100%;
left: -9999px;
z-index: 1010;
width: 100%;
border: 1px solid #aaa;
border-top: 0;
background: #fff;
box-shadow: 0 4px 5px rgba(0, 0, 0, 0.15);
}
.chosen-container.chosen-with-drop .chosen-drop {
left: 0;
}
.chosen-container a {
cursor: pointer;
}
/* @end */
/* @group Single Chosen */
.chosen-container-single .chosen-single {
position: relative;
display: block;
overflow: hidden;
padding: 0 0 0 8px;
height: 25px;
border: 1px solid #aaa;
border-radius: 5px;
background-color: #fff;
background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #ffffff), color-stop(50%, #f6f6f6), color-stop(52%, #eeeeee), color-stop(100%, #f4f4f4));
background: -webkit-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: -moz-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: -o-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background-clip: padding-box;
box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1);
color: #444;
text-decoration: none;
white-space: nowrap;
line-height: 24px;
}
.chosen-container-single .chosen-default {
color: #999;
}
.chosen-container-single .chosen-single span {
display: block;
overflow: hidden;
margin-right: 26px;
text-overflow: ellipsis;
white-space: nowrap;
}
.chosen-container-single .chosen-single-with-deselect span {
margin-right: 38px;
}
.chosen-container-single .chosen-single abbr {
position: absolute;
top: 6px;
right: 26px;
display: block;
width: 12px;
height: 12px;
background: url('chosen-sprite.png') -42px 1px no-repeat;
font-size: 1px;
}
.chosen-container-single .chosen-single abbr:hover {
background-position: -42px -10px;
}
.chosen-container-single.chosen-disabled .chosen-single abbr:hover {
background-position: -42px -10px;
}
.chosen-container-single .chosen-single div {
position: absolute;
top: 0;
right: 0;
display: block;
width: 18px;
height: 100%;
}
.chosen-container-single .chosen-single div b {
display: block;
width: 100%;
height: 100%;
background: url('chosen-sprite.png') no-repeat 0px 2px;
}
.chosen-container-single .chosen-search {
position: relative;
z-index: 1010;
margin: 0;
padding: 3px 4px;
white-space: nowrap;
}
.chosen-container-single .chosen-search input[type="text"] {
margin: 1px 0;
padding: 4px 20px 4px 5px;
width: 100%;
height: auto;
outline: 0;
border: 1px solid #aaa;
background: white url('chosen-sprite.png') no-repeat 100% -20px;
background: url('chosen-sprite.png') no-repeat 100% -20px;
font-size: 1em;
font-family: sans-serif;
line-height: normal;
border-radius: 0;
}
.chosen-container-single .chosen-drop {
margin-top: -1px;
border-radius: 0 0 4px 4px;
background-clip: padding-box;
}
.chosen-container-single.chosen-container-single-nosearch .chosen-search {
position: absolute;
left: -9999px;
}
/* @end */
/* @group Results */
.chosen-container .chosen-results {
color: #444;
position: relative;
overflow-x: hidden;
overflow-y: auto;
margin: 0 4px 4px 0;
padding: 0 0 0 4px;
max-height: 240px;
-webkit-overflow-scrolling: touch;
}
.chosen-container .chosen-results li {
display: none;
margin: 0;
padding: 5px 6px;
list-style: none;
line-height: 15px;
word-wrap: break-word;
-webkit-touch-callout: none;
}
.chosen-container .chosen-results li.active-result {
display: list-item;
cursor: pointer;
}
.chosen-container .chosen-results li.disabled-result {
display: list-item;
color: #ccc;
cursor: default;
}
.chosen-container .chosen-results li.highlighted {
background-color: #3875d7;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #3875d7), color-stop(90%, #2a62bc));
background-image: -webkit-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: -moz-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: -o-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: linear-gradient(#3875d7 20%, #2a62bc 90%);
color: #fff;
}
.chosen-container .chosen-results li.no-results {
color: #777;
display: list-item;
background: #f4f4f4;
}
.chosen-container .chosen-results li.group-result {
display: list-item;
font-weight: bold;
cursor: default;
}
.chosen-container .chosen-results li.group-option {
padding-left: 15px;
}
.chosen-container .chosen-results li em {
font-style: normal;
text-decoration: underline;
}
/* @end */
/* @group Multi Chosen */
.chosen-container-multi .chosen-choices {
position: relative;
overflow: hidden;
margin: 0;
padding: 0 5px;
width: 100%;
height: auto !important;
height: 1%;
border: 1px solid #aaa;
background-color: #fff;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff));
background-image: -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: -moz-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: -o-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: linear-gradient(#eeeeee 1%, #ffffff 15%);
cursor: text;
}
.chosen-container-multi .chosen-choices li {
float: left;
list-style: none;
}
.chosen-container-multi .chosen-choices li.search-field {
margin: 0;
padding: 0;
white-space: nowrap;
}
.chosen-container-multi .chosen-choices li.search-field input[type="text"] {
margin: 1px 0;
padding: 0;
height: 25px;
outline: 0;
border: 0 !important;
background: transparent !important;
box-shadow: none;
color: #999;
font-size: 100%;
font-family: sans-serif;
line-height: normal;
border-radius: 0;
}
.chosen-container-multi .chosen-choices li.search-choice {
position: relative;
margin: 3px 5px 3px 0;
padding: 3px 20px 3px 5px;
border: 1px solid #aaa;
max-width: 100%;
border-radius: 3px;
background-color: #eeeeee;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
background-image: -webkit-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -moz-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -o-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-size: 100% 19px;
background-repeat: repeat-x;
background-clip: padding-box;
box-shadow: 0 0 2px white inset, 0 1px 0 rgba(0, 0, 0, 0.05);
color: #333;
line-height: 13px;
cursor: default;
}
.chosen-container-multi .chosen-choices li.search-choice span {
word-wrap: break-word;
}
.chosen-container-multi .chosen-choices li.search-choice .search-choice-close {
position: absolute;
top: 4px;
right: 3px;
display: block;
width: 12px;
height: 12px;
background: url('chosen-sprite.png') -42px 1px no-repeat;
font-size: 1px;
}
.chosen-container-multi .chosen-choices li.search-choice .search-choice-close:hover {
background-position: -42px -10px;
}
.chosen-container-multi .chosen-choices li.search-choice-disabled {
padding-right: 5px;
border: 1px solid #ccc;
background-color: #e4e4e4;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -o-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
color: #666;
}
.chosen-container-multi .chosen-choices li.search-choice-focus {
background: #d4d4d4;
}
.chosen-container-multi .chosen-choices li.search-choice-focus .search-choice-close {
background-position: -42px -10px;
}
.chosen-container-multi .chosen-results {
margin: 0;
padding: 0;
}
.chosen-container-multi .chosen-drop .result-selected {
display: list-item;
color: #ccc;
cursor: default;
}
/* @end */
/* @group Active */
.chosen-container-active .chosen-single {
border: 1px solid #5897fb;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.chosen-container-active.chosen-with-drop .chosen-single {
border: 1px solid #aaa;
-moz-border-radius-bottomright: 0;
border-bottom-right-radius: 0;
-moz-border-radius-bottomleft: 0;
border-bottom-left-radius: 0;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #eeeeee), color-stop(80%, #ffffff));
background-image: -webkit-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: -moz-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: -o-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: linear-gradient(#eeeeee 20%, #ffffff 80%);
box-shadow: 0 1px 0 #fff inset;
}
.chosen-container-active.chosen-with-drop .chosen-single div {
border-left: none;
background: transparent;
}
.chosen-container-active.chosen-with-drop .chosen-single div b {
background-position: -18px 2px;
}
.chosen-container-active .chosen-choices {
border: 1px solid #5897fb;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.chosen-container-active .chosen-choices li.search-field input[type="text"] {
color: #222 !important;
}
/* @end */
/* @group Disabled Support */
.chosen-disabled {
opacity: 0.5 !important;
cursor: default;
}
.chosen-disabled .chosen-single {
cursor: default;
}
.chosen-disabled .chosen-choices .search-choice .search-choice-close {
cursor: default;
}
/* @end */
/* @group Right to Left */
.chosen-rtl {
text-align: right;
}
.chosen-rtl .chosen-single {
overflow: visible;
padding: 0 8px 0 0;
}
.chosen-rtl .chosen-single span {
margin-right: 0;
margin-left: 26px;
direction: rtl;
}
.chosen-rtl .chosen-single-with-deselect span {
margin-left: 38px;
}
.chosen-rtl .chosen-single div {
right: auto;
left: 3px;
}
.chosen-rtl .chosen-single abbr {
right: auto;
left: 26px;
}
.chosen-rtl .chosen-choices li {
float: right;
}
.chosen-rtl .chosen-choices li.search-field input[type="text"] {
direction: rtl;
}
.chosen-rtl .chosen-choices li.search-choice {
margin: 3px 5px 3px 0;
padding: 3px 5px 3px 19px;
}
.chosen-rtl .chosen-choices li.search-choice .search-choice-close {
right: auto;
left: 4px;
}
.chosen-rtl.chosen-container-single-nosearch .chosen-search,
.chosen-rtl .chosen-drop {
left: 9999px;
}
.chosen-rtl.chosen-container-single .chosen-results {
margin: 0 0 4px 4px;
padding: 0 4px 0 0;
}
.chosen-rtl .chosen-results li.group-option {
padding-right: 15px;
padding-left: 0;
}
.chosen-rtl.chosen-container-active.chosen-with-drop .chosen-single div {
border-right: none;
}
.chosen-rtl .chosen-search input[type="text"] {
padding: 4px 5px 4px 20px;
background: white url('chosen-sprite.png') no-repeat -30px -20px;
background: url('chosen-sprite.png') no-repeat -30px -20px;
direction: rtl;
}
.chosen-rtl.chosen-container-single .chosen-single div b {
background-position: 6px 2px;
}
.chosen-rtl.chosen-container-single.chosen-with-drop .chosen-single div b {
background-position: -12px 2px;
}
/* @end */
/* @group Retina compatibility */
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-resolution: 144dpi) {
.chosen-rtl .chosen-search input[type="text"],
.chosen-container-single .chosen-single abbr,
.chosen-container-single .chosen-single div b,
.chosen-container-single .chosen-search input[type="text"],
.chosen-container-multi .chosen-choices .search-choice .search-choice-close,
.chosen-container .chosen-results-scroll-down span,
.chosen-container .chosen-results-scroll-up span {
background-image: url('[email protected]') !important;
background-size: 52px 37px !important;
background-repeat: no-repeat !important;
}
}
select.form-control + .chosen-container.chosen-container-single .chosen-single {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
-webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
background-image:none;
}
select.form-control + .chosen-container.chosen-container-single .chosen-single div {
top:4px;
color:#000;
}
select.form-control + .chosen-container .chosen-drop {
background-color: #FFF;
border: 1px solid #CCC;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
margin: 2px 0 0;
}
select.form-control + .chosen-container .chosen-search input[type=text] {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #FFF;
border: 1px solid #CCC;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
background-image:none;
}
select.form-control + .chosen-container .chosen-results {
margin: 2px 0 0;
padding: 5px 0;
font-size: 14px;
list-style: none;
background-color: #fff;
margin-bottom: 5px;
}
select.form-control + .chosen-container .chosen-results li ,
select.form-control + .chosen-container .chosen-results li.active-result {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.428571429;
color: #333;
white-space: nowrap;
background-image:none;
}
select.form-control + .chosen-container .chosen-results li:hover,
select.form-control + .chosen-container .chosen-results li.active-result:hover,
select.form-control + .chosen-container .chosen-results li.highlighted
{
color: #FFF;
text-decoration: none;
background-color: #428BCA;
background-image:none;
}
select.form-control + .chosen-container-multi .chosen-choices {
display: block;
width: 100%;
min-height: 34px;
padding: 6px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #FFF;
border: 1px solid #CCC;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
background-image:none;
}
select.form-control + .chosen-container-multi .chosen-choices li.search-field input[type="text"] {
height:auto;
padding:5px 0;
}
select.form-control + .chosen-container-multi .chosen-choices li.search-choice {
background-image: none;
padding: 3px 24px 3px 5px;
margin: 0 6px 0 0;
font-size: 14px;
font-weight: normal;
line-height: 1.428571429;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 4px;
color: #333;
background-color: #FFF;
border-color: #CCC;
}
select.form-control + .chosen-container-multi .chosen-choices li.search-choice .search-choice-close {
top:8px;
right:6px;
}
select.form-control + .chosen-container-multi.chosen-container-active .chosen-choices,
select.form-control + .chosen-container.chosen-container-single.chosen-container-active .chosen-single,
select.form-control + .chosen-container .chosen-search input[type=text]:focus{
border-color: #66AFE9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
}
/* @end */
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<link rel="stylesheet" type="text/css" href="./../docs/css/style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="author" value="JMeter developers">
<meta name="email" value="dev AT jmeter.apache.org">
<title>Apache JMeter - Changes</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#525D76">
<table border="0" cellspacing="0">
<tr>
<td align="left">
<a href="http://www.apache.org"><img title="Apache Software Foundation" width="387" height="100" src="./../docs/images/asf-logo.gif" border="0"/></a>
</td>
<td align="right">
<a href="http://jmeter.apache.org/"><img width="221" height="102" src="./../docs/images/logo.jpg" alt="Apache JMeter" title="Apache JMeter" border="0"></a>
</td>
</tr>
</table>
<table border="0" cellspacing="4">
<tr><td>
<hr noshade size="1">
</td></tr>
<tr>
<td align="left" valign="top">
<br>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr><td bgcolor="#525D76">
<font color="#ffffff" face="arial,helvetica,sanserif">
<strong>Changes</strong></font>
</td></tr>
<tr><td>
<blockquote>
<p><table border="1" bgcolor="#bbbb00" width="50%" cellspacing="0" cellpadding="2">
<tr><td>
<b>
This page details the changes made in the current version only.
</b>
<br>
Earlier changes are detailed in the
<a href="changes_history.html">
History of Previous Changes
</a>
.
</td></tr>
</table></p>
<h1>
Version 2.7
</h1>
<h2>
New and Noteworthy
</h2>
<h3>
OS Process Sampler
</h3>
<p>
A new System Sampler that can be used to execute commands on the local machine.
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='629' height='497' src="./../docs/images/screenshots/changes/2.7/01_os_process_sampler.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<p>
OS Process Sampler results example with DNS lookup command 'dig'
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='877' height='470' src="./../docs/images/screenshots/changes/2.7/02_os_process_example_results.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
JMS Samplers improvements
</h3>
<p>
Addition of a "Non Persistent Delivery" option to send "Non-Persistent" (Guaranteed to be delivered at most once. Message loss is not a concern.) JMS messages
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='953' height='336' src="./../docs/images/screenshots/changes/2.7/11_jms_non_persistent_delivery_mode.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<p>
Support sending of JMS Object Messages to enable sending Objects unmarshalled from XML by XStream
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='808' height='726' src="./../docs/images/screenshots/changes/2.7/12_jms_sending_objects.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<p>
Enable setting JMS Properties through JMS Publisher sampler
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1029' height='470' src="./../docs/images/screenshots/changes/2.7/13_jms_properties.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
Test Action sampler
</h3>
<p>
Allow premature exit from a loop
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='862' height='167' src="./../docs/images/screenshots/changes/2.7/07_test_action_next_iter.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
Webservice Sampler improvements
</h3>
<p>
Add a jmeter property soap.document_cache to control size of Document Cache
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='270' height='59' src="./../docs/images/screenshots/changes/2.7/14_ws_document_cache.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<p>
Make Maintain HTTP Session configurable
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='833' height='505' src="./../docs/images/screenshots/changes/2.7/15_ws_maintain_session.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
Aggregate graph: Clustered Bar char with average, median, 90% line, min and max columns
</h3>
<p>
Aggregate graph changes to Clustered Bar chart, add more columns (median, 90% line, min, max) and options, fixed some bugs.
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1177' height='503' src="./../docs/images/screenshots/changes/2.7/03_aggregate_graph_with_new_cols.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<p>
New settings for aggregate graph
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1173' height='433' src="./../docs/images/screenshots/changes/2.7/04_aggregate_graph_parameters.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
Improvements of HTML report design generated by JMeter Ant task in extras folder
</h3>
<p>
HTML report example
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1264' height='506' src="./../docs/images/screenshots/changes/2.7/05_jmeter_ant_task_report_success.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<p>
HTML report example with some assertion errors
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1267' height='550' src="./../docs/images/screenshots/changes/2.7/06_jmeter_ant_task_report_errors.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
Mailer Visualizer
</h3>
<p>
<ul>
<li>
Enable authentication, and connection security with SSL or TLS
</li>
<li>
Improve GUI design
</li>
<li>
Add internationalisation (i18n) support
</li>
</ul>
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='860' height='403' src="./../docs/images/screenshots/changes/2.7/10_mailer_visualizer_gui.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
New Visual Indicator of number of ERROR/FATAL messages in logs
</h3>
<p>
Indicator shows number of ERROR/FATAL messsages in logs, it can be clicked to toggle Log Viewer panel
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='815' height='633' src="./../docs/images/screenshots/changes/2.7/16_log_errors_counter.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
Dialog box to show detail of a parameter row
</h3>
<p>
Add a detail button on parameters table to show detail of a Row
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='824' height='165' src="./../docs/images/screenshots/changes/2.7/08_param_button_detail.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<p>
Detail box example
<p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='702' height='454' src="./../docs/images/screenshots/changes/2.7/09_detail_box.png"><br>
<font size="-1"></font></td></tr></table></p>
</p>
<h3>
Plugin writers
</h3>
<p>
New interface org.apache.jmeter.engine.util.ConfigMergabilityIndicator has been introduced to tell whether a ConfigTestElement can be merged in Sampler (see Bug 53042):
<br>
<pre>
public boolean applies(ConfigTestElement configElement);
</pre>
</p>
<p>
New interface org.apache.jmeter.protocol.http.proxy.SamplerCreator to allow plugging HTTP based samplers that differ from default HTTP Samplers through Proxy during Recording Phase (see Bug 52674):
<br>
<pre>
public String[] getManagedContentTypes();
</pre>
<pre>
public HTTPSamplerBase createSampler(HttpRequestHdr request, Map<String, String> pageEncodings, Map<String, String> formEncodings);
</pre>
<pre>
public void populateSampler(HTTPSamplerBase sampler, HttpRequestHdr request, Map<String, String> pageEncodings, Map<String, String> formEncodings) throws Exception;
</pre>
</p>
<h2>
Known bugs
</h2>
<p>
The Once Only controller behaves correctly under a Thread Group or Loop Controller,
but otherwise its behaviour is not consistent (or clearly specified).
</p>
<p>
Listeners don't show iteration counts when a If Controller has a condition which is always false from the first iteration (see Bug 52496).
A workaround is to add a sampler at the same level as (or superior to) the If Controller.
For example a Test Action sampler with 0 wait time (which doesn't generate a sample),
or a Debug Sampler with all fields set to False (to reduce the sample size).
</p>
<h2>
Incompatible changes
</h2>
<p>
When doing replacement of User Defined Variables, Proxy will not substitute partial values anymore when "Regexp matching" is used. It will use Perl 5 word matching ("\b")
</p>
<p>
In User Defined Variables, Test Plan, HTTP Sampler Arguments Table, Java Request Defaults, JMS Sampler and Publisher, LDAP Request Defaults and LDAP Extended Request Defaults, rows with
empty Name and Value are no more saved.
</p>
<p>
JMeter now expands the Test Plan tree to the testplan level and no further and selects the root of the tree. Furthermore default value of onload.expandtree is false.
</p>
<p>
Graph Full Results Listener has been removed.
</p>
<p>
When calling "Clear All" command, if Log Viewer is displayed its content will be cleared.
</p>
<h2>
Bug fixes
</h2>
<h3>
HTTP Samplers and Proxy
</h3>
<ul>
<li>
Bug 52613 - Using Raw Post Body option, text gets encoded
</li>
<li>
Bug 52781 - Content-Disposition header garbled even if browser compatible headers is checked (HC4)
</li>
<li>
Bug 52796 - MonitorHandler fails to clear variables when starting a new parse
</li>
<li>
Bug 52871 - Multiple Certificates not working with HTTP Client 4
</li>
<li>
Bug 52885 - Proxy : Recording issues with HTTPS, cookies starting with secure are partly truncated
</li>
<li>
Bug 52886 - Proxy : Recording issues with HTTPS when spoofing is on, secure cookies are not always changed
</li>
<li>
Bug 52897 - HTTPSampler : Using PUT method with HTTPClient4 and empty Content Encoding and sending files leads to NullPointerException
</li>
<li>
Bug 53145 - HTTP Sampler - function in path evaluated too early
</li>
</ul>
<h3>
Other Samplers
</h3>
<ul>
<li>
Bug 51737 - TCPSampler : Packet gets converted/corrupted
</li>
<li>
Bug 52868 - BSF language list should be sorted
</li>
<li>
Bug 52869 - JSR223 language list currently uses BSF list which is wrong
</li>
<li>
Bug 52932 - JDBC Sampler : Sampler is not marked in error in an Exception which is not of class IOException, SQLException, IOException occurs
</li>
<li>
Bug 52916 - JDBC Exception if there is an empty user defined variable
</li>
<li>
Bug 52937 - Webservice Sampler : Clear Soap Documents Cache at end of Test
</li>
<li>
Bug 53027 - Jmeter starts throwing exceptions while using SMTP Sample in a test plan with HTTP Cookie Mngr or HTTP Request Defaults
</li>
<li>
Bug 53072 - JDBC PREPARED SELECT statements should return results in variables like non prepared SELECT
</li>
</ul>
<h3>
Controllers
</h3>
<ul>
<li>
Bug 52968 - Option Start Next Loop in Thread Group does not mark parent Transaction Sampler in error when an error occurs
</li>
<li>
Bug 50898 - IncludeController : NullPointerException loading script in non-GUI mode if Includers use same element name
</li>
</ul>
<h3>
Listeners
</h3>
<ul>
<li>
Bug 43450 - Listeners/Savers assume SampleResult count is always 1; fixed Generate Summary Results
</li>
</ul>
<h3>
Assertions
</h3>
<ul>
<li>
Bug 52848 - NullPointer in "XPath Assertion"
</li>
</ul>
<h3>
Functions
</h3>
<ul>
</ul>
<h3>
I18N
</h3>
<ul>
<li>
Bug 52551 - Function Helper Dialog does not switch language correctly
</li>
<li>
Bug 52552 - Help reference only works in English
</li>
</ul>
<h3>
General
</h3>
<ul>
<li>
Bug 52639 - JSplitPane divider for log panel should be hidden if log is not activated
</li>
<li>
Bug 52672 - Change Controller action deletes all but one child samplers
</li>
<li>
Bug 52694 - Deadlock in GUI related to non AWT Threads updating GUI
</li>
<li>
Bug 52678 - Proxy : When doing replacement of UserDefinedVariables, partial values should not be substituted
</li>
<li>
Bug 52728 - CSV Data Set Config element cannot coexist with BSF Sampler in same Thread Plan
</li>
<li>
Bug 52762 - Problem with multiples certificates: first index not used until indexes are restarted
</li>
<li>
Bug 52741 - TestBeanGUI default values do not work at second time or later
</li>
<li>
Bug 52783 - oro.patterncache.size property never used due to early init
</li>
<li>
Bug 52789 - Proxy with Regexp Matching can fail with NullPointerException in Value Replacement if value is null
</li>
<li>
Bug 52645 - Recording with Proxy leads to OutOfMemory
</li>
<li>
Bug 52679 - User Parameters columns narrow
</li>
<li>
Bug 52843 - Sample headerSize and bodySize not being accumulated for subsamples
</li>
<li>
Bug 52967 - The function __P() couldn't use default value when running with remote server in GUI mode.
</li>
<li>
Bug 50799 - Having a non-HTTP sampler in a http test plan prevents multiple header managers from working
</li>
<li>
Bug 52997 - Jmeter should not exit without saving Test Plan if saving before exit fails
</li>
<li>
Bug 53136 - Catching Throwable needs to be carefully handled
</li>
</ul>
<h2>
Improvements
</h2>
<h3>
HTTP Samplers
</h3>
<ul>
</ul>
<h3>
Other samplers
</h3>
<ul>
<li>
Bug 52775 - JMS Publisher : Add Non Persistent Delivery option
</li>
<li>
Bug 52810 - Enable setting JMS Properties through JMS Publisher sampler
</li>
<li>
Bug 52938 - Webservice Sampler : Add a jmeter property soap.document_cache to control size of Document Cache
</li>
<li>
Bug 52939 - Webservice Sampler : Make MaintainSession configurable
</li>
<li>
Bug 53073 - Allow to assign the OUT result of a JDBC CALLABLE to JMeter variables
</li>
<li>
Bug 53164 - New System Sampler
</li>
<li>
Bug 53172 - OS Process Sampler - allow specification of Environment Variables
</li>
<li>
Bug 52936 - JMS Publisher : Support sending of JMS Object Messages
</li>
</ul>
<h3>
Controllers
</h3>
<ul>
</ul>
<h3>
Listeners
</h3>
<ul>
<li>
Bug 52603 - MailerVisualizer : Enable SSL , TLS and Authentication
</li>
<li>
Bug 52698 - Remove Graph Full Results Listener
</li>
<li>
Bug 53070 - Change Aggregate graph to Clustered Bar chart, add more columns (median, 90% line, min, max) and options, fixed some bugs
</li>
<li>
Bug 53246 - Mailer Visualizer: improve GUI design and I18N
</li>
</ul>
<h3>
Timers, Assertions, Config, Pre- & Post-Processors
</h3>
<ul>
</ul>
<h3>
Functions
</h3>
<ul>
</ul>
<h3>
I18N
</h3>
<ul>
<li>
Mailer Visualizer has been internationalized. French translation added. (see Bug 53246)
</li>
</ul>
<h3>
General
</h3>
<ul>
<li>
Bug 45839 - Test Action : Allow premature exit from a loop
</li>
<li>
Bug 52614 - MailerModel.sendMail has strange way to calculate debug setting
</li>
<li>
Bug 52782 - Add a detail button on parameters table to show detail of a Row
</li>
<li>
Bug 52674 - Proxy : Add a Sampler Creator to allow plugging HTTP based samplers using potentially non textual POST Body (AMF, Silverlight...) and customizing them for others
</li>
<li>
Bug 52934 - GUI : Open Test plan with the tree expanded to the testplan level and no further and select the root of the tree
</li>
<li>
Bug 52941 - Improvements of HTML report design generated by JMeter Ant task extra
</li>
<li>
Bug 53042 - Introduce a new method in Sampler interface to allow Sampler to decide wether a config element applies to Sampler
</li>
<li>
Bug 52771 - Documentation : Added RSS feed on JMeter Home page under link "Subscribe to What's New"
</li>
<li>
Bug 42784 - Show the number of errors logged in the GUI
</li>
<li>
Bug 53256 - Make Clear All command clean LogViewer content
</li>
<li>
Bug 53261 - Make "Error/fatal" counter added in Bug 42784 open Log Viewer panel when Warn Indicator is clicked
</li>
</ul>
<h2>
Non-functional changes
</h2>
<ul>
<li>
Upgraded to rhino 1.7R3 (was js-1.7R2.jar).
Note: the Maven coordinates for the jar were changed from rhino:js to org.mozilla:rhino.
This does not affect JMeter directly, but might cause problems if using JMeter in a Maven project
with other code that depends on an earlier version of the Rhino Javascript jar.
</li>
<li>
Bug 52675 - Refactor Proxy and HttpRequestHdr to allow Sampler Creation by Proxy
</li>
<li>
Bug 52680 - Mention version in which function was introduced
</li>
<li>
Bug 52788 - HttpRequestHdr : Optimize code to avoid useless work
</li>
<li>
JMeter Ant (ant-jmeter-1.1.1.jar) task was upgraded from 1.0.9 to 1.1.1
</li>
<li>
Updated to commons-io 2.2 (from 2.1)
</li>
<li>
Bug 53129 - Upgrade XStream from 1.3.1 to 1.4.2
</li>
<li>
Updated to httpcomponents-client 4.1.3 (from 4.1.2)
</li>
<li>
Updated JMeter distributed testing guide (jmeter_distributed_testing_step_by_step.pdf). Changes source format to OpenOffice odt (from sxw)
</li>
</ul>
</blockquote>
</p>
</td></tr>
<tr><td><br></td></tr>
</table>
<br>
</td>
</tr>
<tr><td>
<hr noshade size="1">
</td></tr>
<tr>
<td>
<table width=100%>
<tr>
<td align="center">
<font color="#525D76" size="-1"><em>
Copyright © 1999-2012, Apache Software Foundation
</em></font>
</td>
</tr>
<tr><td colspan="2">
<div align="center"><font color="#525D76" size="-1">
Apache, Apache JMeter, JMeter, the Apache feather, and the Apache JMeter logo are
trademarks of the Apache Software Foundation.
</font>
</div>
</td></tr>
</table>
</td>
</tr>
</table>
</body>
</html>
| Java |
/* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.File;
/**
* This file isn't long for this world. It's just something I've been using
* to debug multi-process rejoin stuff.
*
*/
public class VLog {
static File m_logfile = new File("vlog.txt");
public synchronized static void setPortNo(int portNo) {
m_logfile = new File(String.format("vlog-%d.txt", portNo));
}
public synchronized static void log(String str) {
// turn off this stupid thing for now
/*try {
FileWriter log = new FileWriter(m_logfile, true);
log.write(str + "\n");
log.flush();
log.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public static void log(String format, Object... args) {
log(String.format(format, args));
}
}
| Java |
<!-- title: Earning Type -->
<div class="dev-header">
<a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;">
Version 6.7.7</a>
<a class="btn btn-default btn-sm" href="https://github.com/frappe/erpnext/tree/develop/erpnext/hr/doctype/earning_type"
target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a>
</div>
<p><b>Table Name:</b> <code>tabEarning Type</code></p>
<h3>Fields</h3>
<table class="table table-bordered" style="table-layout: fixed;">
<thead>
<tr>
<th style="width: 5%">Sr</th>
<th style="width: 25%">Fieldname</th>
<th style="width: 20%">Type</th>
<th style="width: 25%">Label</th>
<th style="width: 25%">Options</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td class="danger" title="Mandatory"><code>earning_name</code></td>
<td >
Data</td>
<td >
Name
</td>
<td></td>
</tr>
<tr >
<td>2</td>
<td ><code>description</code></td>
<td >
Small Text</td>
<td >
Description
</td>
<td></td>
</tr>
</tbody>
</table>
<hr>
<h3>Controller</h3>
<h4>erpnext.hr.doctype.earning_type.earning_type</h4>
<h3 style="font-weight: normal;">Class <b>EarningType</b></h3>
<p style="padding-left: 30px;"><i>Inherits from frappe.model.document.Document</i></h4>
<div class="docs-attr-desc"><p></p>
</div>
<div style="padding-left: 30px;">
</div>
<hr>
<h4>Linked In:</h4>
<ul>
<li>
<a href="https://frappe.github.io/erpnext/current/models/hr/salary_slip_earning">Salary Slip Earning</a>
</li>
<li>
<a href="https://frappe.github.io/erpnext/current/models/hr/salary_structure_earning">Salary Structure Earning</a>
</li>
</ul>
<!-- autodoc -->
<!-- jinja -->
<!-- static --> | Java |
// Generated by CoffeeScript 1.10.0
var api, baseOVHKonnector, connector, name, slug;
baseOVHKonnector = require('../lib/base_ovh_konnector');
name = 'Kimsufi EU';
slug = 'kimsufi_eu';
api = {
endpoint: 'kimsufi-eu',
appKey: '',
appSecret: ''
};
connector = module.exports = baseOVHKonnector.createNew(api, name, slug);
| Java |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.enums;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
public enum BeaconIndexType implements EnumAsString {
LOG("Log"),
STATE("State");
private String value;
BeaconIndexType(String value) {
this.value = value;
}
@Override
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public static BeaconIndexType get(String value) {
if(value == null)
{
return null;
}
// goes over BeaconIndexType defined values and compare the inner value with the given one:
for(BeaconIndexType item: values()) {
if(item.getValue().equals(value)) {
return item;
}
}
// in case the requested value was not found in the enum values, we return the first item as default.
return BeaconIndexType.values().length > 0 ? BeaconIndexType.values()[0]: null;
}
}
| Java |
package NonameTV::Importer::TV2;
use strict;
use warnings;
=pod
Import data from Viasat's press-site. The data is downloaded in
tab-separated text-files.
Features:
Proper episode and season fields. The episode-field contains a
number that is relative to the start of the series, not to the
start of this season.
program_type
=cut
use DateTime;
use Date::Parse;
use Encode;
use NonameTV qw/MyGet expand_entities AddCategory norm/;
use NonameTV::DataStore::Helper;
use NonameTV::Log qw/progress error/;
use NonameTV::Importer::BaseWeekly;
use base 'NonameTV::Importer::BaseWeekly';
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = $class->SUPER::new( @_ );
bless ($self, $class);
defined( $self->{UrlRoot} ) or die "You must specify UrlRoot";
my $dsh = NonameTV::DataStore::Helper->new( $self->{datastore},
"Europe/Oslo" );
$self->{datastorehelper} = $dsh;
return $self;
}
sub ImportContent
{
my $self = shift;
my( $batch_id, $cref, $chd ) = @_;
#my $ds = $self->{datastore};
my $dsh = $self->{datastorehelper};
# Decode the string into perl's internal format.
# see perldoc Encode
# my $str = decode( "utf-8", $$cref );
my $str = decode( "iso-8859-1", $$cref );
my @rows = split("\n", $str );
if( scalar( @rows < 2 ) )
{
error( "$batch_id: No data found" );
return 0;
}
my $columns = [ split( "\t", $rows[0] ) ];
my $date = "";
my $olddate = "";
#print ( $batch_id );
for ( my $i = 1; $i < scalar @rows; $i++ )
{
my $inrow = $self->row_to_hash($batch_id, $rows[$i], $columns );
$date = $inrow->{'SENDEDATO'};
if ($date ne $olddate) {
my $ymd = parseDate(fq( $date ));
#print "\n>>>STARTING NEW DATE $ymd <<<\n";
$dsh->StartDate( $ymd );
}
$olddate = $date;
#$date = substr( $date, 0, 10 );
#$date =~ s/\./-/;
#if ( exists($inrow->{'Date'}) )
#{
# $dsh->StartDate( $inrow->{'Date'} );
#}
my $start = $inrow->{'SENDETID'};
#my ($date, $time) = split(/ /, $start);
#$date =~ s/\./-/;
#$time =~ s/\./:/;
#$date = turnDate($date);
#$start = "$date $time";
#print norm($start);
$start = parseStart(fq($start));
#my $start = $inrow->{'Start time'};
#my $start = $starttime;
my $title = norm( $inrow->{'NORSKTITTEL'} );
$title = fq($title);
my $description = fq( norm( $inrow->{'EPISODESYNOPSIS'} ));
if ($description eq "") {
$description = fq( norm( $inrow->{'GENERELL_SYNOPSIS'} ));
}
my $subtitle = fq( norm ($inrow->{'EPISODETITTEL'}));
if ($subtitle eq "") {
$subtitle = fq( norm( $inrow->{'OVERSKRIFT'}))
}
#$description = norm( $description );
#$description = fq( $description );
# Episode info in xmltv-format
#my $ep_nr = norm(fq($inrow->{'EPISODENUMMER'})) || 0;
#my $ep_se = norm(fq($inrow->{'SESONGNUMMER'})) || 0;
#my $episode = undef;
#
#if( ($ep_nr > 0) and ($ep_se > 0) )
#{
# $episode = sprintf( "%d . %d .", $ep_se-1, $ep_nr-1 );
#}
#elsif( $ep_nr > 0 )
#{
# $episode = sprintf( ". %d .", $ep_nr-1 );
#}
my $ce = {
channel_id => $chd->{id},
title => $title,
description => $description,
subtitle => $subtitle,
start_time => $start,
#episode => $episode,
};
if( defined( $inrow->{'PRODUKSJONSAARKOPI'} ) and
$inrow->{'PRODUKSJONSAARKOPI'} =~ /(\d\d\d\d)/ )
{
$ce->{production_date} = "$1-01-01";
}
my $cast = norm( $inrow->{'ROLLEBESKRIVELSE'} );
$cast = fq( $cast );
if( $cast =~ /\S/ )
{
# Remove all variants of m.fl.
$cast =~ s/\s*m[\. ]*fl\.*\b//;
# Remove trailing '.'
$cast =~ s/\.$//;
my @actors = split( /\s*,\s*/, $cast );
foreach (@actors)
{
# The character name is sometimes given in parentheses. Remove it.
# The Cast-entry is sometimes cutoff, which means that the
# character name might be missing a trailing ).
s/\s*\(.*$//;
}
$ce->{actors} = join( ", ", grep( /\S/, @actors ) );
}
my $director = norm( $inrow->{'REGI'} );
$director = fq( $director );
if( $director =~ /\S/ )
{
# Remove all variants of m.fl.
$director =~ s/\s*m[\. ]*fl\.*\b//;
# Remove trailing '.'
$director =~ s/\.$//;
my @directors = split( /\s*,\s*/, $director );
$ce->{directors} = join( ", ", grep( /\S/, @directors ) );
}
#$self->extract_extra_info( $ce );
$dsh->AddProgramme( $ce );
}
# Success
return 1;
}
sub FetchDataFromSite
{
my $self = shift;
my( $batch_id, $data ) = @_;
my( $year, $week ) = ( $batch_id =~ /(\d+)-(\d+)$/ );
my $url = sprintf( "%s_%01d_%s_%02d.xls",
$self->{UrlRoot}, $week, $data->{grabber_info},
$year);
my( $content, $code ) = MyGet( $url );
return( $content, $code );
}
sub row_to_hash
{
my $self = shift;
my( $batch_id, $row, $columns ) = @_;
$row =~ s/\t.$//;
# if $(row)
my @coldata = split( "\t", $row );
my %res;
if( scalar( @coldata ) > scalar( @{$columns} ) )
{
error( "$batch_id: Too many data columns " .
scalar( @coldata ) . " > " .
scalar( @{$columns} ) );
}
for( my $i=0; $i<scalar(@coldata) and $i<scalar(@{$columns}); $i++ )
{
$res{$columns->[$i]} = norm($coldata[$i])
if $coldata[$i] =~ /\S/;
}
return \%res;
}
sub parseStart
{
my ($string) = @_;
#my $string = @$in[0];
#print "PARSESTART: $string\n";
my $day = substr( $string, 0, 2 );
my $mnt = substr( $string, 3, 2 );
my $yr = substr( $string, 6, 4 );
my $hr = substr( $string, 11, 2 );
my $min = substr( $string, 14, 2 );
return ( "$hr:$min:00");
}
sub parseDate
{
my ($string) = @_;
my $day = substr( $string, 0, 2 );
my $mnt = substr( $string, 3, 2 );
my $year = substr( $string, 6, 4 );
return ("$year-$mnt-$day");
}
sub fq
{
# Remove quotes from strings
my ($string) = @_;
$string =~ s/^"//;
$string =~ s/"$//;
return $string;
}
1;
| Java |
//#############################################################################
//# #
//# 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:24
*
*/
package ims.admin.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class ConfigLocationLiteVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.admin.vo.ConfigLocationLiteVo copy(ims.admin.vo.ConfigLocationLiteVo valueObjectDest, ims.admin.vo.ConfigLocationLiteVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Location(valueObjectSrc.getID_Location());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// Name
valueObjectDest.setName(valueObjectSrc.getName());
// Type
valueObjectDest.setType(valueObjectSrc.getType());
// isActive
valueObjectDest.setIsActive(valueObjectSrc.getIsActive());
// Address
valueObjectDest.setAddress(valueObjectSrc.getAddress());
// IsVirtual
valueObjectDest.setIsVirtual(valueObjectSrc.getIsVirtual());
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 #createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.Set domainObjectSet)
{
return createConfigLocationLiteVoCollectionFromLocation(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.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) iterator.next();
ims.admin.vo.ConfigLocationLiteVo 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.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.List domainObjectList)
{
return createConfigLocationLiteVoCollectionFromLocation(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.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.List domainObjectList)
{
ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) domainObjectList.get(i);
ims.admin.vo.ConfigLocationLiteVo 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.core.resource.place.domain.objects.Location 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 extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection)
{
return extractLocationSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection 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.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(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.core.resource.place.domain.objects.Location 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 extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection)
{
return extractLocationList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection 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.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(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.core.resource.place.domain.objects.Location object.
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo create(ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.Location object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.admin.vo.ConfigLocationLiteVo create(DomainObjectMap map, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.admin.vo.ConfigLocationLiteVo valueObject = (ims.admin.vo.ConfigLocationLiteVo) map.getValueObject(domainObject, ims.admin.vo.ConfigLocationLiteVo.class);
if ( null == valueObject )
{
valueObject = new ims.admin.vo.ConfigLocationLiteVo(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.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo insert(ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location 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.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo insert(DomainObjectMap map, ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Location(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// Name
valueObject.setName(domainObject.getName());
// Type
ims.domain.lookups.LookupInstance instance2 = domainObject.getType();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.LocationType voLookup2 = new ims.core.vo.lookups.LocationType(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.LocationType parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.LocationType(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setType(voLookup2);
}
// isActive
valueObject.setIsActive( domainObject.isIsActive() );
// Address
valueObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.create(map, domainObject.getAddress()) );
// IsVirtual
valueObject.setIsVirtual( domainObject.isIsVirtual() );
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.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject)
{
return extractLocation(domainFactory, valueObject, new HashMap());
}
public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Location();
ims.core.resource.place.domain.objects.Location domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(valueObject);
}
// ims.admin.vo.ConfigLocationLiteVo ID_Location field is unknown
domainObject = new ims.core.resource.place.domain.objects.Location();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Location());
if (domMap.get(key) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(key);
}
domainObject = (ims.core.resource.place.domain.objects.Location) domainFactory.getDomainObject(ims.core.resource.place.domain.objects.Location.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_Location());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getName() != null && valueObject.getName().equals(""))
{
valueObject.setName(null);
}
domainObject.setName(valueObject.getName());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getType() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getType().getID());
}
domainObject.setType(value2);
domainObject.setIsActive(valueObject.getIsActive());
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.generic.domain.objects.Address value4 = null;
if ( null != valueObject.getAddress() )
{
if (valueObject.getAddress().getBoId() == null)
{
if (domMap.get(valueObject.getAddress()) != null)
{
value4 = (ims.core.generic.domain.objects.Address)domMap.get(valueObject.getAddress());
}
}
else
{
value4 = (ims.core.generic.domain.objects.Address)domainFactory.getDomainObject(ims.core.generic.domain.objects.Address.class, valueObject.getAddress().getBoId());
}
}
domainObject.setAddress(value4);
domainObject.setIsVirtual(valueObject.getIsVirtual());
return domainObject;
}
}
| Java |
require 'test_helper'
class PolitizacaosControllerTest < ActionController::TestCase
setup do
@politizacao = politizacaos(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:politizacaos)
end
test "should get new" do
get :new
assert_response :success
end
test "should create politizacao" do
assert_difference('Politizacao.count') do
post :create, politizacao: { body: @politizacao.body, title: @politizacao.title }
end
assert_redirected_to politizacao_path(assigns(:politizacao))
end
test "should show politizacao" do
get :show, id: @politizacao
assert_response :success
end
test "should get edit" do
get :edit, id: @politizacao
assert_response :success
end
test "should update politizacao" do
patch :update, id: @politizacao, politizacao: { body: @politizacao.body, title: @politizacao.title }
assert_redirected_to politizacao_path(assigns(:politizacao))
end
test "should destroy politizacao" do
assert_difference('Politizacao.count', -1) do
delete :destroy, id: @politizacao
end
assert_redirected_to politizacaos_path
end
end
| Java |
delete from configuration_settings where key = 'VACCINE_DASHBOARD_DEFAULT_PRODUCT';
INSERT INTO configuration_settings (key, name, groupname, description, value, valueType, displayOrder)
values ('VACCINE_DASHBOARD_DEFAULT_PRODUCT', 'Configure Default vaccine product', 'Dashboard', '','2412', 'TEXT', 1);
delete from configuration_settings where key = 'VACCINE_DASHBOARD_DEFAULT_PERIOD_TREND';
INSERT INTO configuration_settings (key, name, groupname, description, value, valueType, displayOrder)
values ('VACCINE_DASHBOARD_DEFAULT_PERIOD_TREND', 'Configure Default vaccine period trend', 'Dashboard', '','4', 'NUMBER', 1);
| Java |
/* Taken from a very informative blogpost by Eldar Djafarov:
* http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/
*/
(function() {
'use strict';
module.exports = {
/* Forces an update when the underlying Backbone model instance has
* changed. Users will have to implement getBackboneModels().
* Also requires that React is loaded with addons.
*/
__syncedModels: [],
componentDidMount: function() {
// Whenever there may be a change in the Backbone data, trigger a reconcile.
this.getBackboneModels().forEach(this.injectModel, this);
},
componentWillUnmount: function() {
// Ensure that we clean up any dangling references when the component is
// destroyed.
this.__syncedModels.forEach(function(model) {
model.off(null, model.__updater, this);
}, this);
},
injectModel: function(model){
if(!~this.__syncedModels.indexOf(model)){
var updater = function() {
try {
this.forceUpdate();
} catch(e) {
// This means the component is already being updated somewhere
// else, so we just silently go on with our business.
// This is most likely due to some AJAX callback that already
// updated the model at the same time or slightly earlier.
}
}.bind(this, null);
model.__updater = updater;
model.on('add change remove', updater, this);
}
},
bindTo: function(model, key){
/* Allows for two-way databinding for Backbone models.
* Use by passing it as a 'valueLink' property, e.g.:
* valueLink={this.bindTo(model, attribute)} */
return {
value: model.get(key),
requestChange: function(value){
model.set(key, value);
}.bind(this)
};
}
};
})();
| Java |
<?php use_helper('Text') ?>
<?php if (QubitTerm::REFERENCE_ID == $usageType): ?>
<?php if (isset($link)): ?>
<?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('app_ui_label_digitalobject'))))), $link) ?>
<?php else: ?>
<?php echo image_tag($representation->getFullPath(), array('alt' => '')) ?>
<?php endif; ?>
<?php else: ?>
<?php if ($iconOnly): ?>
<?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('app_ui_label_digitalobject'))))), $link) ?>
<?php else: ?>
<div style="width: 100px; text-align: center"/>
<?php if (isset($link)): ?>
<?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('app_ui_label_digitalobject'))))), $link) ?>
<?php else: ?>
<?php echo image_tag($representation->getFullPath(), array('alt' => '')) ?>
<?php endif; ?>
<?php echo wrap_text($digitalObject->name, 15) ?>
</div>
<?php endif; ?>
<?php endif; ?>
| Java |
<?
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
function send_recover_mail ($user) {
global $site_key, $globals;
require_once(mnminclude.'user.php');
$now = time();
$key = md5($user->id.$user->pass.$now.$site_key.get_server_name());
$url = 'http://'.get_server_name().$globals['base_url'].'profile.php?login='.$user->username.'&t='.$now.'&k='.$key;
//echo "$user->username, $user->email, $url<br />";
$to = $user->email;
$subject = _('Recuperación o verificación de la contraseña de '). get_server_name();
$message = $to . _(': para poder acceder sin la clave, conéctate a la siguiente dirección en menos de dos horas:') . "\n\n$url\n\n";
$message .= _('Pasado este tiempo puedes volver a solicitar acceso en: ') . "\nhttp://".get_server_name().$globals['base_url']."login.php?op=recover\n\n";
$message .= _('Una vez en tu perfil, puedes cambiar la clave de acceso.') . "\n" . "\n";
$message .= "\n\n". _('Este mensaje ha sido enviado a solicitud de la dirección: ') . $globals['user_ip'] . "\n\n";
$message .= "-- \n " . _('el equipo de menéame');
$message = wordwrap($message, 70);
$headers = 'Content-Type: text/plain; charset="utf-8"'."\n" . 'X-Mailer: meneame.net/PHP/' . phpversion(). "\n". 'From: meneame.net <web@'.get_server_name().">\n";
//$pars = '-fweb@'.get_server_name();
mail($to, $subject, $message, $headers);
echo '<p><strong>' ._ ('Correo enviado, mira tu buzón, allí están las instrucciones. Mira también en la carpeta de spam.') . '</strong></p>';
return true;
}
?>
| Java |
<?php
class BAInitiativeParser extends RISParser
{
private static $MAX_OFFSET = 5500;
private static $MAX_OFFSET_UPDATE = 200;
public function parse($antrag_id)
{
$antrag_id = IntVal($antrag_id);
if (SITE_CALL_MODE != "cron") echo "- Initiative $antrag_id\n";
if ($antrag_id == 0) {
RISTools::report_ris_parser_error("Fehler BAInitiativeParser", "Initiative-ID 0\n" . print_r(debug_backtrace(), true));
return;
}
$html_details = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen_details.jsp?Id=$antrag_id");
$html_dokumente = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen_dokumente.jsp?Id=$antrag_id");
//$html_ergebnisse = load_file(RIS_BA_BASE_URL . "/RII/RII/ris_antrag_ergebnisse.jsp?risid=" . $antrag_id);
$daten = new Antrag();
$daten->id = $antrag_id;
$daten->datum_letzte_aenderung = new CDbExpression('NOW()');
$daten->typ = Antrag::$TYP_BA_INITIATIVE;
$dokumente = [];
//$ergebnisse = array();
preg_match("/<h3.*>.* +(.*)<\/h3/siU", $html_details, $matches);
if (count($matches) == 2) $daten->antrags_nr = Antrag::cleanAntragNr($matches[1]);;
$dat_details = explode("<h3 class=\"introheadline\">BA-Initiativen-Nummer", $html_details);
$dat_details = explode("<div class=\"formularcontainer\">", $dat_details[1]);
preg_match_all("/class=\"detail_row\">.*detail_label\">(.*)<\/d.*detail_div\">(.*)<\/div/siU", $dat_details[0], $matches);
$betreff_gefunden = false;
for ($i = 0; $i < count($matches[1]); $i++) switch (trim($matches[1][$i])) {
case "Betreff:":
$betreff_gefunden = true;
$daten->betreff = html_entity_decode($this->text_simple_clean($matches[2][$i]), ENT_COMPAT, "UTF-8");
break;
case "Status:":
$daten->status = $this->text_simple_clean($matches[2][$i]);
break;
case "Bearbeitung:":
$daten->bearbeitung = trim(strip_tags($matches[2][$i]));
break;
}
if (!$betreff_gefunden) {
RISTools::report_ris_parser_error("Fehler BAInitiativeParser", "Kein Betreff\n" . $html_details);
throw new Exception("Betreff nicht gefunden");
}
$dat_details = explode("<div class=\"detailborder\">", $html_details);
$dat_details = explode("<!-- seitenfuss -->", $dat_details[1]);
preg_match_all("/<span class=\"itext\">(.*)<\/span.*detail_div_(left|right|left_long)\">(.*)<\/div/siU", $dat_details[0], $matches);
for ($i = 0; $i < count($matches[1]); $i++) if ($matches[3][$i] != " ") switch ($matches[1][$i]) {
case "Zuständiges Referat:":
$daten->referat = $matches[3][$i];
break;
case "Gestellt am:":
$daten->gestellt_am = $this->date_de2mysql($matches[3][$i]);
break;
case "Wahlperiode:":
$daten->wahlperiode = $matches[3][$i];
break;
case "Bearbeitungsfrist:":
$daten->bearbeitungsfrist = $this->date_de2mysql($matches[3][$i]);
break;
case "Registriert am:":
$daten->registriert_am = $this->date_de2mysql($matches[3][$i]);
break;
case "Bezirksausschuss:":
$daten->ba_nr = IntVal($matches[3][$i]);
break;
case "Typ:":
$daten->antrag_typ = strip_tags($matches[3][$i]);
break;
case "TO aufgenommen am:":
$daten->initiative_to_aufgenommen = $this->date_de2mysql($matches[3][$i]);
break;
}
if ($daten->wahlperiode == "") $daten->wahlperiode = "?";
preg_match_all("/<li><span class=\"iconcontainer\">.*title=\"([^\"]+)\"[^>]+href=\"(.*)\".*>(.*)<\/a>/siU", $html_dokumente, $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
$dokumente[] = [
"url" => $matches[2][$i],
"name" => $matches[3][$i],
"name_title" => $matches[1][$i],
];
}
/*
$dat_ergebnisse = explode("<!-- tabellenkopf -->", $html_ergebnisse);
$dat_ergebnisse = explode("<!-- tabellenfuss -->", $dat_ergebnisse[1]);
preg_match_all("<tr>.*bghell tdborder\"><a.*\">(.*)<\/a>.*
*/
if ($daten->ba_nr == 0) {
echo "BA-Initiative $antrag_id: " . "Keine BA-Angabe";
$GLOBALS["RIS_PARSE_ERROR_LOG"][] = "Keine BA-Angabe (Initiative): $antrag_id";
return;
}
$aenderungen = "";
/** @var Antrag $alter_eintrag */
$alter_eintrag = Antrag::model()->findByPk($antrag_id);
$changed = true;
if ($alter_eintrag) {
$changed = false;
if ($alter_eintrag->betreff != $daten->betreff) $aenderungen .= "Betreff: " . $alter_eintrag->betreff . " => " . $daten->betreff . "\n";
if ($alter_eintrag->bearbeitungsfrist != $daten->bearbeitungsfrist) $aenderungen .= "Bearbeitungsfrist: " . $alter_eintrag->bearbeitungsfrist . " => " . $daten->bearbeitungsfrist . "\n";
if ($alter_eintrag->status != $daten->status) $aenderungen .= "Status: " . $alter_eintrag->status . " => " . $daten->status . "\n";
if ($alter_eintrag->fristverlaengerung != $daten->fristverlaengerung) $aenderungen .= "Fristverlängerung: " . $alter_eintrag->fristverlaengerung . " => " . $daten->fristverlaengerung . "\n";
if ($alter_eintrag->initiative_to_aufgenommen != $daten->initiative_to_aufgenommen) $aenderungen .= "In TO Aufgenommen: " . $alter_eintrag->initiative_to_aufgenommen . " => " . $daten->initiative_to_aufgenommen . "\n";
if ($aenderungen != "") $changed = true;
if ($alter_eintrag->wahlperiode == "") $alter_eintrag->wahlperiode = "?";
}
if ($changed) {
if ($aenderungen == "") $aenderungen = "Neu angelegt\n";
echo "BA-Initiative $antrag_id: Verändert: " . $aenderungen . "\n";
if ($alter_eintrag) {
$alter_eintrag->copyToHistory();
$alter_eintrag->setAttributes($daten->getAttributes());
if (!$alter_eintrag->save()) {
var_dump($alter_eintrag->getErrors());
die("Fehler");
}
$daten = $alter_eintrag;
} else {
if (!$daten->save()) {
var_dump($daten->getErrors());
die("Fehler");
}
}
$daten->resetPersonen();
}
foreach ($dokumente as $dok) {
$aenderungen .= Dokument::create_if_necessary(Dokument::$TYP_BA_INITIATIVE, $daten, $dok);
}
if ($aenderungen != "") {
$aend = new RISAenderung();
$aend->ris_id = $daten->id;
$aend->ba_nr = $daten->ba_nr;
$aend->typ = RISAenderung::$TYP_BA_INITIATIVE;
$aend->datum = new CDbExpression("NOW()");
$aend->aenderungen = $aenderungen;
$aend->save();
/** @var Antrag $antrag */
$antrag = Antrag::model()->findByPk($antrag_id);
$antrag->datum_letzte_aenderung = new CDbExpression('NOW()'); // Auch bei neuen Dokumenten
$antrag->save();
$antrag->rebuildVorgaenge();
}
}
public function parseSeite($seite, $first)
{
if (SITE_CALL_MODE != "cron") echo "BA-Initiativen Seite $seite\n";
$text = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen.jsp?Trf=n&Start=$seite");
$txt = explode("<!-- tabellenkopf -->", $text);
$txt = explode("<div class=\"ergebnisfuss\">", $txt[1]);
preg_match_all("/ba_initiativen_details\.jsp\?Id=([0-9]+)[\"'& ]/siU", $txt[0], $matches);
if ($first && count($matches[1]) > 0) RISTools::report_ris_parser_error("BA-Initiativen VOLL", "Erste Seite voll: $seite");
for ($i = count($matches[1]) - 1; $i >= 0; $i--) try {
$this->parse($matches[1][$i]);
} catch (Exception $e) {
echo " EXCEPTION! " . $e . "\n";
}
return $matches[1];
}
public function parseAlle()
{
$anz = static::$MAX_OFFSET;
$first = true;
for ($i = $anz; $i >= 0; $i -= 10) {
if (SITE_CALL_MODE != "cron") echo ($anz - $i) . " / $anz\n";
$this->parseSeite($i, $first);
$first = false;
}
}
public function parseUpdate()
{
echo "Updates: BA-Initiativen\n";
$loaded_ids = [];
$anz = static::$MAX_OFFSET_UPDATE;
for ($i = $anz; $i >= 0; $i -= 10) {
$ids = $this->parseSeite($i, false);
$loaded_ids = array_merge($loaded_ids, array_map("IntVal", $ids));
}
}
public function parseQuickUpdate()
{
}
}
| Java |
#
# Copyright (C) 2019 - 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/>.
#
require "spec_helper"
describe Messages::AssignmentSubmitted::TwitterPresenter do
let(:course) { course_model(name: "MATH-101") }
let(:assignment) { course.assignments.create!(name: "Introductions", due_at: 1.day.ago) }
let(:teacher) { course_with_teacher(course: course, active_all: true).user }
let(:student) do
course_with_user("StudentEnrollment", course: course, name: "Adam Jones", active_all: true).user
end
let(:submission) do
@submission = assignment.submit_homework(student)
assignment.grade_student(student, grade: 5, grader: teacher)
@submission.reload
end
before :once do
PostPolicy.enable_feature!
end
describe "Presenter instance" do
let(:message) { Message.new(context: submission, user: teacher) }
let(:presenter) { Messages::AssignmentSubmitted::TwitterPresenter.new(message) }
context "when the assignment is not anonymously graded" do
it "#body includes the name of the student" do
expect(presenter.body).to include("Adam Jones")
end
it "#link is a url for the submission" do
expect(presenter.link).to eql(
message.course_assignment_submission_url(course, assignment, submission.user_id)
)
end
end
context "when the assignment is anonymously graded" do
before(:each) do
assignment.update!(anonymous_grading: true)
end
context "when grades have not been posted" do
it "#body excludes the name of the student" do
expect(presenter.body).not_to include("Adam Jones")
end
it "#link is a url to SpeedGrader" do
expect(presenter.link).to eq(
message.speed_grader_course_gradebook_url(course, assignment_id: assignment.id, anonymous_id: submission.anonymous_id)
)
end
end
context "when grades have been posted" do
before(:each) do
submission
assignment.unmute!
end
it "#body includes the name of the student" do
expect(presenter.body).to include("Adam Jones")
end
it "#link is a url for the submission" do
expect(presenter.link).to eql(
message.course_assignment_submission_url(course, assignment, submission.user_id)
)
end
end
end
end
describe "generated message" do
let(:message) { generate_message(:assignment_submitted, :twitter, submission, {}) }
let(:presenter) do
msg = Message.new(context: submission, user: teacher)
Messages::AssignmentSubmitted::TwitterPresenter.new(msg)
end
context "when the assignment is not anonymously graded" do
it "#body includes the name of the student" do
expect(message.body).to include("Adam Jones")
end
it "#url is a url for the submission" do
expect(message.url).to include(presenter.link)
end
end
context "when the assignment is anonymously graded" do
before(:each) do
assignment.update!(anonymous_grading: true)
end
context "when grades have not been posted" do
it "#body excludes the name of the student" do
expect(message.body).not_to include("Adam Jones")
end
it "#url is a url to SpeedGrader" do
expect(message.url).to include(presenter.link)
end
end
context "when grades have been posted" do
before(:each) do
submission
assignment.unmute!
end
it "#body includes the name of the student" do
expect(message.body).to include("Adam Jones")
end
it "#url is a url for the submission" do
expect(message.url).to include(presenter.link)
end
end
end
end
end
| Java |
#
# Copyright (C) 2015 - 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/>.
require 'spec_helper'
require_dependency "users/creation_notify_policy"
module Users
describe CreationNotifyPolicy do
describe "#is_self_registration?" do
it "is true when forced" do
policy = CreationNotifyPolicy.new(false, {force_self_registration: '1'})
expect(policy.is_self_registration?).to be(true)
end
it "is opposite the management ability provide" do
policy = CreationNotifyPolicy.new(false, {})
expect(policy.is_self_registration?).to be(true)
policy = CreationNotifyPolicy.new(true, {})
expect(policy.is_self_registration?).to be(false)
end
end
describe "#dispatch!" do
let(:user){ double() }
let(:pseudonym) { double() }
let(:channel){ double() }
context "for self_registration" do
let(:policy){ CreationNotifyPolicy.new(true, {force_self_registration: true}) }
before{ allow(channel).to receive_messages(has_merge_candidates?: false) }
it "sends confirmation notification" do
allow(user).to receive_messages(pre_registered?: true)
expect(pseudonym).to receive(:send_confirmation!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(true)
end
it "sends the registration notification if the user is pending or registered" do
allow(user).to receive_messages(pre_registered?: false, registered?: false)
expect(pseudonym).to receive(:send_registration_notification!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(true)
end
end
context "when the user isn't yet registered" do
before do
allow(user).to receive_messages(registered?: false)
allow(channel).to receive_messages(has_merge_candidates?: false)
end
it "sends the registration notification if should notify" do
policy = CreationNotifyPolicy.new(true, {send_confirmation: '1'})
expect(pseudonym).to receive(:send_registration_notification!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(true)
end
it "doesnt send the registration notification if shouldnt notify" do
policy = CreationNotifyPolicy.new(true, {send_confirmation: '0'})
expect(pseudonym).to receive(:send_registration_notification!).never
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(false)
end
end
context "when the user is registered" do
before{ allow(user).to receive_messages(registered?: true) }
let(:policy){ CreationNotifyPolicy.new(true, {}) }
it "sends the merge notification if there are merge candidates" do
allow(channel).to receive_messages(has_merge_candidates?: true)
expect(channel).to receive(:send_merge_notification!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(false)
end
it "does nothing without merge candidates" do
allow(channel).to receive_messages(has_merge_candidates?: false)
expect(channel).to receive(:send_merge_notification!).never
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(false)
end
end
end
end
end
| Java |
<?
session_start();
// Modificado Junio 2009
/**
* Original en la SSPD en el año 2003
*
* Se añadio compatibilidad con variables globales en Off
* @autor Jairo Losada 2009-05
* @licencia GNU/GPL
*/
foreach ($_GET as $key => $valor) ${$key} = $valor;
foreach ($_POST as $key => $valor) ${$key} = $valor;
define('ADODB_ASSOC_CASE', 1);
$krd = $_SESSION["krd"];
$dependencia = $_SESSION["dependencia"];
$usua_doc = $_SESSION["usua_doc"];
$codusuario = $_SESSION["codusuario"];
$tip3Nombre=$_SESSION["tip3Nombre"];
$tip3desc = $_SESSION["tip3desc"];
$tip3img =$_SESSION["tip3img"];
$verrad = "";
$ruta_raiz = "..";
/*************************************************************************************/
/* ORFEO GPL:Sistema de Gestion Documental http://www.orfeogpl.org */
/* Idea Original de la SUPERINTENDENCIA DE SERVICIOS PUBLICOS DOMICILIARIOS */
/* COLOMBIA TEL. (57) (1) 6913005 [email protected] */
/* =========================== */
/* */
/* Este programa es software libre. usted puede redistribuirlo y/o modificarlo */
/* bajo los terminos de la licencia GNU General Public publicada por */
/* la "Free Software Foundation"; Licencia version 2. */
/* */
/* Copyright (c) 2005 por : */
/* SSPS "Superintendencia de Servicios Publicos Domiciliarios" */
/* Jairo Hernan Losada [email protected] Desarrollador */
/* Sixto Angel Pinz�n L�pez --- [email protected] Desarrollador */
/* C.R.A. "COMISION DE REGULACION DE AGUAS Y SANEAMIENTO AMBIENTAL" */
/* Liliana Gomez [email protected] Desarrolladora */
/* Lucia Ojeda [email protected] Desarrolladora */
/* D.N.P. "Departamento Nacional de Planeaci�n" */
/* Hollman Ladino [email protected] Desarrollador */
/* */
/* Colocar desde esta lInea las Modificaciones Realizadas Luego de la Version 3.5 */
/* Nombre Desarrollador Correo Fecha Modificacion */
/*************************************************************************************/
$ruta_raiz = "..";
$verrad = "";
include_once "$ruta_raiz/include/db/ConnectionHandler.php";
$db = new ConnectionHandler($ruta_raiz);
if(!$tipo_archivo) $tipo_archivo = 0; //Para la consulta a archivados
/*********************************************************************************
* Filename: prestamo.php
* Modificado:
* 1/3/2006 IIAC Basado en pedido.php. Facilita la b�squeda de los
* registros de pr�stamo.
*********************************************************************************/
//===============================
// prestamo begin
//===============================
// Inicializa, oculta o presenta los par�metros de b�squeda dependiendo de la opci�n del men� de pr�stamos seleccionada
// prestamo CustomIncludes begin
include ("common.php");
// Save Page and File Name available into variables
$sFileName = "prestamo.php";
// Variables de control
$opcionMenu=strip($_POST["opcionMenu"]); //opci�n seleccionada del men�
$pageAnt=strip($_POST["sFileName"]);
$ver=$_POST["s_sql"]; //consulta
// HTML Page layout
?>
<html>
<head>
<title>Prestamos ORFEO</title>
<link rel="stylesheet" href="<?=$ruta_raiz?>/estilos/orfeo.css" type="text/css">
<!--Necesario para hacer visible el calendario -->
<script src="<?=$ruta_raiz?>/js/popcalendar.js"></script>
<div id="spiffycalendar" class="text"></div>
<link rel="stylesheet" type="text/css" href="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.css">
</head>
<body class="PageBODY">
<div align="center">
<table>
<tr>
<td valign="top"><?php Search_Show(); ?></td>
</tr>
</table>
<table>
<tr>
<td valign="top"><?php if($ver=="") Pedidos_Show(); ?></td>
</tr>
</table>
</div>
</body>
</html>
<?php
//===============================
// prestamo end
//===============================
//===============================
// Search_Show begin
//===============================
function Search_Show(){
// De sesi�n
global $db;
global $ruta_raiz;
// Control de visualizaci�n
$sFileName = $_POST["sFileName"];
$opcionMenu = $_POST["opcionMenu"];
// Valores
$fechaFinal = $_POST["fechaFinal"];
$fechaInicial = $_POST["fechaInicial"];
foreach ($_GET as $key => $valor) ${$key} = $valor;
foreach ($_POST as $key => $valor) ${$key} = $valor;
$krd = $_SESSION["krd"];
$dependencia = $_SESSION["dependencia"];
$usua_doc = $_SESSION["usua_doc"];
// Inicializaci�n de la fecha a partir de la cual se cancelan las solicitudes
if ($fechaInicial=="") {
$hastaXDias=strtotime("-30 day");
$fechaInicial=date("Y-m-d",$hastaXDias);
}
if ($fechaFinal=="") {
if ($opcionMenu==3) {
$query="select PARAM_VALOR,PARAM_NOMB from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_DIAS_CANC'";
$rs = $db->conn->query($query);
if(!$rs->EOF) {
$x = $rs->fields("PARAM_VALOR"); // d�as por defecto
$haceXDias = strtotime("-".$x." day");
$fechaFinal=date("Y-m-d",$haceXDias);
}
if ($pageAnt!=$sFileName) { // inicializaci�n del tiempo
$v_hora_limite=date("h");
$v_minuto_limite=date("i");
$v_meridiano=date("A");
}
}
else{ $fechaFinal=date("Y-m-d"); }
}
// Set variables with search parameters
$flds_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]);
$flds_RADI_NUME_RADI=strip($_POST["s_RADI_NUME_RADI"]);
$flds_USUA_LOGIN =strip($_POST["s_USUA_LOGIN"]);
if ($opcionMenu==4) { $flds_USUA_LOGIN=$krd; } // Inicializa el usuario para el caso en que el ingresa por la opci�n de SOLICITADOS
$flds_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]);
$flds_USUA_NOMB =strip($_POST["s_USUA_NOMB"]);
$flds_PRES_REQUERIMIENTO=strip($_POST["s_PRES_REQUERIMIENTO"]);
if ($v_hora_limite=="") { $v_hora_limite =strip($_POST["s_hora_limite"]); }
if ($v_minuto_limite==""){ $v_minuto_limite=strip($_POST["s_minuto_limite"]); }
if ($v_meridiano=="") { $v_meridiano =strip($_POST["s_meridiano"]); }
// Inicializa el titulo y la visibilidad de los criterios de b�squeda
include_once "inicializarForm.inc";
// Form display
?>
<form method="post" action="prestamo.php" name="busqueda">
<!-- de sesi�n !-->
<input type="hidden" value=" " name="radicado">
<input type="hidden" value="" name="s_sql">
<!-- control de visualizaci�n !-->
<input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>">
<input type="hidden" name="sFileName" value="">
<!-- orden de presentaci�n del resultado !-->
<input type="hidden" name="FormPedidos_Sorting" value="1">
<input type="hidden" name="FormPedidos_Sorted" value="0">
<input type="hidden" name="s_Direction" value=" DESC ">
<!-- control de paginaci�n !-->
<input type="hidden" name="FormPedidos_Page" value="1">
<input type="hidden" name="FormStarPage" value="1">
<input type="hidden" name="FormSiguiente" value="0">
<script>
//Inicializa el formulario
function limpiar() {
document.busqueda.action="menu_prestamo.php";
document.busqueda.submit();
}
//Presenta los usuarios segun la dependencia seleccionada
var codUsuaSel="<?=$flds_USUA_NOMB?>";
</script>
<!--Calendario-->
<script language="JavaScript" src="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.js"></script>
<script language="javascript">
setRutaRaiz ('<?=$ruta_raiz?>');
</script>
<table border=0 cellpadding=0 cellspacing=2 class='borde_tab'>
<tr>
<td class="titulos4" colspan="2"><a name="Search"><?=$sFormTitle[$opcionMenu]; ?> </a></td>
</tr>
<tr id="b0" style="display:<?= $tipoBusqueda[$opcionMenu][0]; ?>">
<td class="titulos3"><p align="left">Radicado</p></td>
<td class="listado5"><input type="text" name="s_RADI_NUME_RADI" maxlength="15" value="<?= $flds_RADI_NUME_RADI; ?>" size="25" class="tex_area"></td>
</tr>
<tr id="b1" style="display:<?= $tipoBusqueda[$opcionMenu][1]; ?>">
<td class="titulos3"><p align="left">Login de Usuario</p></td>
<td class="listado5"><input type="text" name="s_USUA_LOGIN" maxlength="15" value="<?= $flds_USUA_LOGIN; ?>" size="25" class="tex_area"></td>
</tr>
<tr id="b2" style="display:<?= $tipoBusqueda[$opcionMenu][2]; ?>">
<td class="titulos3"><p align="left">Dependencia</p></td>
<td class="listado5"><select name="s_DEPE_NOMB" class="select" onChange=" document.busqueda.s_sql.value='no'; document.busqueda.submit(); ">
<option value="">- TODAS LAS DEPENDENCIAS -</option>
<?
$lookup_s = db_fill_array("select DEPE_CODI,DEPE_NOMB from DEPENDENCIA order by 2");
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $flds_DEPE_NOMB) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"$key\">".strtoupper($value)."</option>";
}
} ?>
</select></td>
</tr>
<tr id="b3" style="display:<?= $tipoBusqueda[$opcionMenu][3]; ?>">
<td class="titulos3"><p align="left">Usuario</p></td>
<td class="listado5"><select name="s_USUA_NOMB" class=select>
<option value="">- TODOS LOS USUARIOS -</option>
<? $validUsuaActiv="";
// Modificado Infom�trika 14-Julio-2009
// Compatibilidad con PostgreSQL 8.3
// Cambi� USUA_ESTA=1 por USUA_ESTA='1' para listar los usuarios activos.
if ($opcionMenu==1) { $validUsuaActiv=" USUA_ESTA='1' "; }ELSE { $validUsuaActiv=" USUA_LOGIN IS NOT NULL "; } //Verifica que el usuario se encuentre activo para hacer el prEstamo
if ($flds_DEPE_NOMB != "") $tmp = " AND DEPE_CODI= ".$flds_DEPE_NOMB; else $tmp = "";
$lookup_s = db_fill_array("select USUA_LOGIN,USUA_NOMB from USUARIO where ".$validUsuaActiv.$tmp);
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $flds_USUA_NOMB) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"$key\">".strtoupper($value)."</option>";
}
} ?>
</select></td>
</tr>
<tr id="b4" style="display:<?= $tipoBusqueda[$opcionMenu][4]; ?>">
<td class="titulos3"><p align="left">Requerimiento</p></td>
<td class="listado5"><select name="s_PRES_REQUERIMIENTO" class=select>
<option value="">- TODOS LOS TIPOS -</option>
<? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_REQUERIMIENTO' order by PARAM_VALOR desc");
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $flds_PRES_REQUERIMIENTO)
$option="<option SELECTED value=\"$key\">".strtoupper($value)."</option>";
else
$option="<option value=\"$key\">".strtoupper($value)."</option>";
echo $option;
}
} ?>
</select></td>
</tr>
<tr id="b5" style="display:<?= $tipoBusqueda[$opcionMenu][5]; ?>">
<td class="titulos3"><p align="left">Estado</p></td>
<td class="listado5"><select name="s_PRES_ESTADO" class=select>
<option value="">- TODOS LOS ESTADOS -</option>
<? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_ESTADO' order by PARAM_VALOR");
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $flds_PRES_ESTADO) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"$key\">".strtoupper($value)."</option>";
}
}
if($flds_PRES_ESTADO == -1) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"-1\">VENCIDO</option>"; ?>
</select></td>
</tr>
<tr id="b6" style="display:<?= $tipoBusqueda[$opcionMenu][6]; ?>">
<td class="titulos3"><p align="left">Fecha inicial<br> (aaaa-mm-dd)</p></td>
<td class="listado5"><script language="javascript">
var dateAvailable1 = new ctlSpiffyCalendarBox("dateAvailable1", "busqueda","fechaInicial","btnDate1","<?=$fechaInicial?>",scBTNMODE_CUSTOMBLUE);
dateAvailable1.writeControl();
dateAvailable1.dateFormat="yyyy-MM-dd";
</script></td>
</tr>
<tr id="b7" style="display:<?= $tipoBusqueda[$opcionMenu][7]; ?>">
<td class="titulos3"><p align="left">Fecha final<br> (aaaa-mm-dd)</p></td>
<td class="listado5"><script language="javascript">
var dateAvailable2 = new ctlSpiffyCalendarBox("dateAvailable2", "busqueda","fechaFinal","btnDate2","<?=$fechaFinal?>",scBTNMODE_CUSTOMBLUE);
dateAvailable2.writeControl();
dateAvailable2.dateFormat="yyyy-MM-dd";
</script>
</td>
</tr>
<tr id="b8" style="display:<?= $tipoBusqueda[$opcionMenu][8]; ?>">
<td class="titulos3"><p align="left">Hora límite<br> (hh:mm m)</p></td>
<td class="listado5"><select name="s_hora_limite" class=select>
<? for ($i=1; $i<=12; $i++) {
if ($i<=9) { $h="0".$i; }
else { $h="".$i; }
$seleccion="";
if ($h==$v_hora_limite) { $seleccion="SELECTED"; } ?>
<option <?= $seleccion; ?> value="<?= $h;?>"><?= $h;?></option>
<? } ?>
</select> :
<select name="s_minuto_limite" class=select>
<? for ($i=0; $i<=59; $i++) {
if ($i<=9) { $h="0".$i; }
else { $h="".$i; }
$seleccion="";
if ($h==$v_minuto_limite) { $seleccion="SELECTED"; } ?>
<option <?= $seleccion; ?> value="<?= $h;?>"> <?= $h;?></option>
<? } ?>
</select> :
<select name="s_meridiano" class=select>
<? if ($v_meridiano=="AM") {?>
<option value="AM" selected>am</option>
<option value="PM">pm</option>
<? }
else {?>
<option value="AM">am</option>
<option value="PM" selected>pm</option>
<? } ?>
</select>
</tr>
<tr>
<td class="titulos3" colspan="2">
<? if ($opcionMenu==0 || $opcionMenu==4) {?>
<input type="reset" class='botones' value="Limpiar" onClick="javascript: limpiar();">
<input type="submit" class='botones' value="Generar">
<? }
else {?>
<input type="submit" class='botones' value="Buscar">
<? }?>
</td>
</tr>
</table>
</form>
<?
} //end function
//===============================
// Search_Show end
//===============================
//===============================
// Pedidos_Show begin
//===============================
function Pedidos_Show(){
// De sesi�n
global $db;
global $ruta_raiz;
// Control de visualizaci�n
global $sFileName;
global $opcionMenu;
global $pageAnt; // Pagina de la cual viene
// Valores
$sFileName = $_POST["sFileName"];
$opcionMenu = $_POST["opcionMenu"];
// Valores
$fechaFinal = $_POST["fechaFinal"];
$fechaInicial = $_POST["fechaInicial"];
$krd = $_SESSION["krd"];
$dependencia = $_SESSION["dependencia"];
$usua_doc = $_SESSION["usua_doc"];
// Set variables with search parameters
$ps_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]);
$ps_RADI_NUME_RADI=strip(trim($_POST["s_RADI_NUME_RADI"]));
// Modificado Infom�trika 14-Julio-2009
// A la variable $ps_USUA_LOGIN se le asigna el valor de $_POST["s_USUA_LOGIN"] para
// realizar la consulta, por Login de Usuario, de los radicados solicitados para pr�stamo.
//$ps_USUA_LOGIN =$krd;
$ps_USUA_LOGIN = strip($_POST['s_USUA_LOGIN']); ;
$ps_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]);
$ps_USUA_NOMB =strip($_POST["s_USUA_NOMB"]);
$ps_hora_limite =strip($_POST["s_hora_limite"]);
$ps_minuto_limite =strip($_POST["s_minuto_limite"]);
$ps_meridiano =strip($_POST["s_meridiano"]);
$ps_PRES_REQUERIMIENTO=strip($_POST["s_PRES_REQUERIMIENTO"]);
if (strlen($pageAnt)==0){
// Build SQL
include_once $ruta_raiz."/include/query/prestamo/builtSQL1.inc";
include_once $ruta_raiz."/include/query/prestamo/builtSQL2.inc";
include_once $ruta_raiz."/include/query/prestamo/builtSQL3.inc";
// Build ORDER statement
$iSort=strip(get_param("FormPedidos_Sorting"));
if(!$iSort) $iSort =20;
$iSorted=strip(get_param("FormPedidos_Sorted"));
$sDirection=strip(get_param("s_Direction"));
if ($iSorted!=$iSort){ $sDirection=" DESC ";}
else {
if(strcasecmp($sDirection," DESC ")==0){ $sDirection=" ASC "; }
else { $sDirection=" DESC "; }
}
$sOrder=" order by ".$iSort.$sDirection.",PRESTAMO_ID";
// Inicializa el titulo y la visibilidad de los resultados
include_once "inicializarRTA.inc";
// Execute SQL statement
$db->conn->SetFetchMode(ADODB_FETCH_ASSOC);
$rs=$db->query($sSQL.$sOrder);
$db->conn->SetFetchMode(ADODB_FETCH_NUM);
// Process empty recordset
if(!$rs || $rs->EOF) { ?>
<p align="center" class="titulosError2">NO HAY REGISTROS SELECCIONADOS</p>
<? return;
}
// Build parameters for order
$form_params_search = "s_RADI_NUME_RADI=".tourl($ps_RADI_NUME_RADI)."&s_USUA_LOGIN=".tourl($ps_USUA_LOGIN).
"&s_DEPE_NOMB=".tourl($ps_DEPE_NOMB)."&s_USUA_NOMB=".tourl($ps_USUA_NOMB)."&s_PRES_REQUERIMIENTO=".
tourl($ps_PRES_REQUERIMIENTO)."&s_PRES_ESTADO=".tourl($ps_PRES_ESTADO)."&fechaInicial=".
tourl($fechaInicial)."&fechaFinal=".tourl($fechaFinal)."&s_hora_limite=".tourl($ps_hora_limite).
"&s_minuto_limite=".tourl($ps_minuto_limite)."&s_meridiano=".tourl($ps_meridiano);
$form_params_page = "&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0";
$form_params=$form_params_search.$form_params_page."&opcionMenu=".tourl($opcionMenu)."&krd=".tourl($krd).
"&FormPedidos_Sorted=".tourl($iSort)."&s_Direction=".tourl($sDirection)."&FormPedidos_Sorting=";
// HTML column prestamo headers
?>
<form method="post" action="prestamo.php" name="rta">
<input type="hidden" value='<?=$krd?>' name="krd">
<input type="hidden" value=" " name="radicado">
<input type="hidden" value="" name="prestado">
<input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>">
<!-- orden de presentaci�n del resultado en el formulario de envio !-->
<input type="hidden" name="FormPedidos_Sorting" value="<?=$iSort?>">
<input type="hidden" name="FormPedidos_Sorted" value="<?=$iSorted?>">
<input type="hidden" name="s_Direction" value="<?=$sDirection?>">
<table border=0 cellpadding=0 cellspacing=2 class='borde_tab' width="100%">
<tr>
<td class="titulos4" colspan="<?=$numCol?>"><a name="Search"><?= $tituloRespuesta[$opcionMenu]?></a></td>
</tr>
<?PHP // Titulos de las columnas
include_once "inicializarTabla.inc";
//----------------------
// Process page scroller
//----------------------
// Initialize records per page
$iRecordsPerPage = 15;
// Inicializa el valor de la pagina actual
$iPage=intval(get_param("FormPedidos_Page"));
// Inicializa los registros a presentar seg�n la p�gina actual
$iCounter = 0;
$ant="";
if($iPage > 1) {
do{
$new=$rs->fields["PRESTAMO_ID"];
if ($new!=$ant) {
$iCounter++;
$ant=$new;
}
$rs->MoveNext();
}while ($iCounter < ($iPage - 1) * $iRecordsPerPage && !$rs->EOF);
}
$iCounterIni=$iCounter;
// Display grid based on recordset
$y=0; // Cantidad de registros presentados
include_once "getRtaSQLAntIn.inc"; //Une en un solo campo los expedientes
while($rs && !$rs->EOF && $y<$iRecordsPerPage) {
// Inicializa las variables con los resultados
include "getRtaSQL.inc";
if ($antfldPRESTAMO_ID!=$fldPRESTAMO_ID) { //Une en un solo campo los expedientes
if ($y!=0) { include "cuerpoTabla.inc"; } // Fila de la tabla con los resultados
include "getRtaSQLAnt.inc";
$y++;
}
else {
if ($antfldEXP!=""){
$antfldEXP.="<br>";
$antfldARCH.="<br>";
}
$antfldEXP.=$fldEXP;
if ($fldARCH=='SI') {
$encabARCH = session_name()."=".session_id()."&buscar_exp=".tourl($fldEXP)."&krd=$krd&tipo_archivo=&nomcarpeta=";
$antfldARCH.="<a href='".$ruta_raiz."/expediente/datos_expediente.php?".$encabARCH."&num_expediente=".tourl($fldEXP)."&nurad=".tourl($antfldRADICADO)."' class='vinculos'>".$fldARCH."</a>";
}
else { $antfldARCH.=$fldARCH; }
}
$rs->MoveNext();
}
if ($y!=0) {
include "cuerpoTabla.inc"; // Fila de la tabla con lso resultados
$y++;
}
$cantRegPorPagina=$y;
$iCounter=$iCounter+$y;
?>
<script>
// Inicializa el arreglo con los radicados a procesar
var cantRegPorPagina=<?=$cantRegPorPagina-1?>;
// Marca todas las casillas si la del titulo es marcada
function seleccionarRta() {
valor=document.rta.rta_.checked;
<? for ($j=0; $j<$cantRegPorPagina; $j++) { ?>
document.rta.rta_<?=$j?>.checked=valor;
<? } ?>
}
// Valida y envia el formulario
function enviar() {
var cant=0;
for (i=0; i<cantRegPorPagina; i++) {
if (eval('document.rta.rta_'+i+'.checked')==true){
cant=1;
break;
}
}
if (cant==0) { alert("Debe seleccionar al menos un radicado"); }
else {
document.rta.prestado.value=cantRegPorPagina;
document.rta.action="formEnvio.php";
document.rta.submit();
}
}
// Regresa al men� de pr�stamos
function regresar() {
document.rta.opcionMenu.value="";
document.rta.action="menu_prestamo.php";
document.rta.submit();
}
</script>
<?
// Build parameters for page
if (strcasecmp($sDirection," DESC ")==0){ $sDirectionPages=" ASC "; }
else { $sDirectionPages=" DESC "; }
$form_params_page = $form_params_search."&opcionMenu=".tourl($opcionMenu)."&FormPedidos_Sorted=".tourl($iSort).
"&s_Direction=".tourl($sDirectionPages)."&krd=".tourl($krd)."&FormPedidos_Sorting=".tourl($iSort);
// N�mero total de registros
$ant=$antfldPRESTAMO_ID;
while($rs && !$rs->EOF) {
$new=$rs->fields["PRESTAMO_ID"]; //para el manejo de expedientes
if ($new!=$ant) {
$ant=$new;
$iCounter++;
}
$rs->MoveNext();
}
$iCounter--;
// Inicializa p�ginas visualizables
$iNumberOfPages=10;
// Inicializa cantidad de p�ginas
$iHasPages=intval($iCounter/$iRecordsPerPage);
if ($iCounter%$iRecordsPerPage!=0) { $iHasPages++; }
// Determina la p�gina inicial del intervalo
$iStartPages=1;
$FormSiguiente=get_param("FormSiguiente"); //Indica si (1) el n�mero de p�ginas es mayor al visualizable
if($FormSiguiente==0) { $iStartPages=get_param("FormStarPage"); }
elseif($FormSiguiente==-1){ $iStartPages=$iPage; }
else {
if($iPage>$iNumberOfPages) { $iStartPages=$iPage-$iNumberOfPages+1; }
}
// Genera las p�ginas visualizables
$sPages= "";
if($iHasPages>$iNumberOfPages) {
if($iStartPages==1){ $sPages.="|< << "; }
else{
$sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0&\">
<font class=\"ColumnFONT\" title=\"Ver la primera página\">|<</font></a> ";
$sPages.=" <a href=\"$sFileName?$form_params_page&FormPedidos_Page=".tourl($iStartPages-1)."&FormStarPage=".
tourl($iStartPages-1)."&FormSiguiente=-1&\"><font class=\"ColumnFONT\" title=\"Ver la página ".
($iStartPages-1)."\"><<</font></a> ";
}
}
for($iPageCount=$iStartPages; $iPageCount<($iStartPages+$iNumberOfPages); $iPageCount++) {
if ($iPageCount<=$iHasPages) {
$sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages)."&FormSiguiente=0&\">
<font class=\"ColumnFONT\" title=\"Ver la página ".$iPageCount."\">".$iPageCount."</font></a> ";
}
else { break; }
}
if($iHasPages>$iNumberOfPages) {
if($iPageCount-1<$iHasPages){
$sPages.="... <a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages).
"&FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la página ".$iPageCount."\">>></font></a> ";
$sPages.=" <a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iHasPages&FormStarPage=tourl($iStartPages)
&FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la última página\">>|</font></a>";
}
else { $sPages.=" >> >|"; }
}
?>
<tr class="titulos5" align="center">
<td class="leidos" colspan="<?=($numCol+1);?>"><center><br><?=$sPages?><br><br>Página <?=$iPage?>/<?=$iHasPages?><br>
Total de Registros: <?=$iCounter?><br> </center></td>
</tr>
<? // Botones para procesar
if ($tipoRespuesta[$opcionMenu][$numRtaMax]=="") {?>
<tr class="titulos4" align="center">
<td class="listado1" colspan="<?=($numCol+1);?>" align="center"><center>
<input type="button" class='botones' value="<?=$tituloSubmitRta[$opcionMenu]?>" onClick="javascript:enviar();">
<input type="button" class='botones' value="Cancelar" title="Regresa al menú de préstamo y control de documentos" onClick="javascript:regresar();"></center>
</td>
</tr>
<? }?>
</table>
</form>
<?
} //fin if
} //fin function
//===============================
// Pedidos_Show end
//===============================
?>
| Java |
package org.ownprofile.boundary.owner.client;
public class Result<T> {
private boolean isSuccess;
private T successValue;
private Fail fail;
public static Result<Void> success() {
return success(null);
}
public static <S> Result<S> success(S successValue) {
return new Result<S>(successValue);
}
public static <S> Result<S> fail(String message) {
return fail((Throwable)null, "%s", message);
}
public static <S> Result<S> fail(Throwable cause, String message) {
return fail(cause, "%s", message);
}
public static <S> Result<S> fail(String format, Object... args) {
return fail(null, format, args);
}
public static <S> Result<S> fail(Throwable cause, String format, Object... args) {
final Fail f = new Fail(cause, format, args);
return new Result<S>(f);
}
private Result(T successValue) {
this.isSuccess = true;
this.successValue = successValue;
}
private Result(Fail fail) {
this.isSuccess = false;
this.fail = fail;
}
public boolean isSuccess() {
return isSuccess;
}
public boolean isFail() {
return !isSuccess;
}
public T getSuccessValue() {
if (isSuccess) {
return successValue;
} else {
throw new IllegalStateException(String.format("Result is Fail: %s", fail));
}
}
public Fail getFail() {
if (isSuccess) {
throw new IllegalStateException(String.format("Result is Success"));
} else {
return fail;
}
}
@Override
public String toString() {
return String.format("%s: %s",
isSuccess ? "SUCCESS" : "FAIL",
isSuccess ? successValue : fail);
}
// ------------------------------
public static class Fail {
private String message;
private Throwable cause;
private Fail(Throwable cause, String message) {
this.cause = cause;
this.message = message;
}
private Fail(Throwable cause, String format, Object... args) {
this(cause, String.format(format, args));
}
public String getMessage() {
return message;
}
public Throwable getCause() {
return cause;
}
@Override
public String toString() {
return String.format("%s - %s", message, cause);
}
}
}
| Java |
<?php
use Illuminate\Database\Migrations\Migration;
class AddDomainIdToBusinessesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('businesses', function ($table) {
$table->integer('domain_id')->unsigned()->nullable()->after('category_id');
$table->foreign('domain_id')->references('id')->on('domains')->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('businesses', function ($table) {
$table->dropForeign('businesses_domain_id_foreign');
$table->dropColumn('domain_id');
});
}
}
| Java |
# -*- coding: utf-8 -*-
from .base import BaseHandler
class TestRoute(BaseHandler):
def get(self, file):
return self.render(str(file) + '.jade', show_h1=1)
| Java |
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
module AWS
module Core
class PageResult < Array
# @return [Collection] Returns the collection that was used to
# populated this page of results.
attr_reader :collection
# @return [Integer] Returns the maximum number of results per page.
# The final page in a collection may return fewer than +:per_page+
# items (e.g. +:per_page+ is 10 and there are only 7 items).
attr_reader :per_page
# @return [String] An opaque token that can be passed the #page method
# of the collection that returned this page of results. This next
# token behaves as a pseudo offset. If +next_token+ is +nil+ then
# there are no more results for the collection.
attr_reader :next_token
# @param [Collection] collection The collection that was used to
# request this page of results. The collection should respond to
# #page and accept a :next_token option.
#
# @param [Array] items An array of result items that represent a
# page of results.
#
# @param [Integer] per_page The number of requested items for this
# page of results. If the count of items is smaller than +per_page+
# then this is the last page of results.
#
# @param [String] next_token (nil) A token that can be passed to the
#
def initialize collection, items, per_page, next_token
@collection = collection
@per_page = per_page
@next_token = next_token
super(items)
end
# @return [PageResult]
# @raise [RuntimeError] Raises a runtime error when called against
# a collection that has no more results (i.e. #last_page? == true).
def next_page
if last_page?
raise 'unable to get the next page, already at the last page'
end
collection.page(:per_page => per_page, :next_token => next_token)
end
# @return [Boolean] Returns +true+ if this is the last page of results.
def last_page?
next_token.nil?
end
# @return [Boolean] Returns +true+ if there are more pages of results.
def more?
!!next_token
end
end
end
end
| Java |
# FlareDNS-client
Synchronize your App dynamic IP with your CloudFlare DNS A records.
Use this package if:
* You use [CloudFlare](https://cloudflare.com "CloudFlare").
* You run your Laravel App on a server with a Dynamic IP or your IP changes often.
## Installation
```
composer require thinkingcircles/flaredns-client
```
```php
// config/app.php
'providers' => [
// Other service providers...
ThinkingCircles\FlareDNSClient\FlareDNSClientServiceProvider::class,
]
```
```
php artisan vendor:publish --provider="ThinkingCircles\FlareDNSClient\FlareDNSClientServiceProvider"
```
## Get CloudFlare api keys
## Configuration
```php
// .env
cloudflare_zone_id=
cloudflare_global_api_key=
cloudflare_api_email=
```
:or
```php
// config/flaredns-client.php
<?php return [
'cloudflare_api_account' => [
'cloudflare_zone_id' => 'ZONE-ID',
'cloudflare_global_api_key' => 'API-KEY',
'cloudflare_api_email' => 'API-EMAIL',
'dns_records' => [
//will match id or name
['id'=>null, 'name'=>'domain.net'],
['id'=>'CloudFlare-API-Record-ID', 'name'=>null]
]
]
];
```
## Cron Setup - [Laravel 5.4 - Scheduling](https://laravel.com/docs/5.4/scheduling)
```
// Cron if you have not setup already
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
```
## Usage
```php
// App/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('flarednsclient:ipsync')->everyFiveMinutes();
}
```
## Todo
- [x] Debug
- [ ] Clean up code
- [ ] Improve logic
- [ ] Make UI [FlareDNS Management UI](https://www.github.com/ThinkingCircles/FlareDNS "FlareDNS Management UI") | Java |
<?php
/**
* DAO tbMovimentacaoBancaria
* @author emanuel.sampaio - Politec
* @since 17/02/2011
* @version 1.0
* @package application
* @subpackage application.model
* @copyright © 2011 - Ministério da Cultura - Todos os direitos reservados.
* @link http://www.cultura.gov.br
*/
class tbMovimentacaoBancaria extends GenericModel
{
/* dados da tabela */
protected $_banco = "SAC";
protected $_schema = "dbo";
protected $_name = "tbMovimentacaoBancaria";
/**
* Método para buscar
* @access public
* @param string $pronac
* @param boolean $conta_rejeitada
* @param array $periodo
* @param array $operacao
* @return object
*/
public function buscarDados($pronac = null, $conta_rejeitada = null, $periodo = null, $operacao = null ,$tamanho=-1, $inicio=-1, $count = null)
{
$select = $this->select();
$select->setIntegrityCheck(false);
if(isset($count)){
$select->from(
array("mi" => "tbMovimentacaoBancariaItem"),
array("total" => "count(*)"));
} else {
$select->from(
array("mi" => "tbMovimentacaoBancariaItem")
,array("m.nrBanco"
,"CONVERT(CHAR(10), m.dtInicioMovimento, 103) AS dtInicioMovimento"
,"CONVERT(CHAR(10), m.dtFimMovimento, 103) AS dtFimMovimento"
,"mi.idMovimentacaoBancaria"
,"mi.tpRegistro"
,"mi.nrAgencia"
,"mi.nrDigitoConta"
,"mi.nmTituloRazao"
,"mi.nmAbreviado"
,"CONVERT(CHAR(10), mi.dtAberturaConta, 103) AS dtAberturaConta"
,"mi.nrCNPJCPF"
,"n.Descricao AS Proponente"
,"mi.vlSaldoInicial"
,"mi.tpSaldoInicial"
,"mi.vlSaldoFinal"
,"mi.tpSaldoFinal"
,"CONVERT(CHAR(10), mi.dtMovimento, 103) AS dtMovimento"
,"mi.cdHistorico"
,"mi.dsHistorico"
,"mi.nrDocumento"
,"mi.vlMovimento"
,"mi.cdMovimento"
,"mi.idMovimentacaoBancariaItem"
,"ti.idTipoInconsistencia"
,"ti.dsTipoInconsistencia"
,"(p.AnoProjeto+p.Sequencial) AS pronac"
,"p.NomeProjeto"
,"bc.Descricao AS nmBanco")
);
}
$select->joinInner(
array("m" => $this->_name)
,"m.idMovimentacaoBancaria = mi.idMovimentacaoBancaria"
,array()
);
if(!empty($conta_rejeitada) && $conta_rejeitada){
$select->joinInner(
array("mx" => "tbMovimentacaoBancariaItemxTipoInconsistencia")
,"mi.idMovimentacaoBancariaItem = mx.idMovimentacaoBancariaItem"
,array()
);
$select->joinInner(
array("ti" => "tbTipoInconsistencia")
,"ti.idTipoInconsistencia = mx.idTipoInconsistencia"
,array()
);
} else {
$select->joinLeft(
array("mx" => "tbMovimentacaoBancariaItemxTipoInconsistencia")
,"mi.idMovimentacaoBancariaItem = mx.idMovimentacaoBancariaItem"
,array()
);
$select->joinLeft(
array("ti" => "tbTipoInconsistencia")
,"ti.idTipoInconsistencia = mx.idTipoInconsistencia"
,array()
);
}
$select->joinLeft(
array("c" => "ContaBancaria")
,"mi.nrAgencia = c.Agencia AND (mi.nrDigitoConta = c.ContaBloqueada OR mi.nrDigitoConta = c.ContaLivre)"
,array()
);
$select->joinLeft(
array("p" => "Projetos")
,"c.AnoProjeto = p.AnoProjeto AND c.Sequencial = p.Sequencial"
,array()
);
$select->joinLeft(
array("bc" => "bancos")
,"m.nrBanco = bc.Codigo"
,array()
,"AGENTES.dbo"
);
$select->joinLeft(
array("a" => "Agentes")
,"mi.nrCNPJCPF = a.CNPJCPF"
,array()
,"AGENTES.dbo"
);
$select->joinLeft(
array("n" => "Nomes")
,"a.idAgente = n.idAgente"
,array()
,"AGENTES.dbo"
);
// $select->where("mi.vlSaldoInicial > 0.00");
//$select->where("mi.vlSaldoFinal > 0.00");
// busca pelo pronac
if (!empty($pronac))
{
$select->where("(c.AnoProjeto+c.Sequencial) = ?", $pronac);
}
// filtra por contas rejeitadas
if (!empty($conta_rejeitada) && $conta_rejeitada)
{
$select->where("mx.idMovimentacaoBancariaItem IS NOT NULL");
$select->where("mx.idTipoInconsistencia IS NOT NULL");
}
else
{
$select->where("mx.idMovimentacaoBancariaItem IS NULL");
$select->where("mx.idTipoInconsistencia IS NULL");
}
// busca pelo período
if (!empty($periodo))
{
if ($periodo[0] == "A") // Hoje
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) = CONVERT(DATE, GETDATE())
OR CONVERT(DATE, m.dtFimMovimento) = CONVERT(DATE, GETDATE())
OR CONVERT(DATE, mi.dtMovimento) = CONVERT(DATE, GETDATE())");
}
if ($periodo[0] == "B") // Ontem
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "C") // Últimos 7 dias
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "D") // Semana passada (seg-dom)
{
$select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
END)");
}
if ($periodo[0] == "E") // Última semana (seg-sex)
{
$select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
END)");
}
if ($periodo[0] == "F") // Este mês
{
$select->where("DATEPART(MONTH, m.dtInicioMovimento) + DATEPART(YEAR, m.dtInicioMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())
OR DATEPART(MONTH, m.dtFimMovimento) + DATEPART(YEAR, m.dtFimMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())
OR DATEPART(MONTH, mi.dtMovimento) + DATEPART(YEAR, mi.dtMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())");
}
if ($periodo[0] == "G") // Ano passado
{
$select->where("DATEPART(YEAR, m.dtInicioMovimento) = (DATEPART(YEAR, GETDATE()) - 1)
OR DATEPART(YEAR, m.dtFimMovimento) = (DATEPART(YEAR, GETDATE()) - 1)
OR DATEPART(YEAR, mi.dtMovimento) = (DATEPART(YEAR, GETDATE()) - 1)");
}
if ($periodo[0] == "H") // Últimos 12 meses
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "I") // Últimos 6 meses
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "J") // Últimos 3 meses
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "K") // filtra conforme uma data inicial e uma data final
{
if (!empty($periodo[1]) && !empty($periodo[2]))
{
$select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00");
$select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59");
}
else
{
if (!empty($periodo[1]))
{
$select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00");
}
if (!empty($periodo[2]))
{
$select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59");
}
}
}
} // fecha if periodo
// filtra pelo tipo de operação
if (!empty($operacao))
{
$select->where("mi.tpSaldoInicial = ? OR mi.tpSaldoInicial IS NULL", $operacao);
$select->where("mi.tpSaldoFinal = ? OR mi.tpSaldoFinal IS NULL", $operacao);
$select->where("mi.cdMovimento = ? OR mi.cdMovimento IS NULL", $operacao);
}
/*if(is_null($count)){
/*$select->order("mi.tpRegistro");
$select->order("(p.AnoProjeto+p.Sequencial)");
$select->order("m.dtInicioMovimento");
$select->order("m.dtFimMovimento");
$select->order("mi.dtMovimento");
$select->order(array(5,26,2,3,17));
}*/
//paginacao
if ($tamanho > -1) {
$tmpInicio = 0;
if ($inicio > -1) {
$tmpInicio = $inicio;
}
$select->limit($tamanho, $tmpInicio);
}
//x($select->assemble());
return $this->fetchAll($select);
} // fecha método buscarDados()
/**
* Método para cadastrar
* @access public
* @param array $dados
* @return integer (retorna o último id cadastrado)
*/
public function cadastrarDados($dados)
{
return $this->insert($dados);
} // fecha método cadastrarDados()
/**
* Método para alterar
* @access public
* @param array $dados
* @param integer $where
* @return integer (quantidade de registros alterados)
*/
public function alterarDados($dados, $where)
{
$where = "idMovimentacaoBancaria = " . $where;
return $this->update($dados, $where);
} // fecha método alterarDados()
/**
* Método para excluir
* @access public
* @param integer $where
* @return integer (quantidade de registros excluídos)
*/
public function excluirDados($where)
{
$where = "idMovimentacaoBancaria = " . $where;
return $this->delete($where);
} // fecha método excluirDados()
} // fecha class | Java |
/* This file is part of VoltDB.
* Copyright (C) 2008-2014 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef STATSSOURCE_H_
#define STATSSOURCE_H_
#include "common/tabletuple.h"
#include "common/ids.h"
#include "boost/scoped_ptr.hpp"
#include <string>
#include <vector>
#include <map>
namespace voltdb {
class Table;
class TableFactory;
class TupleSchema;
class TableTuple;
/**
* Abstract superclass of all sources of statistical information inside the EE. Statistics are currently represented as a single
* row table that is updated every time it is retrieved.
*/
class StatsSource {
public:
/**
* Generates the list of column names that are present for every
* stats table. Derived classes should implement their own static
* methods to generate their column names and call this method
* within it to populate the column name vector before adding
* their stat-specific column names.
*/
static std::vector<std::string> generateBaseStatsColumnNames();
/**
* Populates the other schema information which is present for
* every stats table. Usage by derived classes takes the same
* pattern as generateBaseStatsColumnNames.
*/
static void populateBaseSchema(std::vector<voltdb::ValueType>& types,
std::vector<int32_t>& columnLengths,
std::vector<bool>& allowNull,
std::vector<bool>& inBytes);
/*
* Do nothing constructor that initializes statTable_ and schema_ to NULL.
*/
StatsSource();
/**
* Configure a StatsSource superclass for a set of statistics. Since this class is only used in the EE it can be assumed that
* it is part of an Execution Site and that there is a site Id.
* @parameter name Name of this set of statistics
* @parameter hostId id of the host this partition is on
* @parameter hostname name of the host this partition is on
* @parameter siteId this stat source is associated with
* @parameter partitionId this stat source is associated with
* @parameter databaseId Database this source is associated with
*/
void configure(
std::string name,
voltdb::CatalogId databaseId);
/*
* Destructor that frees tupleSchema_, and statsTable_
*/
virtual ~StatsSource();
/**
* Retrieve table containing the latest statistics available. An updated stat is requested from the derived class by calling
* StatsSource::updateStatsTuple
* @param interval Return counters since the beginning or since this method was last invoked
* @param now Timestamp to return with each row
* @return Pointer to a table containing the statistics.
*/
voltdb::Table* getStatsTable(bool interval, int64_t now);
/*
* Retrieve tuple containing the latest statistics available. An updated stat is requested from the derived class by calling
* StatsSource::updateStatsTuple
* @param interval Whether to return counters since the beginning or since the last time this was called
* @param Timestamp to embed in each row
* @return Pointer to a table tuple containing the latest version of the statistics.
*/
voltdb::TableTuple* getStatsTuple(bool interval, int64_t now);
/**
* Retrieve the name of this set of statistics
* @return Name of statistics
*/
std::string getName();
/**
* String representation of the statistics. Default implementation is to print the stats table.
* @return String representation
*/
virtual std::string toString();
protected:
/**
* Update the stats tuple with the latest statistics available to this StatsSource. Implemented by derived classes.
* @parameter tuple TableTuple pointing to a row in the stats table.
*/
virtual void updateStatsTuple(voltdb::TableTuple *tuple) = 0;
/**
* Generates the list of column names that will be in the statTable_. Derived classes must override this method and call
* the parent class's version to obtain the list of columns contributed by ancestors and then append the columns they will be
* contributing to the end of the list.
*/
virtual std::vector<std::string> generateStatsColumnNames();
/**
* Same pattern as generateStatsColumnNames except the return value is used as an offset into the tuple schema instead of appending to
* end of a list.
*/
virtual void populateSchema(std::vector<voltdb::ValueType> &types, std::vector<int32_t> &columnLengths,
std::vector<bool> &allowNull, std::vector<bool> &inBytes);
/**
* Map describing the mapping from column names to column indices in the stats tuple. Necessary because classes in the
* inheritance hierarchy can vary the number of columns they contribute. This removes the dependency between them.
*/
std::map<std::string, int> m_columnName2Index;
bool interval() { return m_interval; }
private:
/**
* Table containing the stat information. Shared pointer used as a substitute for scoped_ptr due to forward
* declaration.
*/
boost::scoped_ptr<voltdb::Table> m_statsTable;
/**
* Tuple used to modify the stat table.
*/
voltdb::TableTuple m_statsTuple;
/**
* Name of this set of statistics.
*/
std::string m_name;
/**
* CatalogId of the partition this StatsSource is associated with.
*/
voltdb::CatalogId m_partitionId;
int64_t m_siteId;
voltdb::CatalogId m_hostId;
voltdb::NValue m_hostname;
bool m_interval;
};
}
#endif /* STATSCONTAINER_H_ */
| Java |
import sys
import time
import sys
num = 1000
print_granularity = 1000
count = 0
first = True
start = 0
gran_start = 0
min = 0
max = 0
avg = 0
sum = 0
total = 0
def set_print_granularity(p):
global print_granularity
print_granularity = p
print("%s: print granularity = %s" % (sys.argv[0], print_granularity))
def loop_count():
global min, max, avg, total, gran_start, sum, start, first, count
now = round(time.time() * 1000)
if not first:
elapsed = now - start
if elapsed < min: min = elapsed
if elapsed > max: max = elapsed
sum = sum + elapsed
start = now
count = count + 1
total = total + 1
if count % print_granularity == 0 and not first:
gran_elapsed = now - gran_start
gran_start = now
avg = sum / print_granularity
print("%s: last %s run stats in msec \t\t elapsed = %s \t min = %s \t max = %s \t avg = %s \t\t total loops = %s" % (sys.argv[0], print_granularity, sum, min, max, avg, total))
# sys.stdout.write("-")
# sys.stdout.flush()
if first or count % print_granularity == 0:
gran_start = now
min = 10e10
max = -10e10
avg = 0
sum = 0
first = False
| Java |
//#############################################################################
//# #
//# 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.vitalsignstprbp;
import ims.framework.delegates.*;
abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode
{
abstract protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onChkLegendValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnViewClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onRadioButtongrpShowByValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnPrintClick() throws ims.framework.exceptions.PresentationLogicException;
public final void setContext(ims.framework.UIEngine engine, GenForm form)
{
this.engine = engine;
this.form = form;
this.form.setFormOpenEvent(new FormOpen()
{
private static final long serialVersionUID = 1L;
public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
onFormOpen();
}
});
this.form.chkLegend().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onChkLegendValueChanged();
}
});
this.form.btnView().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnViewClick();
}
});
this.form.grpShowBy().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onRadioButtongrpShowByValueChanged();
}
});
this.form.btnPrint().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnPrintClick();
}
});
}
public void free()
{
this.engine = null;
this.form = null;
}
protected ims.framework.UIEngine engine;
protected GenForm form;
}
| Java |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo.beans;
public class PatientDiagnosisStatusForReferralCodingVoBean extends ims.vo.ValueObjectBean
{
public PatientDiagnosisStatusForReferralCodingVoBean()
{
}
public PatientDiagnosisStatusForReferralCodingVoBean(ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo = null;
if(map != null)
vo = (ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo();
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.vo.LookupInstanceBean getStatus()
{
return this.status;
}
public void setStatus(ims.vo.LookupInstanceBean value)
{
this.status = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean status;
}
| Java |
<?php
// Database Restore
$locale['400'] = "Восстановление БД";
$locale['401'] = "Ошибка";
$locale['402'] = "Неверный формат файла резервной копии";
$locale['403'] = "Закрыть";
// Backup File Information
$locale['410'] = "Данные о файле резервной копии";
$locale['411'] = "Данные о файле для восстановления";
$locale['412'] = "Имя файла копии:";
$locale['413'] = "Дата создания:";
$locale['414'] = "Имя базы данных:";
$locale['415'] = "Префикс таблиц ядра:";
$locale['416'] = "Таблицы:";
$locale['417'] = "Посмотреть";
$locale['418'] = "отмена";
$locale['419'] = "таблиц";
// Database Restore
$locale['430'] = "Параметры восстановления";
$locale['431'] = "Имя файла:";
$locale['432'] = "Создан:";
$locale['433'] = "Создать таблицы:";
$locale['434'] = "Заполнить таблицы:";
$locale['435'] = "Выбрать:";
$locale['436'] = "все";
$locale['437'] = "ничего";
$locale['438'] = "Восстановить из резервной копии";
$locale['439'] = "Отмена";
$locale['440'] = "Поддерживаемые типы файлов:";
// Database Backup
$locale['450'] = "Резервирование БД";
$locale['451'] = "Информация о базе данных";
$locale['452'] = "Общий размер таблиц:";
$locale['453'] = "Размер таблиц ядра:";
$locale['454'] = "Параметры резервирования:";
$locale['455'] = "Тип резервной копии:";
$locale['456'] = "(сжатая)";
$locale['457'] = "Таблицы БД";
$locale['458'] = "ядро";
$locale['459'] = "Создать резервную копию";
$locale['460'] = "Админпароль:";
$locale['460b'] = "Пожалуйста, введите Ваш админпароль";
$locale['461'] = "Требуемая информация";
// Backup List
$locale['480'] = "Восстановить из резервной копии";
$locale['481'] = "Имя файла:";
$locale['481b'] = "Пожалуйста, укажите имя файла";
?> | Java |
#region C#raft License
// This file is part of C#raft. Copyright C#raft Team
//
// C#raft 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/>.
#endregion
using Chraft.Entity.Items;
using Chraft.Utilities.Blocks;
using Chraft.World.Blocks.Base;
namespace Chraft.World.Blocks
{
class BlockStone : BlockBase
{
public BlockStone()
{
Name = "Stone";
Type = BlockData.Blocks.Stone;
IsSolid = true;
var item = ItemHelper.GetInstance(BlockData.Blocks.Cobblestone);
item.Count = 1;
LootTable.Add(item);
}
}
}
| Java |
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (c) 2015 Odoo S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def _prepare_shipping_invoice_line(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.property_account_income.id
if not account_id:
account_id = carrier.product_id.categ_id.property_account_income_categ.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'invoice_line_tax_ids': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.carrier_tracking_ref = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.carrier_tracking_ref
self.message_post(body=msg)
self.carrier_tracking_ref = False
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search — Paver 1.2.1 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1.2.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/searchtools.js"></script>
<link rel="top" title="Paver 1.2.1 documentation" href="index.html" />
<script type="text/javascript">
jQuery(function() { Search.loadIndex("searchindex.js"); });
</script>
<script type="text/javascript" id="searchindexloader"></script>
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">Paver 1.2.1 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<h1 id="search-documentation">Search</h1>
<div id="fallback" class="admonition warning">
<script type="text/javascript">$('#fallback').hide();</script>
<p>
Please activate JavaScript to enable the search
functionality.
</p>
</div>
<p>
From here you can search these documents. Enter your search
words into the box below and click "search". Note that the search
function will automatically search for all of the words. Pages
containing fewer words won't appear in the result list.
</p>
<form action="" method="get">
<input type="text" name="q" value="" />
<input type="submit" value="search" />
<span id="search-progress" style="padding-left: 10px"></span>
</form>
<div id="search-results">
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">Paver 1.2.1 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2008, SitePen, Inc..
Last updated on Jun 02, 2013.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2b1.
</div>
</body>
</html> | Java |
<?php $this->applyTemplateHook('settings-nav','before'); ?>
<nav id="panel-settings-nav" class="sidebar-panel">
<?php $this->applyTemplateHook('settings-nav','begin'); ?>
<?php $this->applyTemplateHook('settings-nav','end'); ?>
</nav>
<?php $this->applyTemplateHook('settings-nav','after'); ?> | Java |
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.ctp.server.notification;
/**
*
* @version $Id: NotificationProviderException.java,v 1.2 2007-11-28 11:26:16 nichele Exp $
*/
public class NotificationProviderException extends Exception {
/**
* Creates a new instance of <code>NotificationProviderException</code> without
* detail message.
*/
public NotificationProviderException() {
super();
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified detail message.
*
* @param message the detail message.
*/
public NotificationProviderException(String message) {
super(message);
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified detail message and the given cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public NotificationProviderException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified cause.
*
* @param cause the cause.
*/
public NotificationProviderException(Throwable cause) {
super(cause);
}
}
| Java |
//#############################################################################
//# #
//# 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.spinalinjuries.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseSharedNewConcernImpl extends DomainImpl implements ims.spinalinjuries.domain.SharedNewConcern, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatesaveConcern(ims.core.vo.PatientCurrentConcernVo concern, ims.core.vo.PatientShort patient)
{
}
@SuppressWarnings("unused")
public void validatelistHcps(ims.core.vo.HcpFilter filter)
{
}
@SuppressWarnings("unused")
public void validatelistProbsOnAdmission(ims.core.vo.CareContextShortVo coClinicalContactShort)
{
}
@SuppressWarnings("unused")
public void validategetConcern(ims.core.clinical.vo.PatientConcernRefVo concernId)
{
}
}
| Java |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:31
*
*/
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class TrackingLiteVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.TrackingLiteVo copy(ims.emergency.vo.TrackingLiteVo valueObjectDest, ims.emergency.vo.TrackingLiteVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Tracking(valueObjectSrc.getID_Tracking());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// CurrentArea
valueObjectDest.setCurrentArea(valueObjectSrc.getCurrentArea());
// isPrimaryCare
valueObjectDest.setIsPrimaryCare(valueObjectSrc.getIsPrimaryCare());
// isDischarged
valueObjectDest.setIsDischarged(valueObjectSrc.getIsDischarged());
// LastMovementDateTime
valueObjectDest.setLastMovementDateTime(valueObjectSrc.getLastMovementDateTime());
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 #createTrackingLiteVoCollectionFromTracking(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.Set domainObjectSet)
{
return createTrackingLiteVoCollectionFromTracking(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.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) iterator.next();
ims.emergency.vo.TrackingLiteVo 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.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.List domainObjectList)
{
return createTrackingLiteVoCollectionFromTracking(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.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) domainObjectList.get(i);
ims.emergency.vo.TrackingLiteVo 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.Tracking 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 extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection)
{
return extractTrackingSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection 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.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(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.Tracking 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 extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection)
{
return extractTrackingList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection 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.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(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.Tracking object.
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo create(ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.Tracking object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.TrackingLiteVo create(DomainObjectMap map, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.TrackingLiteVo valueObject = (ims.emergency.vo.TrackingLiteVo) map.getValueObject(domainObject, ims.emergency.vo.TrackingLiteVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.TrackingLiteVo(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.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking 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.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(DomainObjectMap map, ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Tracking(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;
// CurrentArea
if (domainObject.getCurrentArea() != null)
{
if(domainObject.getCurrentArea() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getCurrentArea();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(id, -1));
}
else
{
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(domainObject.getCurrentArea().getId(), domainObject.getCurrentArea().getVersion()));
}
}
// isPrimaryCare
valueObject.setIsPrimaryCare( domainObject.isIsPrimaryCare() );
// isDischarged
valueObject.setIsDischarged( domainObject.isIsDischarged() );
// LastMovementDateTime
java.util.Date LastMovementDateTime = domainObject.getLastMovementDateTime();
if ( null != LastMovementDateTime )
{
valueObject.setLastMovementDateTime(new ims.framework.utils.DateTime(LastMovementDateTime) );
}
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.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject)
{
return extractTracking(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Tracking();
ims.emergency.domain.objects.Tracking domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(valueObject);
}
// ims.emergency.vo.TrackingLiteVo ID_Tracking field is unknown
domainObject = new ims.emergency.domain.objects.Tracking();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Tracking());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.Tracking) domainFactory.getDomainObject(ims.emergency.domain.objects.Tracking.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_Tracking());
ims.emergency.configuration.domain.objects.TrackingArea value1 = null;
if ( null != valueObject.getCurrentArea() )
{
if (valueObject.getCurrentArea().getBoId() == null)
{
if (domMap.get(valueObject.getCurrentArea()) != null)
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domMap.get(valueObject.getCurrentArea());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value1 = domainObject.getCurrentArea();
}
else
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domainFactory.getDomainObject(ims.emergency.configuration.domain.objects.TrackingArea.class, valueObject.getCurrentArea().getBoId());
}
}
domainObject.setCurrentArea(value1);
domainObject.setIsPrimaryCare(valueObject.getIsPrimaryCare());
domainObject.setIsDischarged(valueObject.getIsDischarged());
ims.framework.utils.DateTime dateTime4 = valueObject.getLastMovementDateTime();
java.util.Date value4 = null;
if ( dateTime4 != null )
{
value4 = dateTime4.getJavaDate();
}
domainObject.setLastMovementDateTime(value4);
return domainObject;
}
}
| Java |
<!--
This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
-->
<div id="webapp-editor-templates" class="hide">
<!-- Template for the entire editor, both tabs and the actual content -->
<div class="webapp-editor">
<div class="row">
<div class="col-xs-12">
<!-- The editor content gets displayed here -->
<div class="webapp-editor-content">
</div>
</div>
</div>
</div>
<!-- Template for the tab at the top of the editor with filename and an x -->
<ul> <!-- ul so is valid html -->
<li class="super-menu webapp-editor-filename-pill">
<div class="webapp-editor-close-button-x pull-right lighten"><i class="fa fa-times"></i></div>
<a>
<span class="webapp-editor-tab-filename"></span>
</a>
</li>
</ul>
<!-- Template for the codemirror text editor -->
<div class="webapp-editor-codemirror smc-vfill">
<textarea class="webapp-editor-textarea-0 hide"></textarea>
<textarea class="webapp-editor-textarea-1 hide"></textarea>
<div class="webapp-editor-codemirror-content smc-vfill">
<div class="webapp-editor-codemirror-button-row">
<div class="webapp-editor-codemirror-button-container">
<div class="hidden-xs webapp-editor-chat-title webapp-editor-write-only pull-right">
<div class="smc-users-viewing-document">
<!--to be filled with react component for users viewing the document-->
</div>
</div>
<div class="smc-editor-file-info-dropdown" style="float:left;"></div>
<span class="visible-xs">
<span class="btn-group">
<!-- <a href="#close" class="btn btn-default btn-lg"><i class="fa fa-toggle-up"></i> <span>Files...</span></a>-->
<a href="#save" class="btn btn-success btn-lg"><i class="fa fa-save"></i> Save</a>
<a href="#goto-line" class="btn btn-default btn-lg"><i class="fa fa-bolt"> </i></a>
</span>
<span class="btn-group webapp-editor-codemirror-worksheet-buttons hide">
<a href="#execute" class="btn btn-success btn-lg"> <i class="fa fa-play"></i> Run</a>
<a href="#interrupt" class="btn btn-warning btn-lg"> <i class="fa fa-stop"></i></a>
<a href="#kill" class="btn btn-warning btn-lg"><i class="fa fa-refresh"></i></a>
<a href="#tab" class="btn btn-info btn-lg"> <i class="fa fa-step-forward"></i></a>
</span>
<span class="btn-group">
<a href="#decrease-font" class="btn btn-default btn-lg"><i class="fa fa-font" style="font-size:8pt"> </i> </a>
<a href="#increase-font" class="btn btn-default btn-lg"><i class="fa fa-font" style="font-size:13pt"> </i> </a>
</span>
<a class="btn btn-primary btn-lg hide" href="#copy-to-another-project"><i class="fa fa-paper-plane"> </i> <span>Copy To Your Project...</span></a>
</span>
<span class="btn-group webapp-editor-write-only">
<a href="#save" class="hidden-xs btn btn-success webapp-editor-save-group" data-toggle="tooltip" data-placement="bottom" title="Save file to disk.">
<i class="fa fa-save primary-icon"></i>
<i class="fa fa-cocalc-ring hide"></i>
Save
<span class="smc-uncommitted hide" data-toggle="tooltip" data-placement="bottom" title="DANGER: File NOT sent to server and not saved to disk. You will lose work if you close this file."> NOT saved!</span>
</a>
<a href="#history" class="hidden-xs btn btn-info webapp-editor-history-button hide" data-toggle="tooltip" data-placement="bottom" title="View the history of this file.">
<i class="fa fa-history"></i>
<span class="hidden-sm">TimeTravel</span>
</a>
</span>
<span class="hidden-xs">
<span class="webapp-editor-codemirror-worksheet-buttons hide">
<span class="btn-group webapp-editor-write-only">
<a href="#execute" class="btn btn-default " data-toggle="tooltip" data-placement="bottom" title="Execute current or selected cells (unless input hidden)."><i class="fa fa-play"></i> Run</a>
<a href="#tab" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tab completion."> <i class="fa fa-step-forward"></i> <span class="hidden-sm hidden-md">Tab</span></a>
<a href="#interrupt" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Stop the running calculation."><i class="fa fa-stop"></i> <span class="hidden-sm hidden-md">Stop</span></a>
<a href="#kill" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Restart the running Sage process (all variables reset)."><i class="fa fa-refresh"></i> <span class="hidden-sm hidden-md">Restart</span></a>
</span>
<span class="btn-group webapp-editor-write-only hidden-sm">
<a href="#toggle-input" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Toggle display of input of selected cells."><i class="fa fa-toggle-on"></i> <span class="hidden-sm hidden-md">in</span></a>
<a href="#toggle-output" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Toggle display of output of selected cells."><i class="fa fa-toggle-on"></i> <span class="hidden-sm hidden-md">out</span></a>
<a href="#delete-output" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Delete output of selected cells (unless input hidden)."><i class="fa fa-times-circle"></i></a>
</span>
</span>
</span>
<span class="hidden-xs btn-group editor-btn-group">
<a href="#vim-mode-toggle" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Toggle VIM mode" style="width:4em">esc</a>
<a href="#autoindent" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Autoindent selected text"><i class="fa fa-indent"></i></a>
<a href="#undo" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Undo"><i class="fa fa-undo"></i></a>
<a href="#redo" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Redo"><i class="fa fa-repeat"></i></a>
<a href="#search" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Search"><i class="fa fa-search"></i></a>
<!-- <a href="#prev" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Previous"><i class="fa fa-chevron-up"></i></a>
<a href="#next" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Next"><i class="fa fa-chevron-down"></i></a>-->
<a href="#replace" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Replace"><i class="fa fa-exchange"></i></a>
<a href="#split-view" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Split view of document">
<i class="fa fa-horizontal-split webapp-editor-layout-0 hide"></i>
<i class="fa fa-vertical-split webapp-editor-layout-1 hide"></i>
<i class="fa fa-window-maximize webapp-editor-layout-2 hide" style="font-size: 12pt;"></i>
</a>
<a href="#decrease-font" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Decrease text size"><i class="fa fa-font" style="font-size:7pt"> </i> </a>
<a href="#increase-font" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Increase text size"><i class="fa fa-font" style="font-size:11pt"> </i> </a>
<a href="#goto-line" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Go to line"><i class="fa fa-bolt"> </i> </a>
<a href="#copy" class="btn btn-default btn-history webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Copy"><i class="fa fa-copy"> </i> </a>
<a href="#paste" class="btn btn-default btn-history webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Paste"><i class="fa fa-paste"> </i> </a>
<a href="#sagews2pdf" class="hidden-sm btn btn-default webapp-editor-write-only hide" data-toggle="tooltip" data-placement="bottom" title="Convert to PDF"><i class="fa fa-file-pdf-o"> </i> </a>
<a href="#print" class=" hidden-sm btn btn-default webapp-editor-write-only hide" data-toggle="tooltip" data-placement="bottom" title="Print"><i class="fa fa-print"> </i> <i class="fa fa-cocalc-ring hide"></i></a> </a>
<a href="#sagews2ipynb" class="hidden-sm btn btn-default webapp-editor-write-only hide" data-toggle="tooltip" data-placement="bottom" title="Convert to ipynb"><i class="fa fa-ipynb"> </i> <span class="hidden-sm hidden-md">Jupyter</span></a>
</span>
<span class="btn-group webapp-editor-read-only hide">
<a href="#readonly" class="hidden-xs btn btn-success webapp-editor-save-group disabled" data-toggle="tooltip" data-placement="bottom" title="File is read only.">
<i class="fa fa-save"></i>
<span class="hidden-sm">Readonly</span>
</a>
<a href="#history" class="hidden-xs btn btn-info webapp-editor-history-button hide" data-toggle="tooltip" data-placement="bottom" title="View the history of this file.">
<i class="fa fa-history"></i>
<span class="hidden-sm hidden-md">TimeTravel</span>
</a>
</span>
<span class="hidden-xs">
<a class="btn btn-primary hide" href="#copy-to-another-project"><i class="fa fa-paper-plane"> </i> <span>Copy To Your Project...</span></a>
<!--<a class="btn btn-success" href="#download-file"><i class="fa fa-cloud-download"> </i> <span class="hidden-sm">Download</span></a>-->
</span>
<span class="webapp-editor-codemirror-loading hide">
<i class="fa fa-cocalc-ring"></i> load…
</span>
<span class="webapp-editor-codemirror-sync">
<span class="webapp-editor-codemirror-not-synced hide"><i class="fa fa-cocalc-ring"></i> sync…</span>
<span class="webapp-editor-codemirror-synced hide"><i class="fa fa-check"></i></span>
</span>
<span class="webapp-editor-codemirror-message"></span>
<span class="webapp-editor-codemirror-filename pull-right"></span>
</div>
<div class="webapp-editor-buttonbars webapp-editor-write-only">
<div class="webapp-editor-latex-buttonbar hide"></div>
<div class="webapp-editor-codemirror-textedit-buttons hide visible-sm-block visible-md-block visible-lg-block">
<code class="webapp-editor-codeedit-buttonbar-mode pull-right hide"></code>
<span class="react-target"></span>
<span class="webapp-editor-codeedit-buttonbar-assistant pull-right hide">
<a href="#assistant" class="btn btn-default"
data-toggle="tooltip" data-placement="bottom" title="Insert examples">
<i class="fa fa-magic"></i> <span class="hidden-sm">Snippets</span>
</a>
</span>
</div>
<div class="webapp-editor-codemirror-worksheet-editable-buttons hide">
<span class="btn-group">
<a href="#bold" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Bold"><i class="fa fa-bold"></i></a>
<a href="#italic" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Italic"><i class="fa fa-italic"></i></a>
<a href="#underline" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Underline"><i class="fa fa-underline"></i></a>
<a href="#strikethrough" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Strike through"><i class="fa fa-strikethrough"></i></a>
<a href="#subscript" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Subscript (use LaTeX for serious equations)"><i class="fa fa-subscript"></i></a>
<a href="#superscript" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Superscript"><i class="fa fa-superscript"></i></a>
</span>
<span class="btn-group">
<a href="#equation" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Inline equation..."> $ </a>
<a href="#display_equation" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Displayed equation..."> $$ </a>
<a href="#insertunorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert unordered list"><i class="fa fa-list"></i></a>
<a href="#insertorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert ordered list"><i class="fa fa-list-ol"></i></a>
<a href="#link" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert link..."><i class="fa fa-link"></i></a>
<a href="#image" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert image..."><i class="fa fa-image"></i></a>
<!-- <a href="#insertHorizontalRule" class="btn btn-default"><hr></a> -->
</span>
<span class="btn-group">
<a href="#justifyleft" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Left justify"><i class="fa fa-align-left"></i></a>
<a href="#justifycenter" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Justify center"><i class="fa fa-align-center"></i></a>
<a href="#justifyright" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Right justify"><i class="fa fa-align-right"></i></a>
<a href="#justifyfull" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Justify full"><i class="fa fa-align-justify"></i></a>
<a href="#outdent" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Outdent"><i class="fa fa-outdent"></i></a>
<a href="#indent" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Indent"><i class="fa fa-indent"></i></a>
</span>
<span class="btn-group">
<a href="#undo" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Undo"><i class="fa fa-undo"></i></a>
<a href="#redo" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Redo"><i class="fa fa-repeat"></i></a>
</span>
<span class="btn-group">
<span class="btn-group sagews-output-editor-font smc-tooltip" data-toggle="tooltip" data-placement="top" title="Fonts">
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Font">
<i class="fa fa-font"></i> <b class="caret"></b>
</span>
<ul class="dropdown-menu">
</ul>
</span>
<span class="btn-group sagews-output-editor-font-size smc-tooltip" data-toggle="tooltip" data-placement="top" title="Font size">
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Text height">
<i class="fa fa-text-height"></i> <b class="caret"></b>
</span>
<ul class="dropdown-menu">
</ul>
</span>
<span class="btn-group sagews-output-editor-block-type smc-tooltip" data-toggle="tooltip" data-placement="top" title="Format type">
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Header">
<i class="fa fa-header"></i> <b class="caret"></b>
</span>
<ul class="dropdown-menu">
</ul>
</span>
</span>
<span class="btn-group"> <!-- not implemented yet -->
<span class="sagews-output-editor-foreground-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="top" title="Text color">
<input type="text" style="cursor:pointer" class="form-control">
<span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span>
</span>
</span>
<span class="btn-group"> <!-- not implemented yet -->
<span class="sagews-output-editor-background-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="top" title="Text background highlight color">
<input type="text" style="cursor:pointer" class="form-control">
<span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span>
</span>
</span>
</div>
</div>
</div>
<div class="webapp-editor-codemirror-input-container-layout-0 hide"
style="flex: 1; display: flex; flex-direction: column;">
<!-- See https://github.com/codemirror/CodeMirror/issues/3679 for why we do this nesting
(to work around a chrome bug, and/or avoid major slowdown doing layout?) -->
<div class="webapp-editor-codemirror-input-box" style="display: flex; flex-direction: column; position:relative;">
<div style="position:absolute; height:100%; width:100%">
</div>
</div>
<div class="webapp-editor-codemirror-input-box-1 hide">
<div>
</div>
</div>
</div>
<div class="webapp-editor-codemirror-input-container-layout-1 hide"
style="flex: 1; display: flex; flex-direction: column;">
<!-- See https://github.com/codemirror/CodeMirror/issues/3679 for why we do this nesting
(to work around a chrome bug, and/or avoid major slowdown doing layout?) -->
<div class="webapp-editor-codemirror-input-box" style="display: flex; flex-direction: column; position:relative;">
<div style="position:absolute; height:100%; width:100%">
</div>
</div>
<div class="webapp-editor-resize-bar-layout-1">
</div>
<!-- flex: 1 so expands to what is left after editor above is placed. -->
<div class="webapp-editor-codemirror-input-box-1" style="flex: 1; display: flex; flex-direction: column; position:relative;">
<div style="position:absolute; height:100%; width:100%">
</div>
</div>
</div>
<div class="webapp-editor-codemirror-input-container-layout-2 hide"
style="flex: 1; display: flex; flex-direction: row;">
<!-- See https://github.com/codemirror/CodeMirror/issues/3679 for why we do this nesting
(to work around a chrome bug, and/or avoid major slowdown doing layout?) -->
<div class="webapp-editor-codemirror-input-box" style="display: flex; flex-direction: column; position:relative;">
<div style="position:absolute; height:100%; width:100%">
</div>
</div>
<div class="webapp-editor-resize-bar-layout-2">
</div>
<!-- flex: 1 so expands to what is left after editor above is placed. -->
<div class="webapp-editor-codemirror-input-box-1" style="flex: 1; display: flex; flex-direction: column; position:relative;">
<div style="position:absolute; height:100%; width:100%">
</div>
</div>
</div>
</div>
<div class="webapp-editor-codemirror-startup-message alert alert-warning hide" role='alert'>
</div>
</div>
<!-- Template for the codemirror text editor other user cursors -->
<div class="webapp-editor-codemirror-cursor"><span class="webapp-editor-codemirror-cursor-label"></span><div class="webapp-editor-codemirror-cursor-inside"> </div></div>
<div class="smc-editor-codemirror-cursor"><span class="smc-editor-codemirror-cursor-label"></span><div class="smc-editor-codemirror-cursor-inside"> </div></div>
<!-- Static HTML viewer -->
<div class="webapp-editor-static-html">
<div class="webapp-editor-static-html-content">
<iframe style="width:100%;border:0px;">
</iframe>
</div>
</div>
<!-- Templates for the png-based PDF previewer; this is designed for the pdf changes in little ways locally. -->
<div class="webapp-editor-pdf-preview smc-vfill">
<div class="webapp-editor-pdf-preview-spinner hide"></div>
<div class="webapp-editor-pdf-preview-highlight hide"></div>
<div class="webapp-editor-pdf-preview-buttons">
<span class="btn-group">
<a href="#zoom-preview-out" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom out some"><i class="fa fa-search-minus"></i></a>
<a href="#zoom-preview-in" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom in some"><i class="fa fa-search-plus"></i></a>
<a href="#zoom-preview-fullpage" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom so page width matches viewport"><i class="fa fa-file-o"></i></a>
<a href="#zoom-preview-width" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom in close"><i class="fa fa-arrows-alt"></i></a>
<a href="#preview-resolution" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Change the preview resolution"><i class="fa fa-th"></i></a>
<a href="#pdf-download" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Download the PDF file"><i class="fa fa-download"></i></a>
</span>
<span class="btn-group pull-right">
<a href="#toggle-preview" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="If enabled, the LaTeX file is compiled and a preview is rendered.">
<i class="fa fa-check-square-o"></i> Build preview
</a>
</span>
</div>
<div style="flex:1;overflow-y:auto;overflow-x:auto" class="webapp-editor-pdf-preview-output">
<div class="webapp-editor-pdf-preview-page">
</div>
<div class="webapp-editor-pdf-preview-message hide">
</div>
</div>
</div>
<!-- Templates for the embedded PDF previewer: just uses the built-in renderer; can't cope with file updates, inverse search, etc. -->
<div class="webapp-editor-pdf-preview-embed smc-vfill">
<div class="webapp-editor-codemirror-button-row">
<span class="webapp-editor-pdf-preview-embed-spinner hide"></span>
<span class="btn-group">
<a class="btn btn-default btn-lg visible-xs" href="#close" ><i class="fa fa-toggle-up"></i> <span class="hidden-xs">Files...</span></a>
<a class="btn btn-default btn-lg visible-xs" href="#refresh"><i class="fa fa-refresh"></i> <span class="hidden-xs"> Refresh</span></a>
<a class="btn btn-default hidden-xs" href="#refresh"><i class="fa fa-refresh"></i> <span class="hidden-xs"> Refresh</span></a>
</span>
<span class="btn-group pull-right">
<a class="btn btn-default webapp-editor-pdf-title hidden-xs">
<i class="fa fa-external-link"></i>
<span></span>
</a>
</span>
</div>
<div class="webapp-editor-pdf-preview-embed-page smc-vfill">
<iframe frameborder="0" scrolling="no" style="width:100%;height:100%">
<br>
<br>
Your browser doesn't support embedded PDF's, but you can <a target='_blank'>download <span></span></a>...
</iframe>
</div>
</div>
<div class="webapp-editor-history smc-vfill">
<div class="webapp-editor-history-controls" style="display:flex; padding-left: 10px; padding-right: 10px; border-bottom: 1px solid lightgrey; background-color:#efefef">
<span style="color:#666; font-size:14pt; font-weight: bold; margin-right:1em">
<i class="fa fa-history"></i>
TimeTravel
</span>
<span>
<a href="#show-diff" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Show changes"><i class="fa fa-square-o"></i> Changes</a>
<a href="#hide-diff" class="btn btn-default hide" data-toggle="tooltip" data-placement="bottom" title="Show what changed"><i class="fa fa-check-square-o"></i> Changes</a>
</span>
<span class="webapp-editor-history-control-button-container btn-group smc-btn-group-nobreak" style="margin-left:1em">
<a href="#back" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Back"><i class="fa fa-step-backward"></i></a>
<a href="#forward" class="btn btn-default disabled" data-toggle="tooltip" data-placement="bottom" title="Forward"><i class="fa fa-step-forward"></i></a>
</span>
<span class="btn-group smc-btn-group-nobreak">
<a href="#file" class="btn btn-info " style="margin-left:1em" data-toggle="tooltip" data-placement="bottom" title="Show full file"><i class="fa fa-file-code-o"></i> Open File</a>
<a href="#revert" class="btn btn-warning hide" data-toggle="tooltip" data-placement="bottom" title="Revert the live file to the displayed revision"><i class="fa fa-undo"></i> Revert live version to this </a>
<a href="#snapshots" class="btn btn-default">
<i class="fa fa-life-saver"></i>
<span class="hidden-sm" style="font-size: 12px;">Backups</span>
</a>
<a href="#all" class="btn btn-default hide" data-toggle="tooltip" data-placement="bottom" title="Load complete history"><i class="fa fa-floppy-o"></i> Load All History </a>
<a href="#export" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Export to file"><i class="fa fa-file-export"></i> Export</a>
</span>
<div style="color:#666; margin-left: 1em">
<span class="webapp-editor-history-revision-time" style="font-weight: bold; font-size:12pt"></span><span class="webapp-editor-history-diff-mode hide"> to </span><span class="hide webapp-editor-history-diff-mode webapp-editor-history-revision-time2" style="font-weight: bold; font-size:12pt"></span><span class="webapp-editor-history-revision-number"> </span>
</div>
</div>
<div style="margin-top:7px; margin-right:15px;">
<span class="webapp-editor-history-revision-user lighten pull-right"></span>
</div>
<div class="webapp-editor-history-sliders" style="border-bottom: 1px solid lightgrey;">
<div class="webapp-editor-history-slider webapp-editor-history-slider-style">
</div>
<div class="webapp-editor-history-diff-slider hide webapp-editor-history-slider-style">
</div>
</div>
<div class="webapp-editor-history-no-viewer hide" style="margin-left:15px">
<b>WARNING: </b> History viewer for this file type not implemented, so showing underlying raw file instead.
</div>
<div class="webapp-editor-history-history_editor smc-vfill"></div>
</div>
<span class="sagews-input">
<span class="sagews-input-hr sagews-input-eval-state"></span>
<span class="sagews-input-hr sagews-input-run-state"></span>
<span class="sagews-input-hr sagews-input-newcell"></span>
</span>
<span class="sagews-output">
<span class="sagews-output-container">
<span class="sagews-output-messages"></span>
</span>
</span>
<div class="webapp-ipython-notebook">
<!--<h3 style="margin-left:1em">IPython Notebook: <span class="webapp-ipython-filename"></span></h3>-->
<div class="webapp-ipython-notebook-buttons hidden-xs">
<span class="webapp-ipython-notebook-status-messages lighten"> </span>
<span class="hide webapp-ipython-notebook-danger">DANGER: Users on this VM could connect unless you stop your ipython-notebook server (they would have to know secret internal project-id).</span>
<span class="btn-group">
<a href="#save" class="btn btn-sm btn-success" data-toggle="tooltip" data-placement="bottom" title="Save .ipynb file to disk (file is constantly sync'd with server).">
<i class="fa fa-save primary-icon"></i><i class="fa fa-cocalc-ring hide"></i> Save
</a>
<a href="#history" class="btn btn-sm btn-info webapp-editor-history-button hide" data-toggle="tooltip" data-placement="bottom" title="View the history of this file.">
<i class="fa fa-history"></i>
<span class="hidden-sm">TimeTravel</span>
</a>
<a href="#reload" class="btn btn-sm btn-warning" data-toggle="tooltip" data-placement="bottom" title="Reload this Notebook; use if the IPython server is killed or restarted on another port"> <i class="fa fa-refresh"></i> Reload</a>
<a href="#publish" class="btn btn-primary btn-sm" data-toggle="tooltip" data-placement="bottom" title="Publish this notebook for anybody to see"> <i class="fa fa-refresh fa-spin hide"> </i> <i class="fa fa-share-square"></i> Publish</a>
<a href="#info" class="btn btn-sm btn-info" data-toggle="tooltip" data-placement="bottom" title="Extra information about the IPython notebook"> <i class="fa fa-info-circle"></i> About </a>
</span>
</div>
<div class="visible-xs">
<span class="btn-group">
<a href="#save" class="btn btn-success btn-lg"> <i class="fa fa-save"></i> Save</a>
</span>
<span class="btn-group webapp-editor-codemirror-worksheet-buttons hide">
<a href="#execute" class="btn btn-default btn-lg"> <i class="fa fa-play"></i>
<span>Run</span>
</a>
<a href="#interrupt" class="btn btn-default btn-lg"> <i class="fa fa-stop"></i>
<span>Stop</span>
</a>
<a href="#tab" class="btn btn-default btn-lg"> <i class="fa fa-info-circle"></i>
<span>Tab</span>
</a>
</span>
<span class="btn-group">
<a href="#reload" class="btn btn-warning btn-lg"> <i class="fa fa-refresh"></i> Reload</a>
<a href="#info" class="btn btn-info btn-lg"> <i class="fa fa-info-circle"></i> </a>
</span>
</div>
<h3 class="webapp-ipython-notebook-connecting hide" style="margin-left:2em">Opening...</h3>
<div class="webapp-ipython-notebook-notebook"></div>
</div>
<div class="modal webapp-file-print-dialog" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close btn-close" aria-hidden="true">
<span style="font-size:20pt;">×</span>
</button>
<h3><i class="fa fa-print"> </i> Printable PDF version of <span class="webapp-file-print-filename"></span></h3>
</div>
<div class="well">
<h4>Heading <span class="lighten">(click to edit)</span></h4>
<div class="well" style="background-color:white; text-align:center">
<h4 class="webapp-file-print-title" contenteditable="true"></h4>
<h5 class="webapp-file-print-author" contenteditable="true"></h5>
<h5 class="webapp-file-print-date" contenteditable="true"></h5>
</div>
<div class="webapp-file-options-sagews hide">
<h4>Worksheet Options</h4>
<div class="well" style="background-color:white">
<div class="checkbox">
<label class="" rel="tooltip" title="Table of contents">
<input type="checkbox" class="webapp-file-print-contents" rel="tooltip">Table of contents
</label>
</div>
<div class="checkbox">
<label class="" rel="tooltip" title="Keep generated files">
<input type="checkbox" class="webapp-file-print-keepfiles" rel="tooltip">Keep generated files in a sub-directory. This is useful for debugging printing issues or additional editing.
<div class="smc-file-printing-tempdir hide"></div>
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-close pull-left btn-default btn-lg">Close</button>
<button class="btn btn-primary btn-submit pull-left btn-lg"><i class="fa fa-bolt primary-icon"> </i> <i class="fa fa-cocalc-ring hide"></i> Generate PDF</button>
<span class="webapp-file-printing-progress hide">Preparing PDF version...</span>
<a class="webapp-file-printing-link hide" target="_blank">link to PDF version</a>
</div>
</div>
</div>
</div>
<div class="modal webapp-goto-line-dialog" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close btn-close" aria-hidden="true">
<span style="font-size:20pt;">×</span>
</button>
<h3><i class="fa fa-bolt"> </i> Goto Line</h3>
</div>
<div class="well" style="margin:1em">
<div class="lighten">Enter <span class="webapp-goto-line-range"></span></div>
<input class="webapp-goto-line-input form-control" style="width:95%; margin-top: 1ex;" type="text" placeholder="">
</div>
<div class="modal-footer">
<button class="btn btn-close btn-default">Cancel</button>
<button class="btn btn-primary btn-submit">OK</button>
</div>
</div>
</div>
</div>
<div class="webapp-editor-textedit-buttonbar">
<span class="btn-group">
<a href="#bold" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Bold"><i class="fa fa-bold"></i></a>
<a href="#italic" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Italic"><i class="fa fa-italic"></i></a>
<a href="#underline" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Underline"><i class="fa fa-underline"></i></a>
<a href="#strikethrough" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Strike through"><i class="fa fa-strikethrough"></i></a>
<a href="#subscript" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Subscript (use LaTeX for serious equations)"><i class="fa fa-subscript"></i></a>
<a href="#superscript" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Superscript"><i class="fa fa-superscript"></i></a>
<a href="#comment" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Comment out selection"><i class="fa fa-comment-o"></i></a>
</span>
<span class="btn-group">
<a href="#equation" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Inline equation..."> $ </a>
<a href="#display_equation" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Displayed equation..."> $$ </a>
<a href="#insertunorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert unordered list"><i class="fa fa-list"></i></a>
<a href="#insertorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert ordered list"><i class="fa fa-list-ol"></i></a>
<a href="#link" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert link..."><i class="fa fa-link"></i></a>
<a href="#image" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert image..."><i class="fa fa-image"></i></a>
<a href="#table" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert table"><i class="fa fa-table"></i></a>
<a href="#horizontalRule" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert horizontal line">—</a>
<a href="#SpecialChar" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert Special Character ...">Ω</a>
</span>
<span class="btn-group">
<a href="#justifyleft" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Left justify"><i class="fa fa-align-left"></i></a>
<a href="#justifycenter" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Justify center"><i class="fa fa-align-center"></i></a>
<a href="#justifyright" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Right justify"><i class="fa fa-align-right"></i></a>
<a href="#justifyfull" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Justify full"><i class="fa fa-align-justify"></i></a>
<a href="#indent" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Indent/quote selected text"><i class="fa fa-indent"></i></a>
<a href="#unformat" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Remove formatting"><i class="fa fa-remove"></i></a>
<a href="#clean" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Make selected HTML valid"><i class="fa fa-code"></i></a>
</span>
<span class="btn-group">
<span class="btn-group sagews-output-editor-font-face smc-tooltip" data-toggle="tooltip" data-placement="bottom" title="Fonts">
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Font">
<i class="fa fa-font"></i> <b class="caret"></b>
</span>
<ul class="dropdown-menu">
</ul>
</span>
<span class="btn-group sagews-output-editor-font-size smc-tooltip" data-toggle="tooltip" data-placement="bottom" title="Font size">
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Text height">
<i class="fa fa-text-height"></i> <b class="caret"></b>
</span>
<ul class="dropdown-menu">
</ul>
</span>
<span class="btn-group sagews-output-editor-block-type smc-tooltip" data-toggle="tooltip" data-placement="bottom" title="Format type">
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Header">
<i class="fa fa-header"></i> <b class="caret"></b>
</span>
<ul class="dropdown-menu">
</ul>
</span>
</span>
<!-- color menus disabled/broken: see https://github.com/sagemathinc/cocalc/issues/1167 for re-implementing them -->
<span class="btn-group">
<span class="hide sagews-output-editor-foreground-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="bottom" title="Text color">
<input type="text" style="cursor:pointer" class="form-control">
<span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span>
</span>
</span>
<span class="btn-group">
<span class="hide sagews-output-editor-background-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="bottom" title="Text background highlight color">
<input type="text" style="cursor:pointer" class="form-control">
<span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span>
</span>
</span>
</div>
<div class="webapp-editor-codeedit-buttonbar hide" style="margin: 2px">
<!-- buttonbar.coffee populates all entries -->
</div>
<div class="webapp-editor-redit-buttonbar hide" style="margin: 2px">
<!-- buttonbar.coffee populates the entries -->
</div>
<div class="webapp-editor-julia-edit-buttonbar hide" style="margin: 2px">
<!-- buttonbar.coffee populates the entries -->
</div>
<div class="webapp-editor-sh-edit-buttonbar hide" style="margin: 2px">
<!-- buttonbar.coffee populates the entries -->
</div>
<div class="webapp-editor-fricas-edit-buttonbar hide" style="margin: 2px">
<!-- buttonbar.coffee populates the entries -->
</div>
<div class="webapp-editor-fallback-edit-buttonbar hide" style="margin: 2px">
<a class="btn btn-default" href="#todo">…</a>
</div>
<div class='sagews-output-raw_input'>
<div class="form-inline">
<div class="form-group">
<label class="sagews-output-raw_input-prompt" style="margin-right: 10px;">
</label>
<div class="input-group">
<input class="sagews-output-raw_input-value form-control">
<span class="input-group-btn">
<button class="btn btn-success sagews-output-raw_input-submit" type="button">
<i class="fa fa-check"></i>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
| Java |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RequestContextAwareInterface;
/**
* Initializes the locale based on the current request.
*
* This listener works in 2 modes:
*
* * 2.3 compatibility mode where you must call setRequest whenever the Request changes.
* * 2.4+ mode where you must pass a RequestStack instance in the constructor.
*
* @author Fabien Potencier <[email protected]>
*/
class LocaleListener implements EventSubscriberInterface
{
private $router;
private $defaultLocale;
private $requestStack;
/**
* RequestStack will become required in 3.0.
*/
public function __construct($defaultLocale = 'en', RequestContextAwareInterface $router = null, RequestStack $requestStack = null)
{
$this->defaultLocale = $defaultLocale;
$this->requestStack = $requestStack;
$this->router = $router;
}
public static function getSubscribedEvents()
{
return array(
// must be registered after the Router to have access to the _locale
KernelEvents::REQUEST => array( array( 'onKernelRequest', 16 ) ),
KernelEvents::FINISH_REQUEST => array( array( 'onKernelFinishRequest', 0 ) ),
);
}
/**
* Sets the current Request.
*
* This method was used to synchronize the Request, but as the HttpKernel
* is doing that automatically now, you should never call it directly.
* It is kept public for BC with the 2.3 version.
*
* @param Request|null $request A Request instance
*
* @deprecated Deprecated since version 2.4, to be removed in 3.0.
*/
public function setRequest(Request $request = null)
{
if (null === $request) {
return;
}
$this->setLocale($request);
$this->setRouterContext($request);
}
private function setLocale( Request $request )
{
if ($locale = $request->attributes->get( '_locale' )) {
$request->setLocale( $locale );
}
}
private function setRouterContext( Request $request )
{
if (null !== $this->router) {
$this->router->getContext()->setParameter( '_locale', $request->getLocale() );
}
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$request->setDefaultLocale($this->defaultLocale);
$this->setLocale($request);
$this->setRouterContext($request);
}
public function onKernelFinishRequest(FinishRequestEvent $event)
{
if (null === $this->requestStack) {
return; // removed when requestStack is required
}
if (null !== $parentRequest = $this->requestStack->getParentRequest()) {
$this->setRouterContext($parentRequest);
}
}
}
| Java |
package com.sapienter.jbilling.client.jspc.payment;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.sapienter.jbilling.client.util.Constants;
public final class review_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.release();
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.release();
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
if (_jspx_meth_sess_005fexistsAttribute_005f0(_jspx_page_context))
return;
out.write('\r');
out.write('\n');
if (_jspx_meth_sess_005fexistsAttribute_005f1(_jspx_page_context))
return;
out.write("\r\n\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_sess_005fexistsAttribute_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f0 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class);
_jspx_th_sess_005fexistsAttribute_005f0.setPageContext(_jspx_page_context);
_jspx_th_sess_005fexistsAttribute_005f0.setParent(null);
// /payment/review.jsp(30,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f0.setName("jsp_is_refund");
// /payment/review.jsp(30,0) name = value type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f0.setValue(false);
int _jspx_eval_sess_005fexistsAttribute_005f0 = _jspx_th_sess_005fexistsAttribute_005f0.doStartTag();
if (_jspx_eval_sess_005fexistsAttribute_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (_jspx_meth_tiles_005finsert_005f0(_jspx_th_sess_005fexistsAttribute_005f0, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_sess_005fexistsAttribute_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0);
return true;
}
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0);
return false;
}
private boolean _jspx_meth_tiles_005finsert_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f0 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
_jspx_th_tiles_005finsert_005f0.setPageContext(_jspx_page_context);
_jspx_th_tiles_005finsert_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f0);
// /payment/review.jsp(31,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f0.setDefinition("payment.review");
// /payment/review.jsp(31,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f0.setFlush(true);
int _jspx_eval_tiles_005finsert_005f0 = _jspx_th_tiles_005finsert_005f0.doStartTag();
if (_jspx_th_tiles_005finsert_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0);
return false;
}
private boolean _jspx_meth_sess_005fexistsAttribute_005f1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f1 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class);
_jspx_th_sess_005fexistsAttribute_005f1.setPageContext(_jspx_page_context);
_jspx_th_sess_005fexistsAttribute_005f1.setParent(null);
// /payment/review.jsp(33,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f1.setName("jsp_is_refund");
int _jspx_eval_sess_005fexistsAttribute_005f1 = _jspx_th_sess_005fexistsAttribute_005f1.doStartTag();
if (_jspx_eval_sess_005fexistsAttribute_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (_jspx_meth_tiles_005finsert_005f1(_jspx_th_sess_005fexistsAttribute_005f1, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_sess_005fexistsAttribute_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1);
return true;
}
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1);
return false;
}
private boolean _jspx_meth_tiles_005finsert_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f1 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
_jspx_th_tiles_005finsert_005f1.setPageContext(_jspx_page_context);
_jspx_th_tiles_005finsert_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f1);
// /payment/review.jsp(34,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f1.setDefinition("refund.review");
// /payment/review.jsp(34,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f1.setFlush(true);
int _jspx_eval_tiles_005finsert_005f1 = _jspx_th_tiles_005finsert_005f1.doStartTag();
if (_jspx_th_tiles_005finsert_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1);
return false;
}
}
| Java |
/*@author Jvlaple
*Crystal of Roots
*/
var status = 0;
var PQItems = Array(4001087, 4001088, 4001089, 4001090, 4001091, 4001092, 4001093);
importPackage(net.sf.odinms.client);
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else {
if (status >= 0 && mode == 0) {
cm.sendOk("Ok, keep preservering!");
cm.dispose();
return;
}
if (mode == 1)
status++;
else
status--;
if (status == 0 ) {
cm.sendYesNo("Hello I'm the Dungeon Exit NPC. Do you wish to go out from here?");
} else if (status == 1) {
var eim = cm.getPlayer().getEventInstance();
cm.warp(100000000, 0);
if (eim != null) {
eim.unregisterPlayer(cm.getPlayer());
}cm.dispose();
}
}
} | Java |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.notificationdialog;
public interface IFormUILogicCode
{
// No methods yet.
}
| Java |
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package v4
var (
BundleCharms = (*Handler).bundleCharms
ParseSearchParams = parseSearchParams
DefaultIcon = defaultIcon
ArchiveCacheVersionedMaxAge = &archiveCacheVersionedMaxAge
ArchiveCacheNonVersionedMaxAge = &archiveCacheNonVersionedMaxAge
ParamsLogLevels = paramsLogLevels
ParamsLogTypes = paramsLogTypes
ProcessIcon = processIcon
UsernameAttr = usernameAttr
GroupsAttr = groupsAttr
GetPromulgatedURL = (*Handler).getPromulgatedURL
)
| Java |
# frozen_string_literal: true
require "test_helper"
module GobiertoAdmin
class UserFormTest < ActiveSupport::TestCase
def valid_user_form
@valid_user_form ||= UserForm.new(
id: user.id,
name: user.name,
bio: user.bio,
email: user.email
)
end
def invalid_user_form
@invalid_user_form ||= UserForm.new(
name: nil,
email: nil
)
end
def user
@user ||= users(:reed)
end
def test_save_with_valid_attributes
assert valid_user_form.save
end
def test_save_with_invalid_attributes
refute invalid_user_form.save
end
def test_error_messages_with_invalid_attributes
invalid_user_form.save
assert_equal 1, invalid_user_form.errors.messages[:name].size
assert_equal 1, invalid_user_form.errors.messages[:email].size
end
def test_confirmation_email_delivery_when_changing_email
email_changing_form = UserForm.new(
id: user.id,
email: "[email protected]",
name: "Wadus"
)
assert_difference "ActionMailer::Base.deliveries.size", 1 do
email_changing_form.save
end
end
def test_confirmation_email_delivery_when_not_changing_email
assert_no_difference "ActionMailer::Base.deliveries.size" do
valid_user_form.save
end
end
end
end
| Java |
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import decimal
import pytest
from django.conf import settings
from shuup.core.models import Shipment, ShippingStatus, StockBehavior
from shuup.testing.factories import (
add_product_to_order, create_empty_order, create_product,
get_default_shop, get_default_supplier
)
from shuup.utils.excs import Problem
@pytest.mark.django_db
def test_shipment_identifier():
shop = get_default_shop()
supplier = get_default_supplier()
order = _get_order(shop, supplier)
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
shipment = order.create_shipment({line.product: 1}, supplier=supplier)
expected_key_start = "%s/%s" % (order.pk, i)
assert shipment.identifier.startswith(expected_key_start)
assert order.shipments.count() == int(line.quantity)
assert order.shipping_status == ShippingStatus.FULLY_SHIPPED # Check that order is now fully shipped
assert not order.can_edit()
@pytest.mark.django_db
def test_shipment_creation_from_unsaved_shipment():
shop = get_default_shop()
supplier = get_default_supplier()
order = _get_order(shop, supplier)
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
unsaved_shipment = Shipment(order=order, supplier=supplier)
shipment = order.create_shipment({line.product: 1}, shipment=unsaved_shipment)
expected_key_start = "%s/%s" % (order.pk, i)
assert shipment.identifier.startswith(expected_key_start)
assert order.shipments.count() == int(line.quantity)
@pytest.mark.django_db
def test_shipment_creation_without_supplier_and_shipment():
shop = get_default_shop()
supplier = get_default_supplier()
order = _get_order(shop, supplier)
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
with pytest.raises(AssertionError):
order.create_shipment({line.product: 1})
assert order.shipments.count() == 0
@pytest.mark.django_db
def test_shipment_creation_with_invalid_unsaved_shipment():
shop = get_default_shop()
supplier = get_default_supplier()
order = _get_order(shop, supplier)
second_order = create_empty_order(shop=shop)
second_order.full_clean()
second_order.save()
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
with pytest.raises(AssertionError):
unsaved_shipment = Shipment(supplier=supplier, order=second_order)
order.create_shipment({line.product: 1}, shipment=unsaved_shipment)
assert order.shipments.count() == 0
@pytest.mark.django_db
def test_partially_shipped_order_status():
shop = get_default_shop()
supplier = get_default_supplier()
order = _get_order(shop, supplier)
assert order.can_edit()
first_product_line = order.lines.exclude(product_id=None).first()
assert first_product_line.quantity > 1
order.create_shipment({first_product_line.product: 1}, supplier=supplier)
assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED
assert not order.can_edit()
@pytest.mark.django_db
def test_shipment_delete():
shop = get_default_shop()
supplier = get_default_supplier()
order = _get_order(shop, supplier)
assert order.can_edit()
first_product_line = order.lines.exclude(product_id=None).first()
assert first_product_line.quantity > 1
shipment = order.create_shipment({first_product_line.product: 1}, supplier=supplier)
assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED
assert order.shipments.all().count() == 1
# Test shipment delete
shipment.soft_delete()
assert order.shipments.all().count() == 1
assert order.shipments.all_except_deleted().count() == 0
# Check the shipping status update
assert order.shipping_status == ShippingStatus.NOT_SHIPPED
@pytest.mark.django_db
def test_shipment_with_insufficient_stock():
if "shuup.simple_supplier" not in settings.INSTALLED_APPS:
pytest.skip("Need shuup.simple_supplier in INSTALLED_APPS")
from shuup_tests.simple_supplier.utils import get_simple_supplier
shop = get_default_shop()
supplier = get_simple_supplier()
order = _get_order(shop, supplier, stocked=True)
product_line = order.lines.products().first()
product = product_line.product
assert product_line.quantity == 15
supplier.adjust_stock(product.pk, delta=10)
stock_status = supplier.get_stock_status(product.pk)
assert stock_status.physical_count == 10
order.create_shipment({product: 5}, supplier=supplier)
assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED
assert order.shipments.all().count() == 1
with pytest.raises(Problem):
order.create_shipment({product: 10}, supplier=supplier)
# Should be fine after adding more stock
supplier.adjust_stock(product.pk, delta=5)
order.create_shipment({product: 10}, supplier=supplier)
def _get_order(shop, supplier, stocked=False):
order = create_empty_order(shop=shop)
order.full_clean()
order.save()
for product_data in _get_product_data(stocked):
quantity = product_data.pop("quantity")
product = create_product(
sku=product_data.pop("sku"),
shop=shop,
supplier=supplier,
default_price=3.33,
**product_data)
add_product_to_order(order, supplier, product, quantity=quantity, taxless_base_unit_price=1)
order.cache_prices()
order.check_all_verified()
order.save()
return order
def _get_product_data(stocked=False):
return [
{
"sku": "sku1234",
"net_weight": decimal.Decimal("1"),
"gross_weight": decimal.Decimal("43.34257"),
"quantity": decimal.Decimal("15"),
"stock_behavior": StockBehavior.STOCKED if stocked else StockBehavior.UNSTOCKED
}
]
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.