repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Jspsun/LEETCodePractice | Python/PowerOfTwo.py | 325 | class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1 or n == 2:
return True
number = 2
while (number <= n):
number *= 2
if(number == n):
return True
return False
| mit |
romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/Font/LicenseInfoURL.php | 781 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Font;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class LicenseInfoURL extends AbstractTag
{
protected $Id = 14;
protected $Name = 'LicenseInfoURL';
protected $FullName = 'Font::Name';
protected $GroupName = 'Font';
protected $g0 = 'Font';
protected $g1 = 'Font';
protected $g2 = 'Document';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'License Info URL';
}
| mit |
rainliu/sip | Response.go | 3737 | package sip
import (
"bytes"
"fmt"
"io"
"strings"
)
type Response interface {
Message
SetStatusCode(statusCode int) error
GetStatusCode() int
SetReasonPhrase(reasonPhrase string) error
GetReasonPhrase() string
}
const (
TRYING = 100
RINGING = 180
CALL_IS_BEING_FORWARDED = 181
QUEUED = 182
SESSION_PROGRESS = 183
OK = 200
ACCEPTED = 202
MULTIPLE_CHOICES = 300
MOVED_PERMANENTLY = 301
MOVED_TEMPORARILY = 302
USE_PROXY = 305
ALTERNATIVE_SERVICE = 380
BAD_REQUEST = 400
UNAUTHORIZED = 401
PAYMENT_REQUIRED = 402
FORBIDDEN = 403
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
NOT_ACCEPTABLE = 406
PROXY_AUTHENTICATION_REQUIRED = 407
REQUEST_TIMEOUT = 408
GONE = 410
REQUEST_ENTITY_TOO_LARGE = 413
REQUEST_URI_TOO_LONG = 414
UNSUPPORTED_MEDIA_TYPE = 415
UNSUPPORTED_URI_SCHEME = 416
BAD_EXTENSION = 420
EXTENSION_REQUIRED = 421
INTERVAL_TOO_BRIEF = 423
TEMPORARILY_UNAVAILABLE = 480
CALL_OR_TRANSACTION_DOES_NOT_EXIST = 481
LOOP_DETECTED = 482
TOO_MANY_HOPS = 483
ADDRESS_INCOMPLETE = 484
AMBIGUOUS = 485
BUSY_HERE = 486
REQUEST_TERMINATED = 487
NOT_ACCEPTABLE_HERE = 488
BAD_EVENT = 489
REQUEST_PENDING = 491
UNDECIPHERABLE = 493
SERVER_INTERNAL_ERROR = 500
NOT_IMPLEMENTED = 501
BAD_GATEWAY = 502
SERVICE_UNAVAILABLE = 503
SERVER_TIMEOUT = 504
VERSION_NOT_SUPPORTED = 505
MESSAGE_TOO_LARGE = 513
BUSY_EVERYWHERE = 600
DECLINE = 603
DOES_NOT_EXIST_ANYWHERE = 604
SESSION_NOT_ACCEPTABLE = 606
)
////////////////////////////////////////////////////////////////////////////////
type response struct {
message
statusCode int
reasonPhrase string
}
func NewResponse(statusCode int, reasonPhrase string, body io.Reader) *response {
this := &response{
message: message{
sipVersion: "SIP/2.0",
header: make(Header),
body: body,
},
statusCode: statusCode,
reasonPhrase: reasonPhrase,
}
this.StartLineWriter = this
if body != nil {
switch v := body.(type) {
case *bytes.Buffer:
this.SetContentLength(int64(v.Len()))
case *bytes.Reader:
this.SetContentLength(int64(v.Len()))
case *strings.Reader:
this.SetContentLength(int64(v.Len()))
}
}
return this
}
func (this *response) SetStatusCode(statusCode int) error {
this.statusCode = statusCode
return nil
}
func (this *response) GetStatusCode() int {
return this.statusCode
}
func (this *response) SetReasonPhrase(reasonPhrase string) error {
this.reasonPhrase = reasonPhrase
return nil
}
func (this *response) GetReasonPhrase() string {
return this.reasonPhrase
}
//SIP/2.0 StatusCode reasonPhrase
func (this *response) StartLineWrite(w io.Writer) (err error) {
if _, err = fmt.Fprintf(w, "SIP/2.0 %d %s\r\n", this.GetStatusCode(), this.GetReasonPhrase()); err != nil {
return err
}
return nil
}
| mit |
mjmasn/meteor | packages/ddp-client/livedata_connection_tests.js | 72139 | import lolex from 'lolex';
var newConnection = function (stream, options) {
// Some of these tests leave outstanding methods with no result yet
// returned. This should not block us from re-running tests when sources
// change.
return new LivedataTest.Connection(stream, _.extend({
reloadWithOutstanding: true,
bufferedWritesInterval: 0
}, options));
};
var makeConnectMessage = function (session) {
var msg = {
msg: 'connect',
version: LivedataTest.SUPPORTED_DDP_VERSIONS[0],
support: LivedataTest.SUPPORTED_DDP_VERSIONS
};
if (session)
msg.session = session;
return msg;
};
// Tests that stream got a message that matches expected.
// Expected is normally an object, and allows a wildcard value of '*',
// which will then match any value.
// Returns the message (parsed as a JSON object if expected is an object);
// which is particularly handy if you want to extract a value that was
// matched as a wildcard.
var testGotMessage = function (test, stream, expected) {
if (stream.sent.length === 0) {
test.fail({error: 'no message received', expected: expected});
return undefined;
}
var got = stream.sent.shift();
if (typeof got === 'string' && typeof expected === 'object')
got = JSON.parse(got);
// An expected value of '*' matches any value, and the matching value (or
// array of matching values, if there are multiple) is returned from this
// function.
if (typeof expected === 'object') {
var keysWithStarValues = [];
_.each(expected, function (v, k) {
if (v === '*')
keysWithStarValues.push(k);
});
_.each(keysWithStarValues, function (k) {
expected[k] = got[k];
});
}
test.equal(got, expected);
return got;
};
var startAndConnect = function(test, stream) {
stream.reset(); // initial connection start.
testGotMessage(test, stream, makeConnectMessage());
test.length(stream.sent, 0);
stream.receive({msg: 'connected', session: SESSION_ID});
test.length(stream.sent, 0);
};
var SESSION_ID = '17';
Tinytest.add("livedata stub - receive data", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
// data comes in for unknown collection.
var coll_name = Random.id();
stream.receive({msg: 'added', collection: coll_name, id: '1234',
fields: {a: 1}});
// break throught the black box and test internal state
test.length(conn._updatesForUnknownStores[coll_name], 1);
// XXX: Test that the old signature of passing manager directly instead of in
// options works.
var coll = new Mongo.Collection(coll_name, conn);
// queue has been emptied and doc is in db.
test.isUndefined(conn._updatesForUnknownStores[coll_name]);
test.equal(coll.find({}).fetch(), [{_id:'1234', a:1}]);
// second message. applied directly to the db.
stream.receive({msg: 'changed', collection: coll_name, id: '1234',
fields: {a:2}});
test.equal(coll.find({}).fetch(), [{_id:'1234', a:2}]);
test.isUndefined(conn._updatesForUnknownStores[coll_name]);
});
Tinytest.add("livedata stub - buffering data", function (test) {
// Install special setTimeout that allows tick-by-tick control in tests using sinonjs 'lolex'
// This needs to be before the connection is instantiated.
const clock = lolex.install();
const tick = (timeout) => clock.tick(timeout);
const stream = new StubStream();
const conn = newConnection(stream, {
bufferedWritesInterval: 10,
bufferedWritesMaxAge: 40,
});
startAndConnect(test, stream);
const coll_name = Random.id();
const coll = new Mongo.Collection(coll_name, conn);
const testDocCount = (count) => test.equal(coll.find({}).count(), count);
const addDoc = () => {
stream.receive({
msg: 'added',
collection: coll_name,
id: Random.id(),
fields: {}
});
};
// Starting at 0 ticks. At this point we haven't advanced the fake clock at all.
addDoc(); // 1st Doc
testDocCount(0); // No doc been recognized yet because it's buffered, waiting for more.
tick(6); // 6 total ticks
testDocCount(0); // Ensure that the doc still hasn't shown up, despite the clock moving forward.
tick(4) // 10 total ticks, 1st buffer interval
testDocCount(1); // No other docs have arrived, so we 'see' the 1st doc.
addDoc(); // 2nd doc
tick(1); // 11 total ticks (1 since last flush)
testDocCount(1); // Again, second doc hasn't arrived because we're waiting for more...
tick(9); // 20 total ticks (10 ticks since last flush & the 2nd 10-tick interval)
testDocCount(2); // Now we're here and got the second document.
// Add several docs, frequently enough that we buffer multiple times before the next flush.
addDoc(); // 3 docs
tick(6); // 26 ticks (6 since last flush)
addDoc(); // 4 docs
tick(6); // 32 ticks (12 since last flush)
addDoc(); // 5 docs
tick(6); // 38 ticks (18 since last flush)
addDoc(); // 6 docs
tick(6); // 44 ticks (24 since last flush)
addDoc(); // 7 docs
tick(9); // 53 ticks (33 since last flush)
addDoc(); // 8 docs
tick(9); // 62 ticks! (42 ticks since last flush, over max-age - next interval triggers flush)
testDocCount(2); // Still at 2 from before! (Just making sure)
tick(1); // Ok, 63 ticks (10 since last doc, so this should cause the flush of all the docs)
testDocCount(8); // See all the docs.
// Put things back how they were.
clock.uninstall();
});
Tinytest.add("livedata stub - subscribe", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
// subscribe
var callback_fired = false;
var sub = conn.subscribe('my_data', function () {
callback_fired = true;
});
test.isFalse(callback_fired);
test.length(stream.sent, 1);
var message = JSON.parse(stream.sent.shift());
var id = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'my_data', params: []});
var reactivelyReady = false;
var autorunHandle = Tracker.autorun(function () {
reactivelyReady = sub.ready();
});
test.isFalse(reactivelyReady);
// get the sub satisfied. callback fires.
stream.receive({msg: 'ready', 'subs': [id]});
test.isTrue(callback_fired);
Tracker.flush();
test.isTrue(reactivelyReady);
// Unsubscribe.
sub.stop();
test.length(stream.sent, 1);
message = JSON.parse(stream.sent.shift());
test.equal(message, {msg: 'unsub', id: id});
Tracker.flush();
test.isFalse(reactivelyReady);
// Resubscribe.
conn.subscribe('my_data');
test.length(stream.sent, 1);
message = JSON.parse(stream.sent.shift());
var id2 = message.id;
test.notEqual(id, id2);
delete message.id;
test.equal(message, {msg: 'sub', name: 'my_data', params: []});
});
Tinytest.add("livedata stub - reactive subscribe", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var rFoo = new ReactiveVar('foo1');
var rBar = new ReactiveVar('bar1');
var onReadyCount = {};
var onReady = function (tag) {
return function () {
if (_.has(onReadyCount, tag))
++onReadyCount[tag];
else
onReadyCount[tag] = 1;
};
};
// Subscribe to some subs.
var stopperHandle, completerHandle;
var autorunHandle = Tracker.autorun(function () {
conn.subscribe("foo", rFoo.get(), onReady(rFoo.get()));
conn.subscribe("bar", rBar.get(), onReady(rBar.get()));
completerHandle = conn.subscribe("completer", onReady("completer"));
stopperHandle = conn.subscribe("stopper", onReady("stopper"));
});
var completerReady;
var readyAutorunHandle = Tracker.autorun(function() {
completerReady = completerHandle.ready();
});
// Check sub messages. (Assume they are sent in the order executed.)
test.length(stream.sent, 4);
var message = JSON.parse(stream.sent.shift());
var idFoo1 = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'foo', params: ['foo1']});
message = JSON.parse(stream.sent.shift());
var idBar1 = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'bar', params: ['bar1']});
message = JSON.parse(stream.sent.shift());
var idCompleter = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'completer', params: []});
message = JSON.parse(stream.sent.shift());
var idStopper = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'stopper', params: []});
// Haven't hit onReady yet.
test.equal(onReadyCount, {});
Tracker.flush();
test.isFalse(completerReady);
// "completer" gets ready now. its callback should fire.
stream.receive({msg: 'ready', 'subs': [idCompleter]});
test.equal(onReadyCount, {completer: 1});
test.length(stream.sent, 0);
Tracker.flush();
test.isTrue(completerReady);
// Stop 'stopper'.
stopperHandle.stop();
test.length(stream.sent, 1);
message = JSON.parse(stream.sent.shift());
test.equal(message, {msg: 'unsub', id: idStopper});
test.equal(onReadyCount, {completer: 1});
Tracker.flush();
test.isTrue(completerReady);
// Change the foo subscription and flush. We should sub to the new foo
// subscription, re-sub to the stopper subscription, and then unsub from the old
// foo subscription. The bar subscription should be unaffected. The completer
// subscription should *NOT* call its new onReady callback, because we only
// call at most one onReady for a given reactively-saved subscription.
// The completerHandle should have been reestablished to the ready handle.
rFoo.set("foo2");
Tracker.flush();
test.length(stream.sent, 3);
message = JSON.parse(stream.sent.shift());
var idFoo2 = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'foo', params: ['foo2']});
message = JSON.parse(stream.sent.shift());
var idStopperAgain = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'stopper', params: []});
message = JSON.parse(stream.sent.shift());
test.equal(message, {msg: 'unsub', id: idFoo1});
test.equal(onReadyCount, {completer: 1});
test.isTrue(completerReady);
// Ready the stopper and bar subs. Completing stopper should call only the
// onReady from the new subscription because they were separate subscriptions
// started at different times and the first one was explicitly torn down by
// the client; completing bar should call only the onReady from the new
// subscription because we only call at most one onReady per reactively-saved
// subscription.
stream.receive({msg: 'ready', 'subs': [idStopperAgain, idBar1]});
test.equal(onReadyCount, {completer: 1, bar1: 1, stopper: 1});
// Shut down the autorun. This should unsub us from all current subs at flush
// time.
autorunHandle.stop();
Tracker.flush();
test.isFalse(completerReady);
readyAutorunHandle.stop();
test.length(stream.sent, 4);
// The order of unsubs here is not important.
var unsubMessages = _.map(stream.sent, JSON.parse);
stream.sent.length = 0;
test.equal(_.unique(_.pluck(unsubMessages, 'msg')), ['unsub']);
var actualIds = _.pluck(unsubMessages, 'id');
var expectedIds = [idFoo2, idBar1, idCompleter, idStopperAgain];
actualIds.sort();
expectedIds.sort();
test.equal(actualIds, expectedIds);
});
Tinytest.add("livedata stub - reactive subscribe handle correct", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var rFoo = new ReactiveVar('foo1');
// Subscribe to some subs.
var fooHandle, fooReady;
var autorunHandle = Tracker.autorun(function () {
fooHandle = conn.subscribe("foo", rFoo.get());
Tracker.autorun(function() {
fooReady = fooHandle.ready();
});
});
var message = JSON.parse(stream.sent.shift());
var idFoo1 = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'foo', params: ['foo1']});
// Not ready yet
Tracker.flush();
test.isFalse(fooHandle.ready());
test.isFalse(fooReady);
// change the argument to foo. This will make a new handle, which isn't ready
// the ready autorun should invalidate, reading the new false value, and
// setting up a new dep which goes true soon
rFoo.set("foo2");
Tracker.flush();
test.length(stream.sent, 2);
message = JSON.parse(stream.sent.shift());
var idFoo2 = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'foo', params: ['foo2']});
message = JSON.parse(stream.sent.shift());
test.equal(message, {msg: 'unsub', id: idFoo1});
Tracker.flush();
test.isFalse(fooHandle.ready());
test.isFalse(fooReady);
// "foo" gets ready now. The handle should be ready and the autorun rerun
stream.receive({msg: 'ready', 'subs': [idFoo2]});
test.length(stream.sent, 0);
Tracker.flush();
test.isTrue(fooHandle.ready());
test.isTrue(fooReady);
// change the argument to foo. This will make a new handle, which isn't ready
// the ready autorun should invalidate, making fooReady false too
rFoo.set("foo3");
Tracker.flush();
test.length(stream.sent, 2);
message = JSON.parse(stream.sent.shift());
var idFoo3 = message.id;
delete message.id;
test.equal(message, {msg: 'sub', name: 'foo', params: ['foo3']});
message = JSON.parse(stream.sent.shift());
test.equal(message, {msg: 'unsub', id: idFoo2});
Tracker.flush();
test.isFalse(fooHandle.ready());
test.isFalse(fooReady);
// "foo" gets ready again
stream.receive({msg: 'ready', 'subs': [idFoo3]});
test.length(stream.sent, 0);
Tracker.flush();
test.isTrue(fooHandle.ready());
test.isTrue(fooReady);
autorunHandle.stop();
});
Tinytest.add("livedata stub - this", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
conn.methods({test_this: function() {
test.isTrue(this.isSimulation);
this.unblock(); // should be a no-op
}});
// should throw no exceptions
conn.call('test_this', _.identity);
// satisfy method, quiesce connection
var message = JSON.parse(stream.sent.shift());
test.isUndefined(message.randomSeed);
test.equal(message, {msg: 'method', method: 'test_this',
params: [], id:message.id});
test.length(stream.sent, 0);
stream.receive({msg: 'result', id:message.id, result:null});
stream.receive({msg: 'updated', 'methods': [message.id]});
});
if (Meteor.isClient) {
Tinytest.add("livedata stub - methods", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
// setup method
conn.methods({do_something: function (x) {
coll.insert({value: x});
}});
// setup observers
var counts = {added: 0, removed: 0, changed: 0, moved: 0};
var handle = coll.find({}).observe(
{ addedAt: function () { counts.added += 1; },
removedAt: function () { counts.removed += 1; },
changedAt: function () { counts.changed += 1; },
movedTo: function () { counts.moved += 1; }
});
// call method with results callback
var callback1Fired = false;
conn.call('do_something', 'friday!', function (err, res) {
test.isUndefined(err);
test.equal(res, '1234');
callback1Fired = true;
});
test.isFalse(callback1Fired);
// observers saw the method run.
test.equal(counts, {added: 1, removed: 0, changed: 0, moved: 0});
// get response from server
var message = testGotMessage(test, stream, {msg: 'method',
method: 'do_something',
params: ['friday!'],
id: '*',
randomSeed: '*'});
test.equal(coll.find({}).count(), 1);
test.equal(coll.find({value: 'friday!'}).count(), 1);
var docId = coll.findOne({value: 'friday!'})._id;
// results does not yet result in callback, because data is not
// ready.
stream.receive({msg: 'result', id:message.id, result: "1234"});
test.isFalse(callback1Fired);
// result message doesn't affect data
test.equal(coll.find({}).count(), 1);
test.equal(coll.find({value: 'friday!'}).count(), 1);
test.equal(counts, {added: 1, removed: 0, changed: 0, moved: 0});
// data methods do not show up (not quiescent yet)
stream.receive({msg: 'added', collection: collName, id: MongoID.idStringify(docId),
fields: {value: 'tuesday'}});
test.equal(coll.find({}).count(), 1);
test.equal(coll.find({value: 'friday!'}).count(), 1);
test.equal(counts, {added: 1, removed: 0, changed: 0, moved: 0});
// send another methods (unknown on client)
var callback2Fired = false;
conn.call('do_something_else', 'monday', function (err, res) {
callback2Fired = true;
});
test.isFalse(callback1Fired);
test.isFalse(callback2Fired);
// test we still send a method request to server
var message2 = JSON.parse(stream.sent.shift());
test.isUndefined(message2.randomSeed);
test.equal(message2, {msg: 'method', method: 'do_something_else',
params: ['monday'], id: message2.id});
// get the first data satisfied message. changes are applied to database even
// though another method is outstanding, because the other method didn't have
// a stub. and its callback is called.
stream.receive({msg: 'updated', 'methods': [message.id]});
test.isTrue(callback1Fired);
test.isFalse(callback2Fired);
test.equal(coll.find({}).count(), 1);
test.equal(coll.find({value: 'tuesday'}).count(), 1);
test.equal(counts, {added: 1, removed: 0, changed: 1, moved: 0});
// second result
stream.receive({msg: 'result', id:message2.id, result:"bupkis"});
test.isFalse(callback2Fired);
// get second satisfied; no new changes are applied.
stream.receive({msg: 'updated', 'methods': [message2.id]});
test.isTrue(callback2Fired);
test.equal(coll.find({}).count(), 1);
test.equal(coll.find({value: 'tuesday', _id: docId}).count(), 1);
test.equal(counts, {added: 1, removed: 0, changed: 1, moved: 0});
handle.stop();
});
}
Tinytest.add("livedata stub - mutating method args", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
conn.methods({mutateArgs: function (arg) {
arg.foo = 42;
}});
conn.call('mutateArgs', {foo: 50}, _.identity);
// Method should be called with original arg, not mutated arg.
var message = JSON.parse(stream.sent.shift());
test.isUndefined(message.randomSeed);
test.equal(message, {msg: 'method', method: 'mutateArgs',
params: [{foo: 50}], id: message.id});
test.length(stream.sent, 0);
});
var observeCursor = function (test, cursor) {
var counts = {added: 0, removed: 0, changed: 0, moved: 0};
var expectedCounts = _.clone(counts);
var handle = cursor.observe(
{ addedAt: function () { counts.added += 1; },
removedAt: function () { counts.removed += 1; },
changedAt: function () { counts.changed += 1; },
movedTo: function () { counts.moved += 1; }
});
return {
stop: _.bind(handle.stop, handle),
expectCallbacks: function (delta) {
_.each(delta, function (mod, field) {
expectedCounts[field] += mod;
});
test.equal(counts, expectedCounts);
}
};
};
// method calls another method in simulation. see not sent.
if (Meteor.isClient) {
Tinytest.add("livedata stub - methods calling methods", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var coll_name = Random.id();
var coll = new Mongo.Collection(coll_name, {connection: conn});
// setup methods
conn.methods({
do_something: function () {
conn.call('do_something_else');
},
do_something_else: function () {
coll.insert({a: 1});
}
});
var o = observeCursor(test, coll.find());
// call method.
conn.call('do_something', _.identity);
// see we only send message for outer methods
var message = testGotMessage(test, stream, {msg: 'method',
method: 'do_something',
params: [],
id: '*',
randomSeed: '*'});
test.length(stream.sent, 0);
// but inner method runs locally.
o.expectCallbacks({added: 1});
test.equal(coll.find().count(), 1);
var docId = coll.findOne()._id;
test.equal(coll.findOne(), {_id: docId, a: 1});
// we get the results
stream.receive({msg: 'result', id:message.id, result:"1234"});
// get data from the method. data from this doc does not show up yet, but data
// from another doc does.
stream.receive({msg: 'added', collection: coll_name, id: MongoID.idStringify(docId),
fields: {value: 'tuesday'}});
o.expectCallbacks();
test.equal(coll.findOne(docId), {_id: docId, a: 1});
stream.receive({msg: 'added', collection: coll_name, id: 'monkey',
fields: {value: 'bla'}});
o.expectCallbacks({added: 1});
test.equal(coll.findOne(docId), {_id: docId, a: 1});
var newDoc = coll.findOne({value: 'bla'});
test.isTrue(newDoc);
test.equal(newDoc, {_id: newDoc._id, value: 'bla'});
// get method satisfied. all data shows up. the 'a' field is reverted and
// 'value' field is set.
stream.receive({msg: 'updated', 'methods': [message.id]});
o.expectCallbacks({changed: 1});
test.equal(coll.findOne(docId), {_id: docId, value: 'tuesday'});
test.equal(coll.findOne(newDoc._id), {_id: newDoc._id, value: 'bla'});
o.stop();
});
}
Tinytest.add("livedata stub - method call before connect", function (test) {
var stream = new StubStream;
var conn = newConnection(stream);
var callbackOutput = [];
conn.call('someMethod', function (err, result) {
callbackOutput.push(result);
});
test.equal(callbackOutput, []);
// the real stream drops all output pre-connection
stream.sent.length = 0;
// Now connect.
stream.reset();
testGotMessage(test, stream, makeConnectMessage());
testGotMessage(test, stream, {msg: 'method', method: 'someMethod',
params: [], id: '*'});
});
Tinytest.add("livedata stub - reconnect", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
var o = observeCursor(test, coll.find());
// subscribe
var subCallbackFired = false;
var sub = conn.subscribe('my_data', function () {
subCallbackFired = true;
});
test.isFalse(subCallbackFired);
var subMessage = JSON.parse(stream.sent.shift());
test.equal(subMessage, {msg: 'sub', name: 'my_data', params: [],
id: subMessage.id});
// get some data. it shows up.
stream.receive({msg: 'added', collection: collName,
id: '1234', fields: {a:1}});
test.equal(coll.find({}).count(), 1);
o.expectCallbacks({added: 1});
test.isFalse(subCallbackFired);
stream.receive({msg: 'changed', collection: collName,
id: '1234', fields: {b:2}});
stream.receive({msg: 'ready',
subs: [subMessage.id] // satisfy sub
});
test.isTrue(subCallbackFired);
subCallbackFired = false; // re-arm for test that it doesn't fire again.
test.equal(coll.find({a:1, b:2}).count(), 1);
o.expectCallbacks({changed: 1});
// call method.
var methodCallbackFired = false;
conn.call('do_something', function () {
methodCallbackFired = true;
});
conn.apply('do_something_else', [], {wait: true}, _.identity);
conn.apply('do_something_later', [], _.identity);
test.isFalse(methodCallbackFired);
// The non-wait method should send, but not the wait method.
var methodMessage = JSON.parse(stream.sent.shift());
test.isUndefined(methodMessage.randomSeed);
test.equal(methodMessage, {msg: 'method', method: 'do_something',
params: [], id:methodMessage.id});
test.equal(stream.sent.length, 0);
// more data. shows up immediately because there was no relevant method stub.
stream.receive({msg: 'changed', collection: collName,
id: '1234', fields: {c:3}});
test.equal(coll.findOne('1234'), {_id: '1234', a: 1, b: 2, c: 3});
o.expectCallbacks({changed: 1});
// stream reset. reconnect! we send a connect, our pending method, and our
// sub. The wait method still is blocked.
stream.reset();
testGotMessage(test, stream, makeConnectMessage(SESSION_ID));
testGotMessage(test, stream, methodMessage);
testGotMessage(test, stream, subMessage);
// reconnect with different session id
stream.receive({msg: 'connected', session: SESSION_ID + 1});
// resend data. doesn't show up: we're in reconnect quiescence.
stream.receive({msg: 'added', collection: collName,
id: '1234', fields: {a:1, b:2, c:3, d: 4}});
stream.receive({msg: 'added', collection: collName,
id: '2345', fields: {e: 5}});
test.equal(coll.findOne('1234'), {_id: '1234', a: 1, b: 2, c: 3});
test.isFalse(coll.findOne('2345'));
o.expectCallbacks();
// satisfy and return the method
stream.receive({msg: 'updated',
methods: [methodMessage.id]});
test.isFalse(methodCallbackFired);
stream.receive({msg: 'result', id:methodMessage.id, result:"bupkis"});
// The callback still doesn't fire (and we don't send the wait method): we're
// still in global quiescence
test.isFalse(methodCallbackFired);
test.equal(stream.sent.length, 0);
// still no update.
test.equal(coll.findOne('1234'), {_id: '1234', a: 1, b: 2, c: 3});
test.isFalse(coll.findOne('2345'));
o.expectCallbacks();
// re-satisfy sub
stream.receive({msg: 'ready', subs: [subMessage.id]});
// now the doc changes and method callback is called, and the wait method is
// sent. the sub callback isn't re-called.
test.isTrue(methodCallbackFired);
test.isFalse(subCallbackFired);
test.equal(coll.findOne('1234'), {_id: '1234', a: 1, b: 2, c: 3, d: 4});
test.equal(coll.findOne('2345'), {_id: '2345', e: 5});
o.expectCallbacks({added: 1, changed: 1});
var waitMethodMessage = JSON.parse(stream.sent.shift());
test.isUndefined(waitMethodMessage.randomSeed);
test.equal(waitMethodMessage, {msg: 'method', method: 'do_something_else',
params: [], id: waitMethodMessage.id});
test.equal(stream.sent.length, 0);
stream.receive({msg: 'result', id: waitMethodMessage.id, result: "bupkis"});
test.equal(stream.sent.length, 0);
stream.receive({msg: 'updated', methods: [waitMethodMessage.id]});
// wait method done means we can send the third method
test.equal(stream.sent.length, 1);
var laterMethodMessage = JSON.parse(stream.sent.shift());
test.isUndefined(laterMethodMessage.randomSeed);
test.equal(laterMethodMessage, {msg: 'method', method: 'do_something_later',
params: [], id: laterMethodMessage.id});
o.stop();
});
if (Meteor.isClient) {
Tinytest.add("livedata stub - reconnect non-idempotent method", function(test) {
// This test is for https://github.com/meteor/meteor/issues/6108
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var methodCallbackFired = false;
var methodCallbackErrored = false;
// call with noRetry true so that the method should fail to retry on reconnect.
conn.apply('do_something', [], {noRetry: true}, function(error) {
methodCallbackFired = true;
// failure on reconnect should trigger an error.
if (error && error.error === 'invocation-failed') {
methodCallbackErrored = true;
}
});
//The method has not succeeded yet
test.isFalse(methodCallbackFired);
// reconnect.
stream.sent.shift();
// "receive the message"
stream.reset();
// verify that a reconnect message was sent.
testGotMessage(test, stream, makeConnectMessage(SESSION_ID));
// Make sure that the stream triggers connection.
stream.receive({msg: 'connected', session: SESSION_ID + 1});
//The method callback should fire even though the stream has not sent a response.
//the callback should have been fired with an error.
test.isTrue(methodCallbackFired);
test.isTrue(methodCallbackErrored);
// verify that the method message was not sent.
test.isUndefined(stream.sent.shift());
});
}
if (Meteor.isClient) {
Tinytest.add("livedata stub - reconnect method which only got result", function (test) {
var stream = new StubStream;
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
var o = observeCursor(test, coll.find());
conn.methods({writeSomething: function () {
// stub write
coll.insert({foo: 'bar'});
}});
test.equal(coll.find({foo: 'bar'}).count(), 0);
// Call a method. We'll get the result but not data-done before reconnect.
var callbackOutput = [];
var onResultReceivedOutput = [];
conn.apply('writeSomething', [],
{onResultReceived: function (err, result) {
onResultReceivedOutput.push(result);
}},
function (err, result) {
callbackOutput.push(result);
});
// Stub write is visible.
test.equal(coll.find({foo: 'bar'}).count(), 1);
var stubWrittenId = coll.findOne({foo: 'bar'})._id;
o.expectCallbacks({added: 1});
// Callback not called.
test.equal(callbackOutput, []);
test.equal(onResultReceivedOutput, []);
// Method sent.
var methodId = testGotMessage(
test, stream, {msg: 'method', method: 'writeSomething',
params: [], id: '*', randomSeed: '*'}).id;
test.equal(stream.sent.length, 0);
// Get some data.
stream.receive({msg: 'added', collection: collName,
id: MongoID.idStringify(stubWrittenId), fields: {baz: 42}});
// It doesn't show up yet.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId), {_id: stubWrittenId, foo: 'bar'});
o.expectCallbacks();
// Get the result.
stream.receive({msg: 'result', id: methodId, result: 'bla'});
// Data unaffected.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId), {_id: stubWrittenId, foo: 'bar'});
o.expectCallbacks();
// Callback not called, but onResultReceived is.
test.equal(callbackOutput, []);
test.equal(onResultReceivedOutput, ['bla']);
// Reset stream. Method does NOT get resent, because its result is already
// in. Reconnect quiescence happens as soon as 'connected' is received because
// there are no pending methods or subs in need of revival.
stream.reset();
testGotMessage(test, stream, makeConnectMessage(SESSION_ID));
// Still holding out hope for session resumption, so nothing updated yet.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId), {_id: stubWrittenId, foo: 'bar'});
o.expectCallbacks();
test.equal(callbackOutput, []);
// Receive 'connected': time for reconnect quiescence! Data gets updated
// locally (ie, data is reset) and callback gets called.
stream.receive({msg: 'connected', session: SESSION_ID + 1});
test.equal(coll.find().count(), 0);
o.expectCallbacks({removed: 1});
test.equal(callbackOutput, ['bla']);
test.equal(onResultReceivedOutput, ['bla']);
stream.receive({msg: 'added', collection: collName,
id: MongoID.idStringify(stubWrittenId), fields: {baz: 42}});
test.equal(coll.findOne(stubWrittenId), {_id: stubWrittenId, baz: 42});
o.expectCallbacks({added: 1});
// Run method again. We're going to do the same thing this time, except we're
// also going to use an onReconnect to insert another method at reconnect
// time, which will delay reconnect quiescence.
conn.apply('writeSomething', [],
{onResultReceived: function (err, result) {
onResultReceivedOutput.push(result);
}},
function (err, result) {
callbackOutput.push(result);
});
// Stub write is visible.
test.equal(coll.find({foo: 'bar'}).count(), 1);
var stubWrittenId2 = coll.findOne({foo: 'bar'})._id;
o.expectCallbacks({added: 1});
// Callback not called.
test.equal(callbackOutput, ['bla']);
test.equal(onResultReceivedOutput, ['bla']);
// Method sent.
var methodId2 = testGotMessage(
test, stream, {msg: 'method', method: 'writeSomething',
params: [], id: '*', randomSeed: '*'}).id;
test.equal(stream.sent.length, 0);
// Get some data.
stream.receive({msg: 'added', collection: collName,
id: MongoID.idStringify(stubWrittenId2), fields: {baz: 42}});
// It doesn't show up yet.
test.equal(coll.find().count(), 2);
test.equal(coll.findOne(stubWrittenId2), {_id: stubWrittenId2, foo: 'bar'});
o.expectCallbacks();
// Get the result.
stream.receive({msg: 'result', id: methodId2, result: 'blab'});
// Data unaffected.
test.equal(coll.find().count(), 2);
test.equal(coll.findOne(stubWrittenId2), {_id: stubWrittenId2, foo: 'bar'});
o.expectCallbacks();
// Callback not called, but onResultReceived is.
test.equal(callbackOutput, ['bla']);
test.equal(onResultReceivedOutput, ['bla', 'blab']);
conn.onReconnect = function () {
conn.call('slowMethod', function (err, result) {
callbackOutput.push(result);
});
};
// Reset stream. Method does NOT get resent, because its result is already in,
// but slowMethod gets called via onReconnect. Reconnect quiescence is now
// blocking on slowMethod.
stream.reset();
testGotMessage(test, stream, makeConnectMessage(SESSION_ID + 1));
var slowMethodId = testGotMessage(
test, stream,
{msg: 'method', method: 'slowMethod', params: [], id: '*'}).id;
// Still holding out hope for session resumption, so nothing updated yet.
test.equal(coll.find().count(), 2);
test.equal(coll.findOne(stubWrittenId2), {_id: stubWrittenId2, foo: 'bar'});
o.expectCallbacks();
test.equal(callbackOutput, ['bla']);
// Receive 'connected'... but no reconnect quiescence yet due to slowMethod.
stream.receive({msg: 'connected', session: SESSION_ID + 2});
test.equal(coll.find().count(), 2);
test.equal(coll.findOne(stubWrittenId2), {_id: stubWrittenId2, foo: 'bar'});
o.expectCallbacks();
test.equal(callbackOutput, ['bla']);
// Receive data matching our stub. It doesn't take effect yet.
stream.receive({msg: 'added', collection: collName,
id: MongoID.idStringify(stubWrittenId2), fields: {foo: 'bar'}});
o.expectCallbacks();
// slowMethod is done writing, so we get full reconnect quiescence (but no
// slowMethod callback)... ie, a reset followed by applying the data we just
// got, as well as calling the callback from the method that half-finished
// before reset. The net effect is deleting doc 'stubWrittenId'.
stream.receive({msg: 'updated', methods: [slowMethodId]});
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId2), {_id: stubWrittenId2, foo: 'bar'});
o.expectCallbacks({removed: 1});
test.equal(callbackOutput, ['bla', 'blab']);
// slowMethod returns a value now.
stream.receive({msg: 'result', id: slowMethodId, result: 'slow'});
o.expectCallbacks();
test.equal(callbackOutput, ['bla', 'blab', 'slow']);
o.stop();
});
}
Tinytest.add("livedata stub - reconnect method which only got data", function (test) {
var stream = new StubStream;
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
var o = observeCursor(test, coll.find());
// Call a method. We'll get the data-done message but not the result before
// reconnect.
var callbackOutput = [];
var onResultReceivedOutput = [];
conn.apply('doLittle', [],
{onResultReceived: function (err, result) {
onResultReceivedOutput.push(result);
}},
function (err, result) {
callbackOutput.push(result);
});
// Callbacks not called.
test.equal(callbackOutput, []);
test.equal(onResultReceivedOutput, []);
// Method sent.
var methodId = testGotMessage(
test, stream, {msg: 'method', method: 'doLittle',
params: [], id: '*'}).id;
test.equal(stream.sent.length, 0);
// Get some data.
stream.receive({msg: 'added', collection: collName,
id: 'photo', fields: {baz: 42}});
// It shows up instantly because the stub didn't write anything.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne('photo'), {_id: 'photo', baz: 42});
o.expectCallbacks({added: 1});
// Get the data-done message.
stream.receive({msg: 'updated', methods: [methodId]});
// Data still here.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne('photo'), {_id: 'photo', baz: 42});
o.expectCallbacks();
// Method callback not called yet (no result yet).
test.equal(callbackOutput, []);
test.equal(onResultReceivedOutput, []);
// Reset stream. Method gets resent (with same ID), and blocks reconnect
// quiescence.
stream.reset();
testGotMessage(test, stream, makeConnectMessage(SESSION_ID));
testGotMessage(
test, stream, {msg: 'method', method: 'doLittle',
params: [], id: methodId});
// Still holding out hope for session resumption, so nothing updated yet.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne('photo'), {_id: 'photo', baz: 42});
o.expectCallbacks();
test.equal(callbackOutput, []);
test.equal(onResultReceivedOutput, []);
// Receive 'connected'. Still blocking on reconnect quiescence.
stream.receive({msg: 'connected', session: SESSION_ID + 1});
test.equal(coll.find().count(), 1);
test.equal(coll.findOne('photo'), {_id: 'photo', baz: 42});
o.expectCallbacks();
test.equal(callbackOutput, []);
test.equal(onResultReceivedOutput, []);
// Receive method result. onResultReceived is called but the main callback
// isn't (ie, we don't get confused by the fact that we got data-done the
// *FIRST* time through).
stream.receive({msg: 'result', id: methodId, result: 'res'});
test.equal(callbackOutput, []);
test.equal(onResultReceivedOutput, ['res']);
// Now we get data-done. Collection is reset and callback is called.
stream.receive({msg: 'updated', methods: [methodId]});
test.equal(coll.find().count(), 0);
o.expectCallbacks({removed: 1});
test.equal(callbackOutput, ['res']);
test.equal(onResultReceivedOutput, ['res']);
o.stop();
});
if (Meteor.isClient) {
Tinytest.add("livedata stub - multiple stubs same doc", function (test) {
var stream = new StubStream;
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
var o = observeCursor(test, coll.find());
conn.methods({
insertSomething: function () {
// stub write
coll.insert({foo: 'bar'});
},
updateIt: function (id) {
coll.update(id, {$set: {baz: 42}});
}
});
test.equal(coll.find().count(), 0);
// Call the insert method.
conn.call('insertSomething', _.identity);
// Stub write is visible.
test.equal(coll.find({foo: 'bar'}).count(), 1);
var stubWrittenId = coll.findOne({foo: 'bar'})._id;
o.expectCallbacks({added: 1});
// Method sent.
var insertMethodId = testGotMessage(
test, stream, {msg: 'method', method: 'insertSomething',
params: [], id: '*', randomSeed: '*'}).id;
test.equal(stream.sent.length, 0);
// Call update method.
conn.call('updateIt', stubWrittenId, _.identity);
// This stub write is visible too.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId),
{_id: stubWrittenId, foo: 'bar', baz: 42});
o.expectCallbacks({changed: 1});
// Method sent.
var updateMethodId = testGotMessage(
test, stream, {msg: 'method', method: 'updateIt',
params: [stubWrittenId], id: '*'}).id;
test.equal(stream.sent.length, 0);
// Get some data... slightly different than what we wrote.
stream.receive({msg: 'added', collection: collName,
id: MongoID.idStringify(stubWrittenId), fields: {foo: 'barb', other: 'field',
other2: 'bla'}});
// It doesn't show up yet.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId),
{_id: stubWrittenId, foo: 'bar', baz: 42});
o.expectCallbacks();
// And get the first method-done. Still no updates to minimongo: we can't
// quiesce the doc until the second method is done.
stream.receive({msg: 'updated', methods: [insertMethodId]});
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId),
{_id: stubWrittenId, foo: 'bar', baz: 42});
o.expectCallbacks();
// More data. Not quite what we wrote. Also ignored for now.
stream.receive({msg: 'changed', collection: collName,
id: MongoID.idStringify(stubWrittenId), fields: {baz: 43}, cleared: ['other']});
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId),
{_id: stubWrittenId, foo: 'bar', baz: 42});
o.expectCallbacks();
// Second data-ready. Now everything takes effect!
stream.receive({msg: 'updated', methods: [updateMethodId]});
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(stubWrittenId),
{_id: stubWrittenId, foo: 'barb', other2: 'bla',
baz: 43});
o.expectCallbacks({changed: 1});
o.stop();
});
}
if (Meteor.isClient) {
Tinytest.add("livedata stub - unsent methods don't block quiescence", function (test) {
// This test is for https://github.com/meteor/meteor/issues/555
var stream = new StubStream;
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
conn.methods({
insertSomething: function () {
// stub write
coll.insert({foo: 'bar'});
}
});
test.equal(coll.find().count(), 0);
// Call a random method (no-op)
conn.call('no-op', _.identity);
// Call a wait method
conn.apply('no-op', [], {wait: true}, _.identity);
// Call a method with a stub that writes.
conn.call('insertSomething', _.identity);
// Stub write is visible.
test.equal(coll.find({foo: 'bar'}).count(), 1);
var stubWrittenId = coll.findOne({foo: 'bar'})._id;
// first method sent
var firstMethodId = testGotMessage(
test, stream, {msg: 'method', method: 'no-op',
params: [], id: '*'}).id;
test.equal(stream.sent.length, 0);
// ack the first method
stream.receive({msg: 'updated', methods: [firstMethodId]});
stream.receive({msg: 'result', id: firstMethodId});
// Wait method sent.
var waitMethodId = testGotMessage(
test, stream, {msg: 'method', method: 'no-op',
params: [], id: '*'}).id;
test.equal(stream.sent.length, 0);
// ack the wait method
stream.receive({msg: 'updated', methods: [waitMethodId]});
stream.receive({msg: 'result', id: waitMethodId});
// insert method sent.
var insertMethodId = testGotMessage(
test, stream, {msg: 'method', method: 'insertSomething',
params: [], id: '*', randomSeed: '*'}).id;
test.equal(stream.sent.length, 0);
// ack the insert method
stream.receive({msg: 'updated', methods: [insertMethodId]});
stream.receive({msg: 'result', id: insertMethodId});
// simulation reverted.
test.equal(coll.find({foo: 'bar'}).count(), 0);
});
}
Tinytest.add("livedata stub - reactive resub", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var readiedSubs = {};
var markAllReady = function () {
// synthesize a "ready" message in response to any "sub"
// message with an id we haven't seen before
_.each(stream.sent, function (msg) {
msg = JSON.parse(msg);
if (msg.msg === 'sub' && ! _.has(readiedSubs, msg.id)) {
stream.receive({msg: 'ready', subs: [msg.id]});
readiedSubs[msg.id] = true;
}
});
};
var fooArg = new ReactiveVar('A');
var fooReady = 0;
var inner;
var outer = Tracker.autorun(function () {
inner = Tracker.autorun(function () {
conn.subscribe("foo-sub", fooArg.get(),
function () { fooReady++; });
});
});
markAllReady();
test.equal(fooReady, 1);
// Rerun the inner autorun with different subscription
// arguments. Detect the re-sub via onReady.
fooArg.set('B');
test.isTrue(inner.invalidated);
Tracker.flush();
test.isFalse(inner.invalidated);
markAllReady();
test.equal(fooReady, 2);
// Rerun inner again with same args; should be no re-sub.
inner.invalidate();
test.isTrue(inner.invalidated);
Tracker.flush();
test.isFalse(inner.invalidated);
markAllReady();
test.equal(fooReady, 2);
// Rerun outer! Should still be no re-sub even though
// the inner computation is stopped and a new one is
// started.
outer.invalidate();
test.isTrue(inner.invalidated);
Tracker.flush();
test.isFalse(inner.invalidated);
markAllReady();
test.equal(fooReady, 2);
// Change the subscription. Now we should get an onReady.
fooArg.set('C');
Tracker.flush();
markAllReady();
test.equal(fooReady, 3);
});
Tinytest.add("livedata connection - reactive userId", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
test.equal(conn.userId(), null);
conn.setUserId(1337);
test.equal(conn.userId(), 1337);
});
Tinytest.add("livedata connection - two wait methods", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
// setup method
conn.methods({do_something: function (x) {}});
var responses = [];
conn.apply('do_something', ['one!'], function() { responses.push('one'); });
var one_message = JSON.parse(stream.sent.shift());
test.equal(one_message.params, ['one!']);
conn.apply('do_something', ['two!'], {wait: true}, function() {
responses.push('two');
});
// 'two!' isn't sent yet, because it's a wait method.
test.equal(stream.sent.length, 0);
conn.apply('do_something', ['three!'], function() {
responses.push('three');
});
conn.apply('do_something', ['four!'], function() {
responses.push('four');
});
conn.apply('do_something', ['five!'], {wait: true}, function() {
responses.push('five');
});
conn.apply('do_something', ['six!'], function() { responses.push('six'); });
// Verify that we did not send any more methods since we are still waiting on
// 'one!'.
test.equal(stream.sent.length, 0);
// Receive some data. "one" is not a wait method and there are no stubs, so it
// gets applied immediately.
test.equal(coll.find().count(), 0);
stream.receive({msg: 'added', collection: collName,
id: 'foo', fields: {x: 1}});
test.equal(coll.find().count(), 1);
test.equal(coll.findOne('foo'), {_id: 'foo', x: 1});
// Let "one!" finish. Both messages are required to fire the callback.
stream.receive({msg: 'result', id: one_message.id});
test.equal(responses, []);
stream.receive({msg: 'updated', methods: [one_message.id]});
test.equal(responses, ['one']);
// Now we've send out "two!".
var two_message = JSON.parse(stream.sent.shift());
test.equal(two_message.params, ['two!']);
// But still haven't sent "three!".
test.equal(stream.sent.length, 0);
// Receive more data. "two" is a wait method, so the data doesn't get applied
// yet.
stream.receive({msg: 'changed', collection: collName,
id: 'foo', fields: {y: 3}});
test.equal(coll.find().count(), 1);
test.equal(coll.findOne('foo'), {_id: 'foo', x: 1});
// Let "two!" finish, with its end messages in the opposite order to "one!".
stream.receive({msg: 'updated', methods: [two_message.id]});
test.equal(responses, ['one']);
test.equal(stream.sent.length, 0);
// data-done message is enough to allow data to be written.
test.equal(coll.find().count(), 1);
test.equal(coll.findOne('foo'), {_id: 'foo', x: 1, y: 3});
stream.receive({msg: 'result', id: two_message.id});
test.equal(responses, ['one', 'two']);
// Verify that we just sent "three!" and "four!" now that we got
// responses for "one!" and "two!"
test.equal(stream.sent.length, 2);
var three_message = JSON.parse(stream.sent.shift());
test.equal(three_message.params, ['three!']);
var four_message = JSON.parse(stream.sent.shift());
test.equal(four_message.params, ['four!']);
// Out of order response is OK for non-wait methods.
stream.receive({msg: 'result', id: three_message.id});
stream.receive({msg: 'result', id: four_message.id});
stream.receive({msg: 'updated', methods: [four_message.id]});
test.equal(responses, ['one', 'two', 'four']);
test.equal(stream.sent.length, 0);
// Let three finish too.
stream.receive({msg: 'updated', methods: [three_message.id]});
test.equal(responses, ['one', 'two', 'four', 'three']);
// Verify that we just sent "five!" (the next wait method).
test.equal(stream.sent.length, 1);
var five_message = JSON.parse(stream.sent.shift());
test.equal(five_message.params, ['five!']);
test.equal(responses, ['one', 'two', 'four', 'three']);
// Let five finish.
stream.receive({msg: 'result', id: five_message.id});
stream.receive({msg: 'updated', methods: [five_message.id]});
test.equal(responses, ['one', 'two', 'four', 'three', 'five']);
var six_message = JSON.parse(stream.sent.shift());
test.equal(six_message.params, ['six!']);
});
Tinytest.add("livedata connection - onReconnect prepends messages correctly with a wait method", function(test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
// setup method
conn.methods({do_something: function (x) {}});
conn.onReconnect = function() {
conn.apply('do_something', ['reconnect zero'], _.identity);
conn.apply('do_something', ['reconnect one'], _.identity);
conn.apply('do_something', ['reconnect two'], {wait: true}, _.identity);
conn.apply('do_something', ['reconnect three'], _.identity);
};
conn.apply('do_something', ['one'], _.identity);
conn.apply('do_something', ['two'], {wait: true}, _.identity);
conn.apply('do_something', ['three'], _.identity);
// reconnect
stream.sent = [];
stream.reset();
testGotMessage(test, stream, makeConnectMessage(conn._lastSessionId));
// Test that we sent what we expect to send, and we're blocked on
// what we expect to be blocked. The subsequent logic to correctly
// read the wait flag is tested separately.
test.equal(_.map(stream.sent, function(msg) {
return JSON.parse(msg).params[0];
}), ['reconnect zero', 'reconnect one']);
// white-box test:
test.equal(_.map(conn._outstandingMethodBlocks, function (block) {
return [block.wait, _.map(block.methods, function (method) {
return method._message.params[0];
})];
}), [
[false, ['reconnect zero', 'reconnect one']],
[true, ['reconnect two']],
[false, ['reconnect three', 'one']],
[true, ['two']],
[false, ['three']]
]);
});
Tinytest.add("livedata connection - ping without id", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
stream.receive({msg: 'ping'});
testGotMessage(test, stream, {msg: 'pong'});
});
Tinytest.add("livedata connection - ping with id", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var id = Random.id();
stream.receive({msg: 'ping', id: id});
testGotMessage(test, stream, {msg: 'pong', id: id});
});
_.each(LivedataTest.SUPPORTED_DDP_VERSIONS, function (version) {
Tinytest.addAsync("livedata connection - ping from " + version,
function (test, onComplete) {
var connection = new LivedataTest.Connection(getSelfConnectionUrl(), {
reloadWithOutstanding: true,
supportedDDPVersions: [version],
onDDPVersionNegotiationFailure: function () { test.fail(); onComplete(); },
onConnected: function () {
test.equal(connection._version, version);
// It's a little naughty to access _stream and _send, but it works...
connection._stream.on('message', function (json) {
var msg = JSON.parse(json);
var done = false;
if (msg.msg === 'pong') {
test.notEqual(version, "pre1");
done = true;
} else if (msg.msg === 'error') {
// Version pre1 does not play ping-pong
test.equal(version, "pre1");
done = true;
} else {
Meteor._debug("Got unexpected message: " + json);
}
if (done) {
connection._stream.disconnect({_permanent: true});
onComplete();
}
});
connection._send({msg: 'ping'});
}
});
});
});
var getSelfConnectionUrl = function () {
if (Meteor.isClient) {
var ddpUrl = Meteor._relativeToSiteRootUrl("/");
if (typeof __meteor_runtime_config__ !== "undefined") {
if (__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL)
ddpUrl = __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL;
}
return ddpUrl;
} else {
return Meteor.absoluteUrl();
}
};
if (Meteor.isServer) {
Meteor.methods({
reverse: function (arg) {
// Return something notably different from reverse.meteor.com.
return arg.split("").reverse().join("") + " LOCAL";
}
});
}
testAsyncMulti("livedata connection - reconnect to a different server", [
function (test, expect) {
var self = this;
self.conn = DDP.connect("reverse.meteor.com");
pollUntil(expect, function () {
return self.conn.status().connected;
}, 5000, 100, true); // poll until connected, but don't fail if we don't connect
},
function (test, expect) {
var self = this;
self.doTest = self.conn.status().connected;
if (self.doTest) {
self.conn.call("reverse", "foo", expect(function (err, res) {
test.equal(res, "oof");
}));
}
},
function (test, expect) {
var self = this;
if (self.doTest) {
self.conn.reconnect({url: getSelfConnectionUrl()});
self.conn.call("reverse", "bar", expect(function (err, res) {
test.equal(res, "rab LOCAL");
}));
}
}
]);
Tinytest.addAsync("livedata connection - version negotiation requires renegotiating",
function (test, onComplete) {
var connection = new LivedataTest.Connection(getSelfConnectionUrl(), {
reloadWithOutstanding: true,
supportedDDPVersions: ["garbled", LivedataTest.SUPPORTED_DDP_VERSIONS[0]],
onDDPVersionNegotiationFailure: function () { test.fail(); onComplete(); },
onConnected: function () {
test.equal(connection._version, LivedataTest.SUPPORTED_DDP_VERSIONS[0]);
connection._stream.disconnect({_permanent: true});
onComplete();
}
});
});
Tinytest.addAsync("livedata connection - version negotiation error",
function (test, onComplete) {
var connection = new LivedataTest.Connection(getSelfConnectionUrl(), {
reloadWithOutstanding: true,
supportedDDPVersions: ["garbled", "more garbled"],
onDDPVersionNegotiationFailure: function () {
test.equal(connection.status().status, "failed");
test.matches(connection.status().reason, /DDP version negotiation failed/);
test.isFalse(connection.status().connected);
onComplete();
},
onConnected: function () {
test.fail();
onComplete();
}
});
});
Tinytest.add("livedata connection - onReconnect prepends messages correctly without a wait method", function(test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
// setup method
conn.methods({do_something: function (x) {}});
conn.onReconnect = function() {
conn.apply('do_something', ['reconnect one'], _.identity);
conn.apply('do_something', ['reconnect two'], _.identity);
conn.apply('do_something', ['reconnect three'], _.identity);
};
conn.apply('do_something', ['one'], _.identity);
conn.apply('do_something', ['two'], {wait: true}, _.identity);
conn.apply('do_something', ['three'], {wait: true}, _.identity);
conn.apply('do_something', ['four'], _.identity);
// reconnect
stream.sent = [];
stream.reset();
testGotMessage(test, stream, makeConnectMessage(conn._lastSessionId));
// Test that we sent what we expect to send, and we're blocked on
// what we expect to be blocked. The subsequent logic to correctly
// read the wait flag is tested separately.
test.equal(_.map(stream.sent, function(msg) {
return JSON.parse(msg).params[0];
}), ['reconnect one', 'reconnect two', 'reconnect three', 'one']);
// white-box test:
test.equal(_.map(conn._outstandingMethodBlocks, function (block) {
return [block.wait, _.map(block.methods, function (method) {
return method._message.params[0];
})];
}), [
[false, ['reconnect one', 'reconnect two', 'reconnect three', 'one']],
[true, ['two']],
[true, ['three']],
[false, ['four']]
]);
});
Tinytest.add("livedata connection - onReconnect with sent messages", function(test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
// setup method
conn.methods({do_something: function (x) {}});
conn.onReconnect = function() {
conn.apply('do_something', ['login'], {wait: true}, _.identity);
};
conn.apply('do_something', ['one'], _.identity);
// initial connect
stream.sent = [];
stream.reset();
testGotMessage(
test, stream, makeConnectMessage(conn._lastSessionId));
// Test that we sent just the login message.
var loginId = testGotMessage(
test, stream, {msg: 'method', method: 'do_something',
params: ['login'], id: '*'}).id;
// we connect.
stream.receive({msg: 'connected', session: Random.id()});
test.length(stream.sent, 0);
// login got result (but not yet data)
stream.receive({msg: 'result', id: loginId, result: 'foo'});
test.length(stream.sent, 0);
// login got data. now we send next method.
stream.receive({msg: 'updated', methods: [loginId]});
testGotMessage(
test, stream, {msg: 'method', method: 'do_something',
params: ['one'], id: '*'}).id;
});
Tinytest.add("livedata stub - reconnect double wait method", function (test) {
var stream = new StubStream;
var conn = newConnection(stream);
startAndConnect(test, stream);
var output = [];
conn.onReconnect = function () {
conn.apply('reconnectMethod', [], {wait: true}, function (err, result) {
output.push('reconnect');
});
};
conn.apply('halfwayMethod', [], {wait: true}, function (err, result) {
output.push('halfway');
});
test.equal(output, []);
// Method sent.
var halfwayId = testGotMessage(
test, stream, {msg: 'method', method: 'halfwayMethod',
params: [], id: '*'}).id;
test.equal(stream.sent.length, 0);
// Get the result. This means it will not be resent.
stream.receive({msg: 'result', id: halfwayId, result: 'bla'});
// Callback not called.
test.equal(output, []);
// Reset stream. halfwayMethod does NOT get resent, but reconnectMethod does!
// Reconnect quiescence happens when reconnectMethod is done.
stream.reset();
testGotMessage(test, stream, makeConnectMessage(SESSION_ID));
var reconnectId = testGotMessage(
test, stream, {msg: 'method', method: 'reconnectMethod',
params: [], id: '*'}).id;
test.length(stream.sent, 0);
// Still holding out hope for session resumption, so no callbacks yet.
test.equal(output, []);
// Receive 'connected', but reconnect quiescence is blocking on
// reconnectMethod.
stream.receive({msg: 'connected', session: SESSION_ID + 1});
test.equal(output, []);
// Data-done for reconnectMethod. This gets us to reconnect quiescence, so
// halfwayMethod's callback fires. reconnectMethod's is still waiting on its
// result.
stream.receive({msg: 'updated', methods: [reconnectId]});
test.equal(output.shift(), 'halfway');
test.equal(output, []);
// Get result of reconnectMethod. Its callback fires.
stream.receive({msg: 'result', id: reconnectId, result: 'foo'});
test.equal(output.shift(), 'reconnect');
test.equal(output, []);
// Call another method. It should be delivered immediately. This is a
// regression test for a case where it never got delivered because there was
// an empty block in _outstandingMethodBlocks blocking it from being sent.
conn.call('lastMethod', _.identity);
testGotMessage(test, stream,
{msg: 'method', method: 'lastMethod', params: [], id: '*'});
});
Tinytest.add("livedata stub - subscribe errors", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
// subscribe
var onReadyFired = false;
var subErrorInStopped = null;
var subErrorInError = null;
conn.subscribe('unknownSub', {
onReady: function () {
onReadyFired = true;
},
// We now have two ways to get the error from a subscription:
// 1. onStop, which is called no matter what when the subscription is
// stopped (a lifecycle callback)
// 2. onError, which is deprecated and is called only if there is an
// error
onStop: function (error) {
subErrorInStopped = error;
},
onError: function (error) {
subErrorInError = error;
}
});
test.isFalse(onReadyFired);
test.equal(subErrorInStopped, null);
// XXX COMPAT WITH 1.0.3.1 #errorCallback
test.equal(subErrorInError, null);
var subMessage = JSON.parse(stream.sent.shift());
test.equal(subMessage, {msg: 'sub', name: 'unknownSub', params: [],
id: subMessage.id});
// Reject the sub.
stream.receive({msg: 'nosub', id: subMessage.id,
error: new Meteor.Error(404, "Subscription not found")});
test.isFalse(onReadyFired);
// Check the error passed to the stopped callback was correct
test.instanceOf(subErrorInStopped, Meteor.Error);
test.equal(subErrorInStopped.error, 404);
test.equal(subErrorInStopped.reason, "Subscription not found");
// Check the error passed to the error callback was correct
// XXX COMPAT WITH 1.0.3.1 #errorCallback
test.instanceOf(subErrorInError, Meteor.Error);
test.equal(subErrorInError.error, 404);
test.equal(subErrorInError.reason, "Subscription not found");
// stream reset: reconnect!
stream.reset();
// We send a connect.
testGotMessage(test, stream, makeConnectMessage(SESSION_ID));
// We should NOT re-sub to the sub, because we processed the error.
test.length(stream.sent, 0);
test.isFalse(onReadyFired);
});
Tinytest.add("livedata stub - subscribe stop", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
// subscribe
var onReadyFired = false;
var onStopFired = false;
var subErrorInStopped = null;
var sub = conn.subscribe('my_data', {
onStop: function (error) {
onStopFired = true;
subErrorInStopped = error;
}
});
test.equal(subErrorInStopped, null);
sub.stop();
test.isTrue(onStopFired);
test.equal(subErrorInStopped, undefined);
});
if (Meteor.isClient) {
Tinytest.add("livedata stub - stubs before connected", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
// Start and send "connect", but DON'T get 'connected' quite yet.
stream.reset(); // initial connection start.
testGotMessage(test, stream, makeConnectMessage());
test.length(stream.sent, 0);
// Insert a document. The stub updates "conn" directly.
coll.insert({_id: "foo", bar: 42}, _.identity);
test.equal(coll.find().count(), 1);
test.equal(coll.findOne(), {_id: "foo", bar: 42});
// It also sends the method message.
var methodMessage = JSON.parse(stream.sent.shift());
test.isUndefined(methodMessage.randomSeed);
test.equal(methodMessage, {msg: 'method', method: '/' + collName + '/insert',
params: [{_id: "foo", bar: 42}],
id: methodMessage.id});
test.length(stream.sent, 0);
// Now receive a connected message. This should not clear the
// _documentsWrittenByStub state!
stream.receive({msg: 'connected', session: SESSION_ID});
test.length(stream.sent, 0);
test.equal(coll.find().count(), 1);
// Now receive the "updated" message for the method. This should revert the
// insert.
stream.receive({msg: 'updated', methods: [methodMessage.id]});
test.length(stream.sent, 0);
test.equal(coll.find().count(), 0);
});
}
if (Meteor.isClient) {
Tinytest.add("livedata stub - method call between reset and quiescence", function (test) {
var stream = new StubStream();
var conn = newConnection(stream);
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
conn.methods({
update_value: function () {
coll.update('aaa', {value: 222});
}
});
// Set up test subscription.
var sub = conn.subscribe('test_data');
var subMessage = JSON.parse(stream.sent.shift());
test.equal(subMessage, {msg: 'sub', name: 'test_data',
params: [], id:subMessage.id});
test.length(stream.sent, 0);
var subDocMessage = {msg: 'added', collection: collName,
id: 'aaa', fields: {value: 111}};
var subReadyMessage = {msg: 'ready', 'subs': [subMessage.id]};
stream.receive(subDocMessage);
stream.receive(subReadyMessage);
test.isTrue(coll.findOne('aaa').value == 111);
// Initiate reconnect.
stream.reset();
testGotMessage(test, stream, makeConnectMessage(SESSION_ID));
testGotMessage(test, stream, subMessage);
stream.receive({msg: 'connected', session: SESSION_ID + 1});
// Now in reconnect, can still see the document.
test.isTrue(coll.findOne('aaa').value == 111);
conn.call('update_value');
// Observe the stub-written value.
test.isTrue(coll.findOne('aaa').value == 222);
var methodMessage = JSON.parse(stream.sent.shift());
test.equal(methodMessage, {msg: 'method', method: 'update_value',
params: [], id:methodMessage.id});
test.length(stream.sent, 0);
stream.receive(subDocMessage);
stream.receive(subReadyMessage);
// By this point quiescence is reached and stores have been reset.
// The stub-written value is still there.
test.isTrue(coll.findOne('aaa').value == 222);
stream.receive({msg: 'changed', collection: collName,
id: 'aaa', fields: {value: 333}});
stream.receive({msg: 'updated', 'methods': [methodMessage.id]});
stream.receive({msg: 'result', id:methodMessage.id, result:null});
// Server wrote a different value, make sure it's visible now.
test.isTrue(coll.findOne('aaa').value == 333);
});
Tinytest.add("livedata stub - buffering and methods interaction", function (test) {
var stream = new StubStream();
var conn = newConnection(stream, {
// A very high values so that all messages are effectively buffered.
bufferedWritesInterval: 10000,
bufferedWritesMaxAge: 10000
});
startAndConnect(test, stream);
var collName = Random.id();
var coll = new Mongo.Collection(collName, {connection: conn});
conn.methods({
update_value: function () {
const value = coll.findOne('aaa').subscription;
// Method should have access to the latest value of the collection.
coll.update('aaa', {$set: {method: value + 110}});
}
});
// Set up test subscription.
var sub = conn.subscribe('test_data');
var subMessage = JSON.parse(stream.sent.shift());
test.equal(subMessage, {msg: 'sub', name: 'test_data',
params: [], id:subMessage.id});
test.length(stream.sent, 0);
var subDocMessage = {msg: 'added', collection: collName,
id: 'aaa', fields: {subscription: 111}};
var subReadyMessage = {msg: 'ready', 'subs': [subMessage.id]};
stream.receive(subDocMessage);
stream.receive(subReadyMessage);
test.equal(coll.findOne('aaa').subscription, 111);
var subDocChangeMessage = {msg: 'changed', collection: collName,
id: 'aaa', fields: {subscription: 112}};
stream.receive(subDocChangeMessage);
// Still 111 because buffer has not been flushed.
test.equal(coll.findOne('aaa').subscription, 111);
// Call updates the stub.
conn.call('update_value');
// Observe the stub-written value.
test.equal(coll.findOne('aaa').method, 222);
// subscription field is updated to the latest value
// because of the method call.
test.equal(coll.findOne('aaa').subscription, 112);
var methodMessage = JSON.parse(stream.sent.shift());
test.equal(methodMessage, {msg: 'method', method: 'update_value',
params: [], id:methodMessage.id});
test.length(stream.sent, 0);
// "Server-side" change from the method arrives and method returns.
// With potentially fixed value for method field, if stub didn't
// use 112 as the subscription field value.
stream.receive({msg: 'changed', collection: collName,
id: 'aaa', fields: {method: 222}});
stream.receive({msg: 'updated', 'methods': [methodMessage.id]});
stream.receive({msg: 'result', id:methodMessage.id, result:null});
test.equal(coll.findOne('aaa').method, 222);
test.equal(coll.findOne('aaa').subscription, 112);
// Buffer should already be flushed because of a non-update message.
// And after a flush we really want subscription field to be 112.
conn._flushBufferedWrites();
test.equal(coll.findOne('aaa').method, 222);
test.equal(coll.findOne('aaa').subscription, 112);
});
}
// XXX also test:
// - reconnect, with session resume.
// - restart on update flag
// - on_update event
// - reloading when the app changes, including session migration
| mit |
tphx/StreamChatSharp | StreamChatSharp/StreamChatSharp/OutgoingMessageQueue.cs | 4955 | using System;
using System.Collections.Concurrent;
using System.Timers;
namespace Tphx.StreamChatSharp
{
/// <summary>
/// Queues messages that are destined for the chat and provides flood control.
/// </summary>
class OutgoingMessageQueue : IDisposable
{
/// <summary>
/// Triggered whenever a message is ready to be sent to the chat.
/// </summary>
public event EventHandler<ChatMessageEventArgs> MessageReady;
private ConcurrentQueue<ChatMessage> highPriorityMessages = new ConcurrentQueue<ChatMessage>();
private ConcurrentQueue<ChatMessage> normalPriorityMessages = new ConcurrentQueue<ChatMessage>();
private Timer sendMessageTimer = new Timer(1600); // 1.6 seconds.
private bool stoppedManually = false;
private bool messageSentLastCycle = false;
private bool disposed = false;
public OutgoingMessageQueue()
{
sendMessageTimer.Elapsed += OnSendMessageTimerElapsed;
sendMessageTimer.Start();
}
/// <summary>
/// Disposes of everything.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Queues an outgoing ChatMessage to be sent to the chat and starts the send timer unless the queue has been
/// stopped manually via the Stop method.
/// </summary>
/// <param name="message">The chat message to be queued.</param>
/// <param name="isHighPriorityMessage">Whether or not the message is a high priority message.</param>
public void AddMessage(ChatMessage message, bool isHighPriorityMessage)
{
// If the send message timer isn't running (no message has been sent in since the last interval) we can
// send the message instantly.
if (!messageSentLastCycle)
{
SendMessage(message);
messageSentLastCycle = true;
}
else
{
if (isHighPriorityMessage)
{
highPriorityMessages.Enqueue(message);
}
else
{
normalPriorityMessages.Enqueue(message);
}
}
}
/// <summary>
/// The amount of time (in milliseconds) to wait between sent messages. By default this is set to 1.6 seconds
/// between messages (20 messages in 32 seconds).
/// </summary>
public double MessageSendInterval
{
get
{
return sendMessageTimer.Interval;
}
set
{
sendMessageTimer.Interval = value;
}
}
/// <summary>
/// Manually starts the outgoing message queue.
/// </summary>
public void Start()
{
sendMessageTimer.Start();
stoppedManually = false;
}
/// <summary>
/// Manually stops the outgoing message queue. Once the queue has been stopped manually, it can only be
/// restarted manually.
/// </summary>
public void Stop()
{
sendMessageTimer.Stop();
stoppedManually = true;
}
/// <summary>
/// Whether or not the outgoing message queue was stopped manually.
/// </summary>
public bool StoppedManually
{
get
{
return stoppedManually;
}
}
/// <summary>
/// Clears all of the messages in queue.
/// </summary>
public void ClearMessages()
{
highPriorityMessages = new ConcurrentQueue<ChatMessage>();
normalPriorityMessages = new ConcurrentQueue<ChatMessage>();
}
private void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
sendMessageTimer.Dispose();
}
disposed = true;
}
}
private void OnSendMessageTimerElapsed(object sender, ElapsedEventArgs e)
{
ChatMessage message;
if(highPriorityMessages.TryDequeue(out message))
{
SendMessage(message);
messageSentLastCycle = true;
}
else if(normalPriorityMessages.TryDequeue(out message))
{
SendMessage(message);
messageSentLastCycle = true;
}
else
{
messageSentLastCycle = false;
}
}
private void SendMessage(ChatMessage message)
{
if(MessageReady != null)
{
MessageReady(this, new ChatMessageEventArgs(message));
}
}
}
}
| mit |
lechimp-p/php-formlets | src/Internal/Form.php | 5023 | <?php
/******************************************************************************
* An implementation of the "Formlets"-abstraction in PHP.
* Copyright (c) 2014, 2015 Richard Klees <richard.klees@rwth-aachen.de>
*
* This software is licensed under The MIT License. You should have received
* a copy of the along with the code.
*/
namespace Lechimp\Formlets\Internal;
use Lechimp\Formlets\IForm;
use Lechimp\Formlets\IFormlet;
use Lechimp\Formlets\Internal\Checking as C;
use Lechimp\Formlets\Internal\Values as V;
use Lechimp\Formlets\Internal\HTML as H;
use Lechimp\Formlets\Internal\NameSource;
class Form implements IForm {
protected $_builder;// Builder
protected $_collector;// Collector
protected $_id; // string
protected $_input; // [string => mixed] | null
protected $_result; // mixed | null
public function _result() {
return $this->_result;
}
public function __construct($id, $action, $attrs, IFormlet $formlet) {
if (!preg_match("#[a-zA-Z][a-zA-Z0-9_]+#", $id)) {
throw new Exception("Form::__construct: '$id' can not be used as "
."id. Only use numbers and digits.");
}
C::guardIsFormlet($formlet);
C::guardIsString($id);
C::guardIsString($action);
$attrs = Value::defaultTo($attrs, array());
C::guardEachAndKeys($attrs, "C::guardIsString", "C::guardIsString");
$this->_id = $id;
$this->_input = null;
$this->_result = null;
$attrs["method"] = "post";
$attrs["action"] = $action;
$formlet = $formlet
->mapHTML(V::fn(function($dict, $html) use ($attrs) {
return H::tag("form", $attrs, $html);
}));
$name_source = NameSource::instantiate($this->_id);
$repr = $formlet->instantiate($name_source);
$this->_builder = $repr["builder"];
$this->_collector = $repr["collector"];
}
/**
* Initializes the form. If no input array is given uses $_POST.
* Return $this.
*
+ @param [string => mixed] | null $input
* @return Form
*/
public function init($input = null) {
if ($input === null) {
$input = $_POST;
}
$this->_input = $input;
$this->_result = null;
}
/**
* Check whether form was submitted.
*
* @return bool
*/
public function wasSubmitted() {
if ($this->_input === null) {
return false;
}
if ($this->_result !== null) {
return true;
}
try {
$this->_result = $this->_collector->collect($this->_input);
return true;
}
catch (MissingInputError $e) {
return false;
}
}
/**
* Check weather form was successfully evaluated.
*
* @return bool
*/
public function wasSuccessfull() {
if (!$this->wasSubmitted()) {
return false;
}
assert('$this->_result !== null');
return !$this->_result->isError();
}
/**
* Get a HTML-string of the form in its current state.
*
* @return string
*/
public function html() {
if (!$this->wasSubmitted()) {
return $this->_builder->build()->render();
}
$render_dict = new RenderDict($this->_input, $this->_result);
return $this->_builder->buildWithDict($render_dict)->render();
}
/**
* Get the result of the form.
* Throws if form was not submitted and successfully evaluated.
*
* @return mixed
* @throws Exception
*/
public function result() {
if ( !$this->wasSubmitted()
|| !$this->wasSuccessfull()) {
throw new Exception("Form::result: Form was not submitted successfully.");
}
if ( $this->_result->isApplicable()) {
throw new Exception("Form::result: Result is no value but a function.");
}
assert('$this->_result !== null');
return $this->_result->get();
}
/**
* Get an error as string.
* Throws if form was submitted successfully.
*
* @return string
* @throws Exception
*/
public function error() {
if ( $this->wasSuccessfull()) {
throw new Exception("Form::error: Form was submitted successfully.");
}
assert('$this->_result !== null');
return $this->_result->error();
}
}
/**
* Get a new form that processes a formlet. $id must be a unique id throughout
* the program. $action is the action attribute for the form tag. $attrs are
* more attributes for the form tag.
*
* @param string $id
* @param string $action
* @param [string => string] | null $attrs
* @return Form
*/
function _form($id, $action, IFormlet $formlet, $attrs = null) {
return new Form($id, $action, $attrs, $formlet);
}
| mit |
jaryway/api | Api.Lanxin/Logging/Null/NullLogger.cs | 1316 | using log4net;
using System;
namespace Api.Lanxin.Logging.Null
{
/// <summary>
///
/// </summary>
public class NullLogger : ILogger
{
//private ILog _logger;
/// <summary>
///
/// </summary>
internal NullLogger()
{
//_logger = log;
}
/// <summary>
///
/// </summary>
/// <param name="level"></param>
/// <returns></returns>
public bool IsEnabled(LogLevel level)
{
return false;
}
/// <summary>
///
/// </summary>
/// <param name="level"></param>
/// <param name="message"></param>
public void Log(LogLevel level, object message)
{ }
/// <summary>
///
/// </summary>
/// <param name="level"></param>
/// <param name="exception"></param>
/// <param name="message"></param>
public void Log(LogLevel level, Exception exception, object message)
{ }
/// <summary>
///
/// </summary>
/// <param name="level"></param>
/// <param name="format"></param>
/// <param name="args"></param>
public void Log(LogLevel level, string format, params object[] args)
{ }
}
}
| mit |
GluuFederation/oxAsimba | selector/src/main/java/org/gluu/authentication/remote/saml2/selector/ApplicationSelector.java | 2470 | package org.gluu.authentication.remote.saml2.selector;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Element;
import com.alfaariss.oa.OAException;
import com.alfaariss.oa.api.configuration.IConfigurationManager;
import com.alfaariss.oa.api.session.ISession;
import com.alfaariss.oa.authentication.remote.saml2.Warnings;
import com.alfaariss.oa.authentication.remote.saml2.selector.DefaultSelector;
import com.alfaariss.oa.util.saml2.idp.SAML2IDP;
/**
* Asimba selector based on mapping from asimba-selector.xml.
* It do automatic mapping by entityId from request to organizationId
*
* @author Yuriy Movchan Date: 16/05/2014
*/
public class ApplicationSelector extends DefaultSelector {
private Log log;
private ApplicationSelectorConfiguration applicationSelectorConfiguration;
private Map<String, String> applicationMapping;
public ApplicationSelector() {
this.log = LogFactory.getLog(ApplicationSelector.class);
this.applicationSelectorConfiguration = new ApplicationSelectorConfiguration();
}
public void start(IConfigurationManager oConfigurationManager, Element eConfig) throws OAException {
super.start(oConfigurationManager, eConfig);
loadApplicationMapping();
}
private void loadApplicationMapping() {
this.applicationSelectorConfiguration.loadConfiguration();
this.applicationMapping = this.applicationSelectorConfiguration.getApplicationMapping();
}
@Override
public SAML2IDP resolve(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession,
List<SAML2IDP> listOrganizations, String sMethodName, List<Warnings> oWarnings) throws OAException {
String requestorId = oSession.getRequestorId();
log.debug("Attempting to find mapping by requestorId: " + requestorId);
String organizationId = this.applicationMapping.get(requestorId);
if (organizationId != null) {
log.debug("Found organizationId: " + organizationId + " by requestorId: " + requestorId);
for (SAML2IDP org : listOrganizations) {
if (org.getID().equals(organizationId)) {
return org;
}
}
} else {
log.debug("Can't find mapping by requestorId: " + requestorId);
}
SAML2IDP result = super.resolve(oRequest, oResponse, oSession, listOrganizations, sMethodName, oWarnings);
return result;
}
}
| mit |
mcleanra/sp-rest-proxy | src/routers/restGet.ts | 2323 | import { ProxyUtils } from '../utils';
import { IProxyContext, IProxySettings } from '../interfaces';
import { ISPRequest } from 'sp-request';
import { Request, Response, NextFunction } from 'express';
export class RestGetRouter {
private spr: ISPRequest;
private ctx: IProxyContext;
private settings: IProxySettings;
private util: ProxyUtils;
constructor (context: IProxyContext, settings: IProxySettings) {
this.ctx = context;
this.settings = settings;
this.util = new ProxyUtils(this.ctx);
}
public router = (req: Request, res: Response, next?: NextFunction) => {
let endpointUrl = this.util.buildEndpointUrl(req.originalUrl);
this.spr = this.util.getCachedRequest(this.spr);
if (!this.settings.silentMode) {
console.log('\nGET: ' + endpointUrl);
}
let requestHeadersPass: any = {};
let ignoreHeaders = [
'host', 'referer', 'origin',
'if-none-match', 'connection', 'cache-control', 'user-agent',
'accept-encoding', 'x-requested-with', 'accept-language'
];
Object.keys(req.headers).forEach((prop: string) => {
if (ignoreHeaders.indexOf(prop.toLowerCase()) === -1) {
if (prop.toLowerCase() === 'accept' && req.headers[prop] !== '*/*') {
requestHeadersPass.Accept = req.headers[prop];
} else if (prop.toLowerCase() === 'content-type') {
requestHeadersPass['Content-Type'] = req.headers[prop];
} else {
requestHeadersPass[prop] = req.headers[prop];
}
}
});
if (this.settings.debugOutput) {
console.log('\nHeaders:');
console.log(JSON.stringify(req.headers, null, 2));
}
this.spr.get(endpointUrl, {
headers: requestHeadersPass,
agent: this.util.isUrlHttps(endpointUrl) ? this.settings.agent : undefined
})
.then((response: any) => {
if (this.settings.debugOutput) {
console.log(response.statusCode, response.body);
}
res.status(response.statusCode);
res.json(response.body);
})
.catch((err: any) => {
res.status(err.statusCode >= 100 && err.statusCode < 600 ? err.statusCode : 500);
if (err.response && err.response.body) {
res.json(err.response.body);
} else {
res.send(err.message);
}
});
}
}
| mit |
jeremythuff/WebGL-Planets-Client | src/engine/utils/assets/AjaxLoader.js | 1664 | import { Service } from "context/Service";
import { Deferred } from "engine/extensions/Deferred";
export class AjaxLoader {
constructor(headers) {
this.headers = typeof headers !== undefined ? headers: {};
}
GET(url) {
let deferred = new Deferred();
_makeXhrReq("GET", url, null, deferred);
return deferred.promise;
}
POST(url, data) {
let deferred = new Deferred();
_makeXhrReq("POST", url, data, deferred);
return deferred.promise;
}
PUT(url, data) {
let deferred = new Deferred();
_makeXhrReq("PUT", url, data, deferred);
return deferred.promise;
}
DELETE(url, data) {
let deferred = new Deferred();
_makeXhrReq("DELETE", url, data, deferred);
return deferred.promise;
}
}
let _makeXhrReq = function(method, url, data, deferred) {
let client = new XMLHttpRequest();
let uri = url;
if (data && (method === 'POST' || method === 'PUT' || method === 'DELETE')) {
uri += '?';
var argcount = 0;
for (var key in data) {
if (data.hasOwnProperty(key)) {
if (argcount++) {
uri += '&';
}
uri += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
}
}
}
client.open(method, uri);
//client.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
client.send();
client.onload = function () {
if (this.status >= 200 && this.status < 300) {
// Performs the function "resolve" when this.status is equal to 2xx
deferred.resolve(this.response);
} else {
// Performs the function "reject" when this.status is different than 2xx
deferred.reject(this.statusText);
}
};
client.onerror = function () {
deferred.reject(this.statusText);
};
} | mit |
emiloberg/liferay-ddmtool | lib/saveStructures.js | 4280 | "use strict";
var fs = require('fs-extra');
var _ = require('underscore');
var utilities = require('./utilities.js');
var Constants = require('./Constants.js');
var LrClassNameConfig = require('./ClassNameConfig.js');
var Table = require('cli-table');
var saveStructures = function(e, filesRootPath, options) {
var filePath;
var fileContent;
var friendlyName = '';
var oldFile = '';
var downloadStatuses = [];
var outTable;
var states = [
{
status: 'uptodate',
heading: 'Already up to date'
},
{
status: 'update',
heading: 'Updated'
},
{
status: 'create',
heading: 'Created new'
}
];
for (var i = 0; i < e.length; ++i) {
filePath = filesRootPath + '/' + LrClassNameConfig.getSingleValue('id', e[i].classNameId, 'filesPath');
fileContent = e[i].xsd;
// If the class is DLFileEntryMetadata, then check 'type'.
// Depending on type, set different save paths for 'Document Type' and 'Metadata Set'
if (e[i].classNameId === LrClassNameConfig.getSingleValue('clazz', 'com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata', 'id')) {
if (e[i].type === 1) {
filePath = filePath + '/' + Constants.fetch('pathSlugDocumentTypes') + '/structures/' + e[i].nameCurrentValue + '.' + e[i].storageType;
} else {
filePath = filePath + '/' + Constants.fetch('pathSlugMetadataSets') + '/structures/' + e[i].nameCurrentValue + '.' + e[i].storageType;
}
} else {
filePath = filePath + '/structures/' + e[i].nameCurrentValue + '.' + e[i].storageType;
}
// Check status (if file needs to be updated, if it doesn't or if it's new.)
if (fs.existsSync(filePath)) {
try {
oldFile = fs.readFileSync(filePath, {encoding: Constants.fetch('filesEncoding')});
if (oldFile === fileContent) {
downloadStatuses.push({
status: 'uptodate',
name: e[i].nameCurrentValue,
type: LrClassNameConfig.getSingleValue('id', e[i].classNameId, 'friendlyName')
});
} else {
downloadStatuses.push({
status: 'update',
name: e[i].nameCurrentValue,
type: LrClassNameConfig.getSingleValue('id', e[i].classNameId, 'friendlyName')
});
fs.outputFileSync(filePath, fileContent);
}
} catch(catchErr) {}
} else {
downloadStatuses.push({
status: 'create',
name: e[i].nameCurrentValue,
type: LrClassNameConfig.getSingleValue('id', e[i].classNameId, 'friendlyName')
});
fs.outputFileSync(filePath, fileContent);
}
}
if (!options.silent) {
// Echo what has been saved
utilities.writeToScreen('', Constants.fetch('SEVERITY_NORMAL'), Constants.fetch('SCREEN_PRINT_HEADING'));
// Print already up to date
var countAlreadyUpToDate = downloadStatuses.filter(function (entry) {
return entry.status == states[0].status;
});
if (countAlreadyUpToDate.length > 0) {
utilities.writeToScreen(utilities.pad(countAlreadyUpToDate.length, 3, 'left') + ' structures - ' + states[0].heading, Constants.fetch('SEVERITY_NORMAL'), Constants.fetch('SCREEN_PRINT_SAVE'));
}
// Print update and create new
for (var z = 1; z < states.length; z++) {
/*jshint -W083 */
var outArr = downloadStatuses.filter(function (entry) {
return entry.status == states[z].status;
});
/*jshint +W083 */
if (outArr.length > 0) {
utilities.writeToScreen(utilities.pad(outArr.length, 3, 'left') + ' structures - ' + states[z].heading, Constants.fetch('SEVERITY_NORMAL'), Constants.fetch('SCREEN_PRINT_SAVE'));
outTable = new Table({
head: ['Name', 'Type'],
chars: {
'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
'left': '', 'left-mid': '', 'mid': '', 'mid-mid': '',
'right': '', 'right-mid': '', 'middle': ' '
},
style: {
'padding-left': 2,
'padding-right': 0,
'head': ['magenta']
},
colWidths: [40]
});
for (var x = 0; x < outArr.length; x++) {
outTable.push([
outArr[x].name,
outArr[x].type
]);
}
utilities.writeToScreen(outTable.toString(), Constants.fetch('SEVERITY_NORMAL'), Constants.fetch('SCREEN_PRINT_INFO'));
}
}
}
};
module.exports = saveStructures; | mit |
objorke/oxyplot | Source/Examples/DrawingLibrary/Examples/OpenStreetMapExamples/OpenStreetMapExamples.cs | 4003 | namespace DrawingLibrary.Examples
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using DrawingDemo;
using OsmLibrary;
using OxyPlot;
using OxyPlot.Drawing;
public static class OpenStreetMapExamples
{
[Example("OSM Høvik")]
public static Example OsmHøvik()
{
var drawing = new DrawingModel();
var tileLayer = new TileLayer
{
Source = "http://tile.openstreetmap.org/{Z}/{X}/{Y}.png",
CopyrightNotice = "OpenStreetMap",
Opacity = 0.2
};
drawing.Add(tileLayer);
Func<IEnumerable<Node>, IEnumerable<DataPoint>> transform = nodes => nodes.Select(n => tileLayer.Transform(new LatLon(n.Latitude, n.Longitude)));
var assembly = typeof(OpenStreetMapExamples).GetTypeInfo().Assembly;
using (var stream = assembly.GetManifestResourceStream("DrawingLibrary.Examples.OpenStreetMapExamples.map.osm"))
{
var osm = OpenStreetMap.Load(stream);
osm.Query(way => way["highway"] == "motorway", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -5 }));
osm.Query(way => way["highway"] == "primary", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -3 }));
osm.Query(way => way["highway"] == "secondary", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -2 }));
osm.Query(way => way["highway"] == "residential", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -2, Color = OxyColors.Gray }));
osm.Query(way => way["building"] != null, (way, nodes) => drawing.Add(new Polygon(transform(nodes)) { Fill = OxyColors.Gray }));
osm.Query(way => way["amenity"] == "parking", (way, nodes) => drawing.Add(new Polygon(transform(nodes)) { Fill = OxyColors.LightBlue }));
}
return new Example(drawing);
}
[Example("OSM MTB")]
public static Example OsmMtb()
{
// Ways with mtb:scale tags are extracted using http://overpass-turbo.eu/ with the following query
/*
<query type="way">
<has-kv k="mtb:scale"/>
<bbox-query {{bbox}}/>
</query>
<union>
<item />
<recurse type="way-node"/>
</union>
<print/>
*/
var drawing = new DrawingModel();
var tileLayer = new TileLayer
{
Source = "http://tile.openstreetmap.org/{Z}/{X}/{Y}.png",
CopyrightNotice = "OpenStreetMap",
};
drawing.Add(tileLayer);
Func<IEnumerable<Node>, IEnumerable<DataPoint>> transform = nodes => nodes.Select(n => tileLayer.Transform(new LatLon(n.Latitude, n.Longitude)));
var assembly = typeof(OpenStreetMapExamples).GetTypeInfo().Assembly;
using (var stream = assembly.GetManifestResourceStream("DrawingLibrary.Examples.OpenStreetMapExamples.mtbways.osm"))
{
var osm = OpenStreetMap.Load(stream);
osm.Query(way => way["mtb:scale"] == "0", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -5, Color = OxyColor.FromAColor(80, OxyColors.Green) }));
osm.Query(way => way["mtb:scale"] == "1", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -5, Color = OxyColor.FromAColor(80, OxyColors.Blue) }));
osm.Query(way => way["mtb:scale"] == "2", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -5, Color = OxyColor.FromAColor(80, OxyColors.Red) }));
osm.Query(way => way["mtb:scale"] == "3", (way, nodes) => drawing.Add(new Polyline(transform(nodes)) { Thickness = -5, Color = OxyColor.FromAColor(80, OxyColors.Magenta) }));
}
return new Example(drawing);
}
}
}
| mit |
thinkerbot/series_calc | benchmark/series_calc/core_bench.rb | 338 | #!/usr/bin/env ruby
require File.expand_path("../../helper", __FILE__)
Benchmark.bm(35) do |bm|
n = 100
nk = n * 1000
tries = 3
m = 100
mk = m * 1000
array = Array.new(mk)
tries.times do |try|
bm.report("#{n} #{m}k-array#each (#{try})") do
n.times do
array.each(&:object_id)
end
end
end
end
| mit |
pap/elixirscript | priv/javascript/lib/processes/processes/states.js | 444 | export default {
NORMAL: Symbol.for("normal"),
KILL: Symbol.for("kill"),
SUSPEND: Symbol.for("suspend"),
CONTINUE: Symbol.for("continue"),
RECEIVE: Symbol.for("receive"),
SEND: Symbol.for("send"),
SLEEPING: Symbol.for("sleeping"),
RUNNING: Symbol.for("running"),
SUSPENDED: Symbol.for("suspended"),
STOPPED: Symbol.for("stopped"),
SLEEP: Symbol.for("sleep"),
EXIT: Symbol.for("exit"),
NOMATCH: Symbol.for("no_match")
} | mit |
callemall/material-ui | packages/material-ui-icons/src/NineteenMpSharp.js | 374 | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M13.5 6.5H15V8h-1.5zM15 14h1.5v1.5H15z" /><path d="M3 3v18h18V3H3zm9 7h3V9h-3V5.5h4.5v6H12V10zM7 5.5h3v6H8.5V7H7V5.5zm5.5 13H11V14h-1v3H8.5v-3h-1v4.5H6v-6h6.5v6zM18 17h-3v1.5h-1.5v-6H18V17z" /></React.Fragment>
, 'NineteenMpSharp');
| mit |
softwarespartan/AGT | tests/ProcessingSessionValidate.py | 5025 | import Processing;
import unittest
class TestFunctions(unittest.TestCase):
def setUp(self):
# initialize a configuration object
self.session = Processing.Session();
# init session object properly
self.session.options['year'] = 2012;
self.session.options['doy' ] = 201;
def test_validate_year_none(self):
with self.assertRaises(Processing.SessionException):
self.session.options['year'] = None; self.session.validate();
def test_validate_year_not_int(self):
with self.assertRaises(Processing.SessionException):
self.session.options['year'] = 'someint'; self.session.validate();
def test_validate_year_small(self):
with self.assertRaises(Processing.SessionException):
self.session.options['year'] = 1847; self.session.validate();
def test_validate_year_yy(self):
with self.assertRaises(Processing.SessionException):
self.session.options['year'] = 01; self.session.validate();
def test_validate_year_big(self):
with self.assertRaises(Processing.SessionException):
self.session.options['year'] = 2047; self.session.validate();
def test_validate_doy_none(self):
with self.assertRaises(Processing.SessionException):
self.session.options['doy'] = None; self.session.validate();
def test_validate_doy_not_int(self):
with self.assertRaises(Processing.SessionException):
self.session.options['doy'] = '29yi'; self.session.validate();
def test_validate_doy_small(self):
with self.assertRaises(Processing.SessionException):
self.session.options['doy'] = -1; self.session.validate();
def test_validate_doy_big(self):
with self.assertRaises(Processing.SessionException):
self.session.options['year'] = 481; self.session.validate();
def test_validate_expt_too_long(self):
with self.assertRaises(Processing.SessionException):
self.session.options['expt'] = 'antarctica'; self.session.validate();
def test_validate_expt_too_short(self):
with self.assertRaises(Processing.SessionException):
self.session.options['expt'] = 'ant'; self.session.validate();
def test_validate_eop_wrong_type(self):
with self.assertRaises(Processing.SessionException):
self.session.options['eop_type'] = 'bull_a'; self.session.validate();
def test_validate_expt_type_wrong(self):
with self.assertRaises(Processing.SessionException):
self.session.options['expt_type'] = 'ephem'; self.session.validate();
def test_validate_minspan_too_big(self):
with self.assertRaises(Processing.SessionException):
self.session.options['minspan'] = '134'; self.session.validate();
def test_validate_minspan_too_small(self):
with self.assertRaises(Processing.SessionException):
self.session.options['minspan'] = '0'; self.session.validate();
def test_validate_minspan_not_int(self):
with self.assertRaises(Processing.SessionException):
self.session.options['minspan'] = 'ag12'; self.session.validate();
def test_validate_should_iterate(self):
with self.assertRaises(Processing.SessionException):
self.session.options['should_iterate'] = '1'; self.session.validate();
def test_validate_sp3_type_too_big(self):
with self.assertRaises(Processing.SessionException):
self.session.options['sp3_type'] = 'igs1'; self.session.validate();
def test_validate_sp3_type_too_small(self):
with self.assertRaises(Processing.SessionException):
self.session.options['sp3_type'] = 'i1'; self.session.validate();
def test_validate_org_too_big(self):
with self.assertRaises(Processing.SessionException):
self.session.options['org'] = 'anet'; self.session.validate();
def test_validate_org_too_small(self):
with self.assertRaises(Processing.SessionException):
self.session.options['org'] = 'at'; self.session.validate();
def test_validate_net_id_wrong(self):
with self.assertRaises(Processing.SessionException):
self.session.options['network_id'] = 'net12'; self.session.validate();
def test_validate_dns_none(self):
with self.assertRaises(Processing.SessionException):
self.session.options['dns'] = None; self.session.validate();
def test_validate_stn_list_duplicates(self):
with self.assertRaises(Processing.SessionException):
self.session.stn_list = ['igs.yell','igs.algo','igs.yell'];
self.session.validate();
if __name__ == '__main__':
unittest.main() | mit |
IonicaBizau/vowels | lib/index.js | 50 | module.exports = [
"a", "e", "i", "o", "u"
];
| mit |
codyaverett/CMNH-carshow | mean/modules/users/client/services/judges.client.service.js | 1562 | 'use strict';
// Authentication service for user variables
angular.module('users').factory('Judges', ['Classes',
function(Classes) {
var strings = {
carstrucks:[
'Paint - Overall Paint Job',
'Body & Exterior Modifications',
'Engine Modifications',
'Suspension/Undercarriage',
'Wheels & Tires',
'Interior Modifications',
'Lamps & Brightwork',
'Safety Equipment (Fire Extinguisher/FirstAid kit)'
], motorcycles: [
'Originality',
'Wheels & Tires',
'Paint',
'Plating',
'Electrical & Equipment',
'Controls',
'Cleanliness',
'Engine & Transmission'
]};
var isMotorcycle = function ( classString ) {
var result = Classes.getClassNumber(classString);
if( 1 == result || 20 == result || 21 == result || 22 == result )
return true;
return false;
};
var isCarOrisTruck = function ( classString ) {
var result = isMotorcycle( classString );
if (result == false)
return true;
return false;
}
return {
strings: strings,
isMotorcycle: isMotorcycle,
isCarOrisTruck: isCarOrisTruck
}
}
]); | mit |
xiao-T/vue-5253 | src/js/game-list-detail.js | 2667 | /**
* Create by xiaoT
* at 2015-11-23
*/
;(function(){
var GameListDetail = function(){
var _this = this;
_this.gameGroupId = common.getParam('gameGroupId') || 10;
_this.pageIndex = 0;
_this.gameListDetailWrap = $('#js-game-list-detail');
_this.gameListBase = $('#js-game-list-base');
_this.gameListDetail = _this.gameListDetailWrap.find('.detail-list');;
_this.loadMoreBtn = _this.gameListDetailWrap.find('.load-more');
_this.gameConut = _this.gameListDetailWrap.find('.count');
_this.init = function(){
common.goBack();
common.downApp('js-game-list-detail')
_this.getDataBase();
_this.getDetaiList();
_this.loadMore();
}
_this.getDataBase = function(){
var url;
url = common.domain + '/gameGroup/gameGroupDetail.action?gameGroupId=' + _this.gameGroupId;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data){
renderBase(data.data);
}
})
}
function renderBase(data){
var html = template('gameListBase', data);
// console.log(html);
_this.gameConut.html('共' + data.count + '款游戏')
_this.gameListBase.html(html);
}
function render(data){
var html = template('gameListDetail', data);
// console.log(html);
_this.gameListDetail.append(html);
}
_this.getDetaiList = function(){
var url;
url = common.domain + '/gameGroup/gameList.action?gameGroupId='+ _this.gameGroupId +'&pageIndex=' + _this.pageIndex;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data){
if(_this.pageIndex == data.nextIndex) {
_this.loadMoreBtn.hide();
} else {
_this.pageIndex = data.nextIndex;
_this.loadMoreBtn.show();
}
render(data);
}
})
}
_this.loadMore = function() {
_this.loadMoreBtn.tap(function(e){
_this.getDetaiList();
e.stopPropagation();
})
}
return {
'init': _this.init
}
}
var gameListDetail = new GameListDetail();
gameListDetail.init();
})($)
| mit |
nationalfield/symfony | lib/plugins/sfDoctrinePlugin/test/functional/fixtures/lib/form/doctrine/ProfileForm.class.php | 253 | <?php
/**
* Profile form.
*
* @package form
* @subpackage Profile
* @version SVN: $Id: ProfileForm.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class ProfileForm extends BaseProfileForm
{
public function configure()
{
}
}
| mit |
wangyanxing/Demi3D | src/tools/HonFxer/Editor/EditorManager.cpp | 21635 | /**********************************************************************
This source file is a part of Demi3D
__ ___ __ __ __
| \|_ |\/|| _)| \
|__/|__| || __)|__/
Copyright (c) 2013-2014 Demi team
https://github.com/wangyanxing/Demi3D
Released under the MIT License
https://github.com/wangyanxing/Demi3D/blob/master/License.txt
***********************************************************************/
#include "FxerPch.h"
#include "EditorManager.h"
#include "HonFxerApp.h"
#include "MainPaneControl.h"
#include "RenderWindowControl.h"
#include "ParticleSystemObj.h"
#include "ParticleElementObj.h"
#include "PointEmitterObj.h"
#include "CircleEmitterObj.h"
#include "LineEmitterObj.h"
#include "BoxEmitterObj.h"
#include "EffectManager.h"
#include "Grid.h"
#include "ColorControllerObj.h"
#include "VortexControllerObj.h"
#include "GravityControllerObj.h"
#include "TextureRotatorControllerObj.h"
#include "GeometryRotatorControllerObj.h"
#include "RandomiserControllerObj.h"
#include "JetControllerObj.h"
#include "ColliderControllerObj.h"
#include "ForceControllerObj.h"
#include "ScaleControllerObj.h"
#include "K2Configs.h"
#include "ParticleSystem.h"
#include "ParticleElement.h"
#include "ParticleEmitter.h"
#include "ParticleController.h"
#include "CommandManager.h"
#include "TokensParser.h"
#include "RenderWindow.h"
#include "Window.h"
#include "PathLib.h"
#include "MessageBox.h"
#include "AssetManager.h"
#include "RefModelObj.h"
#include "XMLFile.h"
#include "XMLElement.h"
#include "PropertyItem.h"
namespace Demi
{
DiEditorManager* DiEditorManager::sEditorMgr = nullptr;
DiEditorManager::DiEditorManager()
{
sEditorMgr = this;
InitFactories();
InitCommands();
mRootObject = CreateEditorObject("Base");
mRootObject->OnCreate();
mRootObject->OnCreateUI();
DiMaterialPtr dbgHelperMat = DiMaterial::QuickCreate("basic_v", "basic_p", SHADER_FLAG_USE_COLOR);
dbgHelperMat->SetDepthCheck(false);
mGridPlane = make_shared<DiGridPlane>(30, 10, DiColor(0.1f, 0.1f, 0.1f), DiColor(0.5f, 0.5f, 0.5f));
mGridPlane->SetMaterial(dbgHelperMat);
Driver->GetSceneManager()->GetRootNode()->AttachObject(mGridPlane);
CommandManager::getInstance().registerCommand("Command_ToolPlay", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolPlay));
CommandManager::getInstance().registerCommand("Command_ToolPause", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolPause));
CommandManager::getInstance().registerCommand("Command_ToolStop", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolStop));
CommandManager::getInstance().registerCommand("Command_ToolNewFile", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolNew));
CommandManager::getInstance().registerCommand("Command_ToolSaveFile", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolSave));
CommandManager::getInstance().registerCommand("Command_ToolOpenFile", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolOpen));
CommandManager::getInstance().registerCommand("Command_ToolReset", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolReset));
CommandManager::getInstance().registerCommand("Command_ToolSelect", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolSelect));
CommandManager::getInstance().registerCommand("Command_ToolMove", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolMove));
CommandManager::getInstance().registerCommand("Command_ToolRotate", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolRotate));
CommandManager::getInstance().registerCommand("Command_ToolScale", MyGUI::newDelegate(this, &DiEditorManager::Command_ToolScale));
}
DiEditorManager::~DiEditorManager()
{
SAFE_DELETE(mRootObject);
sEditorMgr = nullptr;
}
void DiEditorManager::Command_ToolPlay(const MyGUI::UString& _commandName, bool& _result)
{
if (mSelectingFx)
{
if(mSelectingFx->GetState() == DiParticleSystem::PSS_PAUSED)
{
mSelectingFx->Resume();
}
else if(mSelectingFx->GetState() == DiParticleSystem::PSS_STOPPED)
{
mSelectingFx->Start();
}
else
{
mSelectingFx->Stop();
mSelectingFx->Start();
}
}
_result = true;
}
void DiEditorManager::Command_ToolPause(const MyGUI::UString& _commandName, bool& _result)
{
if (mSelectingFx)
{
mSelectingFx->Pause();
}
_result = true;
}
void DiEditorManager::Command_ToolStop(const MyGUI::UString& _commandName, bool& _result)
{
if (mSelectingFx)
{
mSelectingFx->Stop();
}
_result = true;
}
void DiEditorManager::Command_ToolNew(const MyGUI::UString& _commandName, bool& _result)
{
DiString msg;
if (!mFxFileName.empty())
msg = "Do you want to keep the new effects?";
else
msg = "Do you want to save the effects?";
auto msgBox = MyGUI::Message::createMessageBox("Message", "New",
msg.c_str(),
MyGUI::MessageBoxStyle::Yes|MyGUI::MessageBoxStyle::No|
MyGUI::MessageBoxStyle::Cancel|MyGUI::MessageBoxStyle::IconDefault);
msgBox->eventMessageBoxResultLambda = [this](MyGUI::Message*, MyGUI::MessageBoxStyle style){
if(style == MyGUI::MessageBoxStyle::Yes)
{
SaveAll();
NewFx();
}
else if(style == MyGUI::MessageBoxStyle::No)
{
NewFx();
}
};
_result = true;
}
void DiEditorManager::Command_ToolSave(const MyGUI::UString& _commandName, bool& _result)
{
SaveAll();
_result = true;
}
void DiEditorManager::Command_ToolOpen(const MyGUI::UString& _commandName, bool& _result)
{
void* wndHandle = DiBase::Driver->GetMainRenderWindow()->GetWindow()->GetWndHandle();
DiVector<DiString> out;
DiString filter = "XML effect file(fx)|*.fx|All files (*.*)|*.*";
DiPathLib::OpenFileDialog(wndHandle, "Effect file", DiAssetManager::GetInstance().GetBasePath(), "", filter, 0, out);
if (out.size() >= 1)
{
OpenFx(out[0]);
}
_result = true;
}
void DiEditorManager::Command_ToolReset(const MyGUI::UString& _commandName, bool& _result)
{
auto msg = MyGUI::Message::createMessageBox("Message", "Reset",
"Do you really want to reset?",
MyGUI::MessageBoxStyle::Yes|MyGUI::MessageBoxStyle::No|
MyGUI::MessageBoxStyle::IconDefault);
msg->eventMessageBoxResultLambda = [this](MyGUI::Message*, MyGUI::MessageBoxStyle style){
if(style == MyGUI::MessageBoxStyle::Yes)
{
Reset();
}
};
_result = true;
}
void DiEditorManager::Command_ToolSelect(const MyGUI::UString& _commandName, bool& _result)
{
if(!HonFxerApp::GetFxApp()->GetMainPane()->GetWorkspaceControl()->GetRenderWndControl()->canvasFocus())
return;
SetGizmoMode(DiTransGizmo::GIZMO_SELECT);
_result = true;
}
void DiEditorManager::Command_ToolRotate(const MyGUI::UString& _commandName, bool& _result)
{
if(!HonFxerApp::GetFxApp()->GetMainPane()->GetWorkspaceControl()->GetRenderWndControl()->canvasFocus())
return;
SetGizmoMode(DiTransGizmo::GIZMO_ROTATE);
_result = true;
}
void DiEditorManager::Command_ToolScale(const MyGUI::UString& _commandName, bool& _result)
{
if(!HonFxerApp::GetFxApp()->GetMainPane()->GetWorkspaceControl()->GetRenderWndControl()->canvasFocus())
return;
SetGizmoMode(DiTransGizmo::GIZMO_SCALE);
_result = true;
}
void DiEditorManager::Command_ToolMove(const MyGUI::UString& _commandName, bool& _result)
{
if(!HonFxerApp::GetFxApp()->GetMainPane()->GetWorkspaceControl()->GetRenderWndControl()->canvasFocus())
return;
SetGizmoMode(DiTransGizmo::GIZMO_MOVE);
_result = true;
}
void DiEditorManager::SetWorldSpaceGizmo(bool val)
{
mWorldSpaceGizmoOrientation = val;
}
void DiEditorManager::SetGizmoMode(DiTransGizmo::GizmoMode mode)
{
mGlobalGizmoMode = mode;
if(mCurrentSel && mCurrentSel->GetGizmo())
{
mCurrentSel->GetGizmo()->SetGizmoMode(mode);
}
}
void DiEditorManager::NewFx()
{
Reset();
auto psObj = mRootObject->_CreateChild("ParticleSystem");
psObj->_CreateChild("ParticleElement");
}
void DiEditorManager::OpenFx(const DiString& fxFileName)
{
DiString base = fxFileName.ExtractFileName();
if(!DiAssetManager::GetInstance().HasArchive(base))
{
DiString message;
message.Format("Cannot find the effect file(%s) in our media folders!", base.c_str());
MyGUI::Message::createMessageBox("Message", "Error", message.c_str(),
MyGUI::MessageBoxStyle::Ok|MyGUI::MessageBoxStyle::IconError);
return;
}
DiFxTokensParser parser;
auto stream = DiAssetManager::GetInstance().OpenArchive(base);
shared_ptr<DiXMLFile> xmlfile(DI_NEW DiXMLFile());
xmlfile->Load(stream->GetAsString());
DiXMLElement root = xmlfile->GetRoot();
if (!root.CheckName("Effects"))
{
DI_WARNING("Bad effect file: %s", base.c_str());
return;
}
auto child = root.GetChild();
while (child)
{
if (child.CheckName("ParticleSystem"))
{
auto ps = parser.ReadSystem(child);
LoadParticleSystem(ps);
}
else if(child.CheckName("ReferenceModel"))
{
LoadRefModel(child);
}
child = child.GetNext();
}
SetCurrentFileName(fxFileName);
}
void DiEditorManager::Reset()
{
mRootObject->ClearChildren();
SetCurrentFileName("");
}
void DiEditorManager::SetCurrentFileName(const DiString& name)
{
mFxFileName = name;
DiString title = "Hon Fxer";
if(!name.empty())
title.Format("Hon Fxer - %s",name.ExtractFileName().c_str());
DiBase::Driver->GetMainRenderWindow()->GetWindow()->SetTitle(title.c_str());
}
void DiEditorManager::SaveAll(const DiString& fxFileName)
{
DiFxTokensParser parser;
shared_ptr<DiXMLFile> xmlfile(new DiXMLFile());
DiXMLElement root = xmlfile->CreateRoot("Effects");
mRootObject->TraversalChildren([&](size_t id, DiBaseEditorObj* obj){
if(obj->GetType() == "ParticleSystem")
{
auto psObj = dynamic_cast<DiParticleSystemObj*>(obj);
DiParticleSystemPtr ps = psObj->GetParticleSystem();
auto nd = root.CreateChild("ParticleSystem");
parser.WriteSystem(ps, nd);
}
else if(obj->GetType() == "ReferenceModel")
{
auto refmdObj = dynamic_cast<DiRefModelObj*>(obj);
refmdObj->Save(root);
}
});
xmlfile->Save(fxFileName);
SetCurrentFileName(fxFileName);
}
void DiEditorManager::SaveAll()
{
if (!mFxFileName.empty())
{
SaveAll(mFxFileName);
}
else
{
void* wndHandle = DiBase::Driver->GetMainRenderWindow()->GetWindow()->GetWndHandle();
DiVector<DiString> out;
DiString filter = "XML effect file(fx)|*.fx|All files (*.*)|*.*";
DiPathLib::SaveFileDialog(wndHandle, "Effect file", DiPathLib::GetApplicationPath(), "", filter, 0, out);
if (out.size() >= 1)
{
SaveAll(out[0]);
}
}
}
DiBaseEditorObj* DiEditorManager::LoadRefModel(const DiXMLElement& node)
{
auto psObj = mRootObject->_CreateChildFrom("ReferenceModel", DiAny(node));
return psObj;
}
DiBaseEditorObj* DiEditorManager::LoadParticleSystem(DiParticleSystemPtr ps)
{
DI_ASSERT(ps);
auto psObj = mRootObject->_CreateChildFrom("ParticleSystem", DiAny(ps));
size_t numElements = ps->GetNumElements();
for(size_t i = 0; i < numElements; ++i)
{
DiParticleElement* element = ps->GetElement(i);
auto elementObj = psObj->_CreateChildFrom("ParticleElement", DiAny(element));
// emitters
size_t numEmits = element->GetNumEmitters();
for(size_t e = 0; e < numEmits; ++e)
{
DiParticleEmitter* emitter = element->GetEmitter(e);
auto type = emitter->GetEmitterType() + "Emitter";
elementObj->_CreateChildFrom(type, DiAny(emitter));
}
// controllers
size_t numCtrls = element->GetNumControllers();
for(size_t c = 0; c < numCtrls; ++c)
{
DiParticleController* ctrl = element->GetController(c);
auto type = ctrl->GetControllerType() + "Controller";
elementObj->_CreateChildFrom(type, DiAny(ctrl));
}
}
return psObj;
}
DiBaseEditorObj* DiEditorManager::CreateEditorObject(const DiString& type)
{
DiBaseEditorObj* ret = nullptr;
auto it = mObjFactories.find(type);
if (it != mObjFactories.end())
{
ret = it->second();
}
else
{
DI_WARNING("Cannot create the object [type = %s]", type.c_str());
}
mLastCreatedObject = ret;
return ret;
}
void DiEditorManager::DeleteEditorObject(DiBaseEditorObj* obj)
{
if(mLastCreatedObject == obj)
mLastCreatedObject = nullptr;
if(obj->GetType() == "ParticleSystem")
{
if(dynamic_cast<DiParticleSystemObj*>(obj)->GetParticleSystem() == mSelectingFx)
{
if(mSelectingFx)
{
DI_DEBUG("Change selecting ps from [name = %s] to nullptr", mSelectingFx->GetName().c_str());
}
mSelectingFx = nullptr;
}
}
bool triggerChangemodel = obj->GetType() == "ReferenceModel";
DI_ASSERT(obj);
obj->Release();
SAFE_DELETE(obj);
mCurrentSel = nullptr;
if(triggerChangemodel)
{
DiEditorManager::Get()->TriggerEvent("RefModel");
}
}
void DiEditorManager::SetCurrentSelection(DiBaseEditorObj* sel)
{
if (mCurrentSel != sel)
{
mCurrentSel = sel;
SetGizmoMode(mGlobalGizmoMode);
auto psParent = mCurrentSel->LookForParent("ParticleSystem");
if(!psParent)
return;
auto psObj = dynamic_cast<DiParticleSystemObj*>(psParent);
mSelectingFx = psObj->GetParticleSystem();
DI_DEBUG("Change selecting ps to [name = %s]", mSelectingFx->GetName().c_str());
}
}
void DiEditorManager::InitFactories()
{
mObjFactories["Base"] = [](){return DI_NEW DiBaseEditorObj(); };
mObjFactories["ParticleSystem"] = [](){return DI_NEW DiParticleSystemObj(); };
mObjFactories["ParticleElement"] = [](){return DI_NEW DiParticleElementObj(); };
mObjFactories["PointEmitter"] = [](){return DI_NEW DiPointEmitterObj(); };
mObjFactories["BoxEmitter"] = [](){return DI_NEW DiBoxEmitterObj(); };
mObjFactories["CircleEmitter"] = [](){return DI_NEW DiCircleEmitterObj(); };
mObjFactories["LineEmitter"] = [](){return DI_NEW DiLineEmitterObj(); };
mObjFactories["ColorController"] = [](){return DI_NEW DiColorControllerObj(); };
mObjFactories["ScaleController"] = [](){return DI_NEW DiScaleControllerObj(); };
mObjFactories["VortexController"] = [](){return DI_NEW DiVortexControllerObj(); };
mObjFactories["JetController"] = [](){return DI_NEW DiJetControllerObj(); };
mObjFactories["GravityController"] = [](){return DI_NEW DiGravityControllerObj(); };
mObjFactories["RandomiserController"] = [](){return DI_NEW DiRandomiserControllerObj(); };
mObjFactories["GeometryRotatorController"] = [](){return DI_NEW DiGeometryRotatorControllerObj(); };
mObjFactories["TextureRotatorController"] = [](){return DI_NEW DiTextureRotatorControllerObj(); };
mObjFactories["LinearForceController"] = [](){return DI_NEW DiLinearForceControllerObj(); };
mObjFactories["SineForceController"] = [](){return DI_NEW DiSineForceControllerObj(); };
mObjFactories["BoxColliderController"] = [](){return DI_NEW DiBoxColliderControllerObj(); };
mObjFactories["SphereColliderController"] = [](){return DI_NEW DiSphereColliderControllerObj(); };
mObjFactories["PlaneColliderController"] = [](){return DI_NEW DiPlaneColliderControllerObj(); };
mObjFactories["ReferenceModel"] = [](){return DI_NEW DiRefModelObj(); };
}
DiString DiEditorManager::GenerateSystemName()
{
static int id = 0;
DiString ret;
ret.Format("ParticleSystem_%d", id++);
return ret;
}
DiString DiEditorManager::GenerateRefModelName()
{
static int id = 0;
DiString ret;
ret.Format("Model_%d", id++);
return ret;
}
DiString DiEditorManager::GenerateElementName()
{
static int id = 0;
DiString ret;
ret.Format("Element_%d", id++);
return ret;
}
DiString DiEditorManager::GenerateEmitterName(const DiString& type)
{
static int id = 0;
DiString ret;
ret.Format("%s_%d", type.c_str(), id++);
return ret;
}
DiString DiEditorManager::GenerateControllerName(const DiString& type)
{
static int id = 0;
DiString ret;
ret.Format("%s_%d", type.c_str(), id++);
return ret;
}
void DiEditorManager::InitCommands()
{
CommandMgr->AddCommand("removeObj", [&](Demi::DiCmdArgs* args){
if (mCurrentSel)
{
DeleteEditorObject(mCurrentSel);
return true;
}
else
{
DI_WARNING("No object selected, cannot remove!");
return false;
}
});
CommandMgr->AddCommand("createChild", [&](Demi::DiCmdArgs* args){
if (mCurrentSel)
{
DI_ASSERT(args->GetArgCount() == 2);
mCurrentSel->_CreateChild(args->GetArg(1));
return true;
}
else
{
DI_WARNING("No object selected, cannot create child!");
return false;
}
});
CommandMgr->AddCommand("selectLast", [&](Demi::DiCmdArgs* args){
mCurrentSel = mLastCreatedObject;
return true;
});
}
void DiEditorManager::Update()
{
DiEffectManager::GetInstance().Update();
mRootObject->Update(Driver->GetDeltaSecond());
}
void DiEditorManager::SetK2ResourcePack(const DiString& resPack, const DiString& texturePack)
{
if (texturePack.empty())
DiK2Configs::SetK2ResourcePack(resPack);
else
DiK2Configs::SetK2ResourcePack(resPack, texturePack);
}
void DiEditorManager::RegisterDynEnumItem(DiDynamicEnumPropertyItem* item, const DiString& eventName)
{
mDynEnumItems[eventName].insert( item );
}
void DiEditorManager::UnregisterDynEnumItem(DiDynamicEnumPropertyItem* item, const DiString& eventName)
{
auto it = mDynEnumItems.find(eventName);
if(it != mDynEnumItems.end())
{
auto& sets = it->second;
auto itemIt = sets.find(item);
if(itemIt != sets.end())
{
sets.erase(itemIt);
}
}
}
void DiEditorManager::TriggerEvent(const DiString& eventName)
{
auto it = mDynEnumItems.find(eventName);
if(it != mDynEnumItems.end())
{
for(auto& s : it->second)
{
s->NotifyDynEnumChanged();
}
}
}
} | mit |
s3db/s3db | read.php | 2441 | <?php
#acecpts an S3QL query to download the queried file
#Helena F Deus, March 18, 2009
ini_set('display_errors',0);
if($_REQUEST['su3d']) {
ini_set('display_errors',1);
}
if(file_exists('config.inc.php')) {
include('config.inc.php');
} else {
Header('Location: index.php');
exit;
}
include_once(S3DB_SERVER_ROOT.'/dbstruct.php');
include_once(S3DB_SERVER_ROOT.'/s3dbcore/authentication.php');
include_once(S3DB_SERVER_ROOT.'/s3dbcore/display.php');
include_once(S3DB_SERVER_ROOT.'/s3dbcore/callback.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/element_info.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/validation_engine.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/insert_entries.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/file2folder.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/update_entries.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/delete_entries.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/datamatrix.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/create.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/permission.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/list.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/S3QLRestWrapper.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/SQL.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/S3QLaction.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/htmlgen.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/acceptFile.php');
include_once (S3DB_SERVER_ROOT.'/s3dbcore/URIaction.php');
include_once(S3DB_SERVER_ROOT.'/s3dbcore/common_functions.inc.php');
$format = $_REQUEST['format'];
if($format=='') { $format='html'; }
#if a key has been provided, validate the key
$key=$_REQUEST['key'];
include_once('core.header.php');
$query=($_REQUEST['query']!="")?$_REQUEST['query']:$_REQUEST['q'];
if($query=='') {
echo formatReturn('3','Please input an S3QL query.',$format,'');
exit;
}
$q=compact('query','format','key','user_id','db');
$s3ql=parse_xml_query($q);
$s3ql['db']=$db;
$s3ql['user_id']=$user_id;
$data = S3QLaction($s3ql);
if(count($data)>1) {
$s3ql['order_by']='created_on desc';
$s3ql['limit']='1';
$data = S3QLaction($s3ql);
}
if($data[0]['file_name']=='') {
echo $data[0]['value'];
} else {
$statement_info = $data[0];
pushDownload2Header(compact('statement_info', 'db', 'user_id', 'format'));
}
?> | mit |
TGITS/programming-workouts | java/misc/camera/src/main/java/com/github/tgits/camera/Camera.java | 1435 | package com.github.tgits.camera;
/**
* Example taken from Functional Programming in Java from Venkat Subramaniam,
* Chapter 4 "Designing with Lambda Expressions"
*/
import java.awt.*;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Function;
@SuppressWarnings("unchecked")
public class Camera {
private Function<Color, Color> filter;
public Camera() {
setFilters();
}
public Color capture(final Color inputColor) {
final Color processedColor = filter.apply(inputColor);
return processedColor;
}
public void setFilters(final Function<Color, Color>... filters) {
filter = Arrays.asList(filters).stream()
.reduce((filter, next) -> filter.compose(next))
.orElse(color -> color);
}
public static void main(String args[]) {
final Camera camera = new Camera();
final Consumer<String> printCaptured = (filterInfo) -> System.out.println(String.format("with %s: %s", filterInfo, camera.capture(new Color(200, 100, 200))));
//printCaptured.accept("no filter");
//camera.setFilters(Color::brighter);
//printCaptured.accept("brighter filter");
//camera.setFilters(Color::darker);
//printCaptured.accept("darker filter");
camera.setFilters(Color::brighter, Color::darker);
printCaptured.accept("brighter & darker filter");
}
}
| mit |
jakulov/bun | src/Core/Repository/AbstractRepository.php | 3933 | <?php
namespace Bun\Core\Repository;
use Bun\Core\Config\ConfigAwareInterface;
use Bun\Core\Config\ConfigInterface;
use Bun\Core\Model\ModelInterface;
use Bun\Core\ObjectMapper\ObjectMapperInterface;
/**
* Class AbstractRepository
*
* @package Bun\Core\Repository
*/
abstract class AbstractRepository implements RepositoryInterface, ConfigAwareInterface
{
/** @var ObjectMapperInterface */
protected $objectMapper;
/** @var string */
protected $className;
/** @var ModelInterface */
protected $modelObject;
/** @var ConfigInterface */
protected $config;
/**
* @param ConfigInterface $config
*/
public function setConfig(ConfigInterface $config)
{
$this->config = $config;
}
/**
* @param ObjectMapperInterface $objectMapper
* @return mixed|void
*/
public function setObjectManager(ObjectMapperInterface $objectMapper)
{
$this->objectMapper = $objectMapper;
}
/**
* @param $className
* @return $this
*/
public function setModelClassName($className)
{
$this->className = $className;
$this->modelObject = new $className;
return $this;
}
/**
* @return \Bun\Core\Storage\StorageInterface
*/
public function getStorage()
{
return $this->objectMapper->getStorage($this->className);
}
/**
* @return ObjectMapperInterface
*/
public function getObjectMapper()
{
return $this->objectMapper;
}
/**
* @param $id
* @return ModelInterface
*/
abstract public function find($id);
/**
* @param $where
* @param array $orderBy
* @param array $limit
* @return ModelInterface[]
*/
abstract public function findBy($where, $orderBy = array(), $limit = array());
abstract public function count($where, $limit = array());
/**
* @param $data
* @return \Bun\Core\Model\ModelInterface
*/
protected function createObject($data)
{
if ($data) {
return $this->getObjectMapper()->map($this->className, $data);
}
return null;
}
/**
* @param $data
* @param array $aggregateFields
* @return \Bun\Core\Model\ModelInterface[]
*/
protected function createObjectsArray($data, $aggregateFields = array())
{
if ($data) {
return $this->getObjectMapper()->mapArray($this->className, $data, $aggregateFields);
}
return array();
}
/**
* @return mixed
*/
public function getTable()
{
return $this->modelObject->getTableName();
}
/**
* @param $clause
* @param null|ModelInterface $object
* @return array
*/
public function mapClauseFields($clause, $object = null)
{
if ($object === null) {
$object = $this->modelObject;
}
$mappedClause = array();
foreach ($clause as $field => $value) {
$mappedField = null;
$mappedValue = null;
if (strpos($field, '$') === false) {
$mappedField = $object->field($field);
}
elseif (is_array($value)) {
$mappedValue = $this->mapClauseFields($value, $object);
}
if($mappedField !== null) {
$mappedClause[$mappedField] = $value;
}
elseif($mappedValue !== null) {
$mappedClause[$field] = $mappedValue;
}
else {
$mappedClause[$field] = $value;
}
}
return $mappedClause;
}
/**
* @param $field
* @param null $object
* @return mixed
*/
public function mapField($field, $object = null)
{
if ($object === null) {
$object = $this->modelObject;
}
return $object->field($field);
}
} | mit |
Leo-g/Flask-Scaffold | app/templates/static/node_modules/karma-jasmine-html-reporter/src/index.js | 839 | var JASMINE_CORE_PATTERN = /([\\/]karma-jasmine[\\/])/i;
var createPattern = function (path) {
return { pattern: path, included: true, served: true, watched: false };
};
var initReporter = function (files, baseReporterDecorator) {
var jasmineCoreIndex = 0;
baseReporterDecorator(this);
files.forEach(function (file, index) {
if (JASMINE_CORE_PATTERN.test(file.pattern)) {
jasmineCoreIndex = index;
}
});
files.splice(++jasmineCoreIndex, 0, createPattern(__dirname + '/css/jasmine.css'));
files.splice(++jasmineCoreIndex, 0, createPattern(__dirname + '/lib/html.jasmine.reporter.js'));
files.splice(++jasmineCoreIndex, 0, createPattern(__dirname + '/lib/adapter.js'));
};
initReporter.$inject = ['config.files', 'baseReporterDecorator'];
module.exports = {
'reporter:kjhtml': ['type', initReporter]
};
| mit |
Lloople/deployer | app/Factories/MessengerFactory.php | 540 | <?php
namespace Deployer\Factories;
use Deployer\Exceptions\MessengerNotFound;
class MessengerFactory
{
public function create($class, $configuration)
{
$messengerClass = $this->getMessengerClass($class);
if (! class_exists($messengerClass)) {
throw new MessengerNotFound();
}
return new $messengerClass($configuration);
}
public function getMessengerClass($class)
{
return 'Deployer\Messengers\\' . ucfirst($class) . '\\' . ucfirst($class).'Messenger';
}
} | mit |
ARCANESOFT/Tracker | resources/views/admin/_composers/dashboard/referers-ratio-list.blade.php | 2040 | <div class="box">
<div class="box-header with-border">
<h2 class="box-title">{{ trans('tracker::referers.titles.referers') }}</h2>
</div>
<div class="box-body no-padding">
<div class="table-responsive">
<table class="table table-condensed table-hover no-margin">
<thead>
<tr>
<th>{{ trans('tracker::referers.attributes.domain') }}</th>
<th class="text-center" style="width: 100px;">{{ trans('tracker::generals.count') }}</th>
<th>{{ trans('tracker::generals.percentage') }}</th>
</tr>
</thead>
<tbody>
@forelse($referersRatio as $referer)
<tr>
<td>
<small>{{ $referer['name'] }}</small>
</td>
<td class="text-center">
{{ label_count($referer['count']) }}
</td>
<td>
<div class="progress no-margin">
<div class="progress-bar progress-bar-primary" role="progressbar" aria-valuenow="{{ $referer['percentage'] }}%" aria-valuemin="0" aria-valuemax="100" style="width: {{ $referer['percentage'] }}%">
{{ $referer['percentage'] }}%
</div>
</div>
</td>
</tr>
@empty
<tr>
<td colspan="3" class="text-center">
<span class="label label-default">{{ trans('tracker::referers.list-empty') }}</span>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
| mit |
ArijitK2015/love_-architect | application/controllers/Admin_email_template.php | 3990 | <?php
class Admin_email_template extends MY_Controller {
public function __construct()
{
parent::__construct();
}
/**
* Load the main view with all the current model model's data.
* @return void
*/
public function index()
{
$data['info'] = $this->email_template_model->get_tempalte_info();
$data['view_link'] = 'admin/email_template/email_template_manage';
$this->load->view('includes/template', $data);
}
function delete()
{
$id = $this->uri->segment(4);
$this->newsletter->delete_email($id);
redirect('control/newsletters');
}
public function add()
{
$tablename='email_template';
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$data_to_store = array(
'email_subject' => $this->input->post('subject'),
'email_template' => $this->input->post('email_content')
);
$last_insert=$this->email_template_model->store_template($data_to_store,$tablename);
}
//load the view
$data['view_link'] = 'admin/template/add_template';
$this->load->view('includes/template', $data);
}
public function updt()
{
//product id
$id = $this->input->post('page_id');
$user_id = ($this->session->userdata('user_id_lovearchitect')) ? $this->session->userdata('user_id_lovearchitect') : 1;
$setting_data = $this->myaccount_model->get_account_data($user_id);
$data['data']['setting_data'] = $setting_data;
$data['data']['settings'] = $this->sitesetting_model->get_settings();
$data['data']['dealer_id'] = $user_id;
//settings data
$data['data']['myaccount_data'] = $this->myaccount_model->get_account_data($user_id);
$edit_id = $this->input->post('edit_id');
//if save button was clicked, get the data sent via post
if ($this->input->server('REQUEST_METHOD') === 'POST' && $edit_id != '')
{
$data_to_store = array(
'email_subject' => $this->input->post('email_subject'),
'email_template' => $this->input->post('email_template')
);
$this->mongo_db->where(array('_id' => strval($edit_id)));
$this->mongo_db->set($data_to_store);
//if the insert has returned true then we show the flash message
if($this->mongo_db->update('email_templates'))
$this->session->set_flashdata('flash_message', 'pages_updated');
else
$this->session->set_flashdata('flash_message', 'pages_not_updated');
redirect('control/email-template');
}
$this->mongo_db->where(array('_id' => $id));
$edit_contents = $this->mongo_db->get('email_templates');
$data['data']['page_content'] = $edit_contents;
if(count($edit_contents)==0)
{
redirect('control/email-template');
}
$data['view_link'] = 'admin/email_template/edit_email_template';
$this->load->view('includes/template', $data);
}//update
public function modify()
{
$id = $this->uri->segment(4);
$tablename='email_template';
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$data_to_store = array(
'email_title' => $this->input->post('edit_title'),
'email_subject' => $this->input->post('edit_subject'),
'email_template' => $this->input->post('edit_email_content')
);
if($this->email_template_model->update_template($id, $data_to_store,$tablename) == TRUE)
{
$this->session->set_flashdata('flash_message', 'pages_updated');
}else
{
$this->session->set_flashdata('flash_message', 'pages_not_updated');
}
//redirect('admin/pages/update/'.$id.'');
redirect('control/email_template');
}
}
}
?> | mit |
e-budur/detective-criminal-name-search | Detective.Web/App_Start/BundleConfig.cs | 1873 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Optimization;
namespace Detective.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-{version}.js",
"~/Scripts/knockout.validation.js"));
bundles.Add(new ScriptBundle("~/bundles/app").Include(
"~/Scripts/sammy-{version}.js",
"~/Scripts/app/common.js",
"~/Scripts/app/app.datamodel.js",
"~/Scripts/app/app.viewmodel.js",
"~/Scripts/app/home.viewmodel.js",
"~/Scripts/app/_run.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
}
}
}
| mit |
azihsoyn/gocovercache | gocovercache_test.go | 331 | package main
import (
"testing"
"github.com/kr/pretty"
)
func TestCalcCheckSum(t *testing.T) {
checksum := calcCheckSum("./")
pretty.Println("checksum : ", checksum)
}
func TestGetAbsolutePackageDir(t *testing.T) {
pkgDir := getAbsolutePackageDir("github.com/azihsoyn/gocovercache")
pretty.Println("pkgDir : ", pkgDir)
}
| mit |
Tommmi/Reunion | source/Reunion.Common/Model/TimeRange.cs | 2205 | using System;
using System.ComponentModel.DataAnnotations;
namespace Reunion.Common.Model
{
/// <summary>
/// Entity which represents a date range intervall, when the given player can come or not.
/// TimeRange is associated with exactly one reunion and one player
/// </summary>
public class TimeRange
{
/// <summary>
///
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="preference"></param>
/// <param name="player"></param>
/// <param name="reunion"></param>
public TimeRange(
DateTime start,
DateTime end,
PreferenceEnum preference,
Player player,
ReunionEntity reunion)
{
Init(
start,
end,
preference,
player,
reunion);
}
/// <summary>
///
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="preference"></param>
/// <param name="player"></param>
/// <param name="reunion"></param>
/// <returns></returns>
public TimeRange Init(
DateTime start,
DateTime end,
PreferenceEnum preference,
Player player,
ReunionEntity reunion)
{
Start = start;
End = end;
Preference = preference;
Player = player;
Reunion = reunion;
return this;
}
public TimeRange()
{
}
public int Id { get; set; }
public ReunionEntity Reunion { get; set; }
public Player Player { get; set; }
[Required]
public DateTime Start { get; set; }
[Required]
public DateTime End { get; set; }
[Required]
public PreferenceEnum Preference { get; set; }
/// <summary>
/// true if "date" is in date range [Start,End]
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public bool IsInRange(DateTime date)
{
return date.Date >= Start.Date && date.Date <= End.Date;
}
/// <summary>
/// true, if date is in this date range and the date range is marked as a time,
/// when the player can come to the meeting
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public bool IsAcceptedDate(DateTime date)
{
return IsInRange(date)
&& (Preference == PreferenceEnum.Yes || Preference == PreferenceEnum.PerfectDay);
}
}
}
| mit |
mayc2/PseudoKnot_research | HotKnots_v2.0/LE/commonPK_old.cpp | 74461 | /***************************************************************************
common.cpp - description
-------------------
begin : Thu Apr 11 2002
copyright : (C) 2002 by Mirela Andronescu
email : andrones@cs.ubc.ca
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
// This file contains common functions, that may be used throughout the library
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "commonPK.h"
#include "common.h"
#include "externs.h"
#include "externsPK.h"
#include "structs.h"
#include "s_hairpin_loop.h"
#include "s_stacked_pair.h"
#include "s_internal_loop.h"
//#include "s_specific_functions.h"
#include "constantsPK.h"
//#include "common.h" // July 17 - removed - unnecessary
//#include "constants.h" // July 17 - removed - unnecessary
//#include "structsPK.h" // July 17 - removed - unnecessary
//#include "externs.h" // July 17 - removed - unnecessary
//#include "externsPK.h" // July 17 - removed - unnecessary
#include "Stack.h"
#include "s_hairpin_loop.h"
#include "s_stacked_pair.h"
#include "s_internal_loop.h"
#include "s_specific_functions.h"
#include "common.h" // July 17 - removed - unnecessary
//#include "constants.h" // July 17 - removed - unnecessary
//#include "structsPK.h" // July 17 - removed - unnecessary
//#include "externs.h" // July 17 - removed - unnecessary
//#include "externsPK.h" // July 17 - removed - unnecessary
//#include "computeEnergy.h"
#include "params.h"
#include "paramsPK.h"
PARAMTYPE LEstacked_pair_energy (int i, int j, int *sequence)
{
// printf("INSIDE LE_STACK = %f\n", s_stacked_pair::get_energy (i, j, sequence));
return s_stacked_pair::get_energy (i, j, sequence);
}
PARAMTYPE LEhairpin_loop_energy (int i, int j, int* sequence, char *csequence)
// PRE: seq is the sequence of the loop; important for tetraloops
// I assume i-j can pair
// POST: Help function to compute_hairpin_matrix
// Return the energy of a hairpin
{
//PARAMTYPE testvar = s_hairpin_loop::get_energy(i, j, sequence, csequence);
//printf("******* %f", testvar);
//return testvar;
// printf("Inside LE_HAIR = %f\n", s_hairpin_loop::get_energy(i, j, sequence, csequence));
return s_hairpin_loop::get_energy(i, j, sequence, csequence);
}
PARAMTYPE LEinternal_loop_energy (int i, int j, int ip, int jp, int *sequence)
// PRE: The energy matrix was calculated
// POST: Read from the read pool, write to nodes;
// Store the node and return the energy.
{
// printf("Inside LE_internal = %f\n", s_internal_loop::get_energy(i,j,ip,jp,sequence));
return s_internal_loop::get_energy(i,j,ip,jp,sequence);
}
/*
void substr (char *source, int begin, int end, char *dest)
// PRE: begin and end are smaller than strlen(source)
// POST: Put in dest what is in source between position begin and position end
{
// in src/common/common.cpp
// common::substr(source, begin, end, dest);
substr(source, begin, end, dest);
}
int penalty_by_size (int size, char type)
// PRE: size is the size of the loop
// type is HAIRP or INTER or BULGE
// POST: return the penalty by size of the loop
{
// in src/common/common.cpp
return penalty_by_size(size, type);
}
void giveup (char *string1, char *string2)
// to add: variable nb of parameters, as in scanf, printf
{
// in src/common/common.cpp
giveup(string1, string2);
}
void empty_string (char * str)
// PRE: str is a string
// POST: Put '\0' at all positions
{
// in src/common/common.cpp
empty_string(str);
}
*/
// Cristina: changed this to match the simfold prototype
PARAMTYPE dangling_energy (int *sequence, char* structure, int i1, int i2, int i3, int i4)
// ( )...( )
// i1..i2..i3..i4
// PRE: (i1, i2) and (i3, i4) are pairs, i2 and i3 are neighbours, i2 < i3
// POST: return dangling energy between i2 and i3
{
if (no_pk_dangling_ends == 0)
return s_dangling_energy(sequence, structure, i1, i2, i3, i4);
return 0;
}
PARAMTYPE dangling_energy_left (int *sequence, char* structure, int i1, int i2, int i3, int i4)
// (....( ) )
// i1 i3 i4 i2
// PRE: (i1, i2) and (i3, i4) are pairs, i1 and i3 are neighbours, i3 < i2
// POST: return dangling energy between i1 and i3
{
if (no_pk_dangling_ends == 0)
return s_dangling_energy_left(sequence, structure, i1, i2, i3, i4);
return 0;
}
PARAMTYPE dangling_energy_right (int *sequence, char* structure, int i1, int i2, int i3, int i4)
// ( ( )...)
// i1 i3 i4 i2
// PRE: (i1, i2) and (i3, i4) are pairs, i1 and i3 are neighbours, i3 < i2
// POST: return dangling energy between i4 and i2
{
if (no_pk_dangling_ends == 0)
return s_dangling_energy_right(sequence, structure, i1, i2, i3, i4);
return 0;
}
// COAXIAL STACKING
int LEcoax_stack_energy_flush_a (int i, int j, int ip, int jp, int *sequence)
// Pre: ip is i+1 and jp = bp(ip) and j = bp(i); that is, i is always closest to 5' end compared to ip
// Post: Returns coaxial stacking energy from Walter et al 1999, or Turner parameters
// if the given combination is not calculated in Walter et al. 1999, or 0 if
// the returned value is INF (base pair is not canonical)
// Energy returned in 10cal/mol
{
int coaxial = coaxstack_f_a [sequence[i]]
[sequence[j]]
[sequence[ip]]
[sequence[jp]];
if (DEBUG2)
printf("LEcoax_stack_energy_flush_a: coaxstack[%d][%d]{%d][%d] = %d\n", i, j, ip, jp, coaxial);
if (coaxial >= INF)
{
coaxial = stack [sequence[i]]
[sequence[j]]
[sequence[ip]]
[sequence[jp]];
if (DEBUG2)
printf("LEcoax_stack_energy_flush_a: stack[%d][%d]{%d][%d] = %d\n", i, j, ip, jp, coaxial);
if (coaxial >= INF)
return 0;
}
return coaxial;
}
int LEcoax_stack_energy_flush_b (int i, int j, int ip, int jp, int flag, int dangle_i, int dangle_ip, int other_j, int other_jp, int *sequence, int ignore_dangles)
// Pre: ip is i+1 and jp = bp(ip) and j = bp(i); that is, i is always closest to 5' end compared to ip
// flag = COAX_MULTI, COAX_PSEUDO, or COAX_OTHER
// dangle_i corresponds to the base pair i.j
// dangle_ip corresponds to the base pair ip.jp
// Post: Returns coaxial stacking energy from Turner lab / Mathews parameters (coaxial.dat).
// Currently, this is simply the Turner parameters for a regular stacked pair, or 0 if
// the returned value is INF (base pair is not canonical)
// Energy returned in 10cal/mol
{
int coaxial = coaxstack_f_b [sequence[i]]
[sequence[j]]
[sequence[ip]]
[sequence[jp]];
int dangle_en1 = 0;
int dangle_en2 = 0;
if (flag == COAX_MULTI) // between rightmost child and outer base pair of multiloop (here, ip > jp, so dangle_ip = ip - 1 and use dangle_bot, dangle 3')
{
// outer base pair and leftmost child stack
// dangle_ip dangle_i
// | |
// ( . . ( ) )
// jp j i ip
// outer base pair and rightmost child stack
// dangle_ip dangle_i
// | |
// ( ( ) . . )
// i ip jp j
if (ignore_dangles == 0)
{
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// take dangle_en2 as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_f_b, multi: dangle_en1 = %d, dangle_en2 = %d\n", dangle_en1, dangle_en2);
if (dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return 0;
}
else if (flag == COAX_OTHER) //e.g two children in a multiloop (here, ip < jp here so dangle_ip is jp+1, so use dangle_top, dangle 5')
{
// dangle_i dangle_ip
// | |
// . ( ) ( ) .
// j i ip jp
if (ignore_dangles == 0)
{
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0) // the next base pair to the left of j shares the dangling end
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0) // the next base pair to the right of jp shares the dangling end
{
if (simple_dangling_ends)
{
// return the current dangle_en2
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_f_b, other: dangle_en1 = %d, dangle_en2 = %d\n", dangle_en1, dangle_en2);
if (dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return 0;
}
else // if (flag == COAX_PSEUDO)
{
// dangle_ip dangle_i
// | |
// ( . ( ) . )
// jp i ip j
if (ignore_dangles == 0)
{
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// leave as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_f_b, pseudo: dangle_en1 = %d, dangle_en2 = %d\n", dangle_en1, dangle_en2);
if (dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return 0;
}
if (DEBUG2)
printf("LEcoax_stack_energy_flush_b: coaxstack[%d][%d]{%d][%d] = %d\n", i, j, ip, jp, coaxial);
if (coaxial >= INF)
{
return 0;
}
return coaxial;
}
int LEcoax_stack_energy_mismatch(int i, int j, int ip, int jp, int flag, int dangle_i, int dangle_ip, int *sequence, char* structure, int other_j, int other_jp, int& stack_dangle, int ignore_dangles)
// Pre: ip is i+2 and jp = bp(ip) and j = bp(i); that is, i is always closest to 5' end compared to ip
// flag = COAX_MULTI, COAX_PSEUDO, or COAX_OTHER
// dangle_i corresponds to the base pair i.j
// dangle_ip corresponds to the base pair ip.jp
// Post: Returns coaxial stacking mismatch energy from Turner lab / Mathews parameters.
// stack_dangle is set to 0 or 1 to indicate whether the i or ip dangle, respectively, is involved in the stacking
//
// Note: "structure" does not have to be the true representation (i.e. use different paranetheses for
// different bands. (In particular, do not use < or > since these have a special interpretation in
// the dangling energy function.)
//
// Energy returned in 10cal/mol
{
int coaxial_i = 0;
int coaxial_ip = 0;
if (dangle_i > 0) // involve dangle_i in coaxial stack only if it's a free base
coaxial_i = ( coaxstack_m1 [sequence[i]] [sequence[j]] [sequence[i+1]] [sequence[dangle_i]] +
coaxstack_m2 [sequence[i+1]] [sequence[dangle_i]] [sequence[ip]] [sequence[jp]] );
if (dangle_ip > 0) // involve dangle_ip in coaxial stack only if it's a free base
coaxial_ip = ( coaxstack_m1 [sequence[jp]] [sequence[ip]] [sequence[dangle_ip]] [sequence[i+1]] +
coaxstack_m2 [sequence[i]] [sequence[j]] [sequence[i+1]] [sequence[dangle_ip]] );
if (DEBUG2)
{
printf("LEcoax_stack_energy_mismatch: i.j, dangle_i %d(%d).%d(%d) dangle %d(%d); ip.jp, dangle_ip %d(%d).%d(%d), dangle %d(%d); i+1 = %d(%d)\n",
i, sequence[i], j, sequence[j], dangle_i, sequence[dangle_i], ip, sequence[ip], jp, sequence[jp], dangle_ip, sequence[dangle_ip], i+1, sequence[i+1]);
printf(" coaxial_i = ");
if (dangle_i > 0)
printf("%d + %d = ", coaxstack_m1 [sequence[i]] [sequence[j]][sequence[i+1]] [sequence[dangle_i]],
coaxstack_m2 [sequence[i+1]] [sequence[dangle_i]] [sequence[ip]] [sequence[jp]], coaxial_i);
printf("%d; ", coaxial_i);
printf("coaxial_ip = ");
if (dangle_ip > 0)
printf("%d + %d = ", coaxstack_m1 [sequence[jp]] [sequence[ip]] [sequence[dangle_ip]] [sequence[i+1]],
coaxstack_m2 [sequence[i]] [sequence[j]] [sequence[i+1]] [sequence[dangle_ip]]);
printf("%d \n", coaxial_ip);
}
int coaxial = 0;
if (coaxial_i <= coaxial_ip)
{
coaxial = coaxial_i;
stack_dangle = 0; // i is part of the continuous backbone stack
}
else
{
coaxial = coaxial_ip;
stack_dangle = 1; // ip is part of the continuous backbone stack
}
int dangle_en0 = 0;
int dangle_en1 = 0;
int dangle_en2 = 0;
if (flag == COAX_MULTI) // between rightmost child and outer base pair of multiloop (here, ip > jp, so dangle_ip = ip - 1 and use dangle_bot, dangle 3')
{
// outer base pair and leftmost child stack
// dangle_ip dangle_i
// | |
// ( . . ( ) . )
// jp j i ip
// outer base pair and rightmost child stack
// dangle_ip dangle_i
// | |
// ( . ( ) . . )
// i ip jp j
if (ignore_dangles == 0)
{
// dangling energy of base between i and ip
if (ip < jp) // outer base pair and leftmost child stacking
dangle_en0 = s_dangling_energy_left(sequence, structure, i, j, ip, jp);
else // outer base pair and rightmost child stacking
dangle_en0 = s_dangling_energy_right(sequence, structure, ip, j, i, jp);
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// take dangle_en2 as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_mismatch, multi: dangle_en0 = %d, dangle_en1 = %d, dangle_en2 = %d\n", dangle_en0, dangle_en1, dangle_en2);
if (dangle_en0 + dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return 0;
}
else if (flag == COAX_OTHER) //e.g two children in a multiloop (here, ip < jp here so dangle_ip is jp+1, so use dangle_top, dangle 5')
{
// dangle_i dangle_ip
// | |
// . ( ) . ( ) .
// j i ip jp
if (ignore_dangles == 0)
{
// dangling energy of base between i and ip
dangle_en0 = s_dangling_energy(sequence, structure, j, i, ip, jp);
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0) // the next base pair to the left of j shares the dangling end
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0) // the next base pair to the right of jp shares the dangling end
{
if (simple_dangling_ends)
{
// return the current dangle_en2
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_mismatch, other: dangle_en0 = %d, dangle_en1 = %d, dangle_en2 = %d\n", dangle_en0, dangle_en1, dangle_en2);
if (dangle_en0 + dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return 0;
}
else // if (flag == COAX_PSEUDO)
{
// ignore danling, calculate just coaxial energy
// dangle_ip dangle_i
// | |
// ( . ( ) . )
// jp i ip j
if (ignore_dangles == 0)
{
// dangling energy of base between i and ip
dangle_en0 = s_dangling_energy(sequence, structure, j, i, ip, jp);
// NOTE: even though this is the dangling energy between two stems of a pseudoknot,
// simply using the schema shown below for the parameters of s_dangling_energy
// yields the correct result, since the dangling bases are now on the inside of
// base pairs i1.i2, i3.i4 in the implementation of s_dangling_energy
// ( ( ... ) )
// i4 i2 i3 i1
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// leave as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_mismatch, pseudo: dangle_en0 = %d, dangle_en1 = %d, dangle_en2 = %d\n", dangle_en0, dangle_en1, dangle_en2);
if (dangle_en0 + dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return 0;
}
if (coaxial >= INF)
{
return 0;
}
return coaxial;
}
//// FOR PARAMETER TUNING //////
void count_LEcoax_stack_energy_flush_b (int i, int j, int ip, int jp, int flag, int dangle_i, int dangle_ip, int other_j, int other_jp, int *sequence, double* counter, int ignore_dangles)
// Pre: ip is i+1 and jp = bp(ip) and j = bp(i); that is, i is always closest to 5' end compared to ip
// flag = COAX_MULTI, COAX_PSEUDO, or COAX_OTHER
// dangle_i corresponds to the base pair i.j
// dangle_ip corresponds to the base pair ip.jp
// Post: Returns coaxial stacking energy from Turner lab / Mathews parameters (coaxial.dat).
// Currently, this is simply the Turner parameters for a regular stacked pair, or 0 if
// the returned value is INF (base pair is not canonical)
// NOTE: all the flags work, not just COAX_PSEUDO
{
int coaxial = coaxstack_f_b [sequence[i]]
[sequence[j]]
[sequence[ip]]
[sequence[jp]];
int num_params_DP_and_pkfree = get_num_params_PK_DP();
char type[100];
sprintf(type, "coaxstack_f_b[%d][%d][%d][%d]", sequence[i], sequence[j], sequence[ip], sequence[jp]);
int index_coax = structure_type_index_PK_CC(type);
int dangle_en1 = 0;
int dangle_en2 = 0;
if (flag == COAX_MULTI) // between rightmost child and outer base pair of multiloop (here, ip > jp, so dangle_ip = ip - 1 and use dangle_bot, dangle 3')
{
// outer base pair and leftmost child stack
// dangle_ip dangle_i
// | |
// ( . . ( ) )
// jp j i ip
// outer base pair and rightmost child stack
// dangle_ip dangle_i
// | |
// ( ( ) . . )
// i ip jp j
if (ignore_dangles == 0)
{
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// take dangle_en2 as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_f_b, multi: dangle_en1 = %d, dangle_en2 = %d\n", dangle_en1, dangle_en2);
if (dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return;
}
else if (flag == COAX_OTHER) //e.g two children in a multiloop (here, ip < jp here so dangle_ip is jp+1, so use dangle_top, dangle 5')
{
// dangle_i dangle_ip
// | |
// . ( ) ( ) .
// j i ip jp
if (ignore_dangles == 0)
{
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0) // the next base pair to the left of j shares the dangling end
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0) // the next base pair to the right of jp shares the dangling end
{
if (simple_dangling_ends)
{
// return the current dangle_en2
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_f_b, other: dangle_en1 = %d, dangle_en2 = %d\n", dangle_en1, dangle_en2);
if (dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return;
}
else // if (flag == COAX_PSEUDO)
{
// dangle_ip dangle_i
// | |
// ( . ( ) . )
// jp i ip j
if (ignore_dangles == 0)
{
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// leave as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_f_b, pseudo: dangle_en1 = %d, dangle_en2 = %d\n", dangle_en1, dangle_en2);
if (dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return;
}
if (DEBUG2)
printf("LEcoax_stack_energy_flush_b: coaxstack[%d][%d]{%d][%d] = %d\n", i, j, ip, jp, coaxial);
if (coaxial >= INF)
{
return;
}
counter[num_params_DP_and_pkfree + index_coax - 1]++;
return; // only case where we return coaxial (ie. use coaxial stacking)
}
void count_LEcoax_stack_energy_mismatch(int i, int j, int ip, int jp, int flag, int dangle_i, int dangle_ip, int *sequence, char* structure, int other_j, int other_jp, int& stack_dangle, double* counter, int ignore_dangles)
// Pre: ip is i+2 and jp = bp(ip) and j = bp(i); that is, i is always closest to 5' end compared to ip
// flag = COAX_MULTI, COAX_PSEUDO, or COAX_OTHER
// dangle_i corresponds to the base pair i.j
// dangle_ip corresponds to the base pair ip.jp
// Post: Returns coaxial stacking mismatch energy from Turner lab / Mathews parameters.
// stack_dangle is set to 0 or 1 to indicate whether the i or ip dangle, respectively, is involved in the stacking
//
// NOTE: all the flags work, not just COAX_PSEUDO
// Note: "structure" does not have to be the true representation (i.e. use different paranetheses for
// different bands. (In particular, do not use < or > since these have a special interpretation in
// the dangling energy function.)
{
char type[100];
int index_coax1 = -1;
int index_coax2 = -1;
int index_coax_i1 = -1;
int index_coax_ip1 = -1;
int index_coax_i2 = -1;
int index_coax_ip2 = -1;
int num_params_DP_and_pkfree = get_num_params_PK_DP();
int coaxial_i = 0;
int coaxial_ip = 0;
if (dangle_i > 0) // involve dangle_i in coaxial stack only if it's a free base
{
coaxial_i = ( coaxstack_m1 [sequence[i]] [sequence[j]] [sequence[i+1]] [sequence[dangle_i]] +
coaxstack_m2 [sequence[i+1]] [sequence[dangle_i]] [sequence[ip]] [sequence[jp]] );
sprintf(type, "coaxstack_m1[%d][%d][%d][%d]", sequence[i], sequence[j], sequence[i+1], sequence[dangle_i]);
index_coax_i1 = structure_type_index_PK_CC(type);
sprintf(type, "coaxstack_m2[%d][%d][%d][%d]", sequence[i+1], sequence[dangle_i], sequence[ip], sequence[jp]);
index_coax_i2 = structure_type_index_PK_CC(type);
}
if (dangle_ip > 0) // involve dangle_ip in coaxial stack only if it's a free base
{
coaxial_ip = ( coaxstack_m1 [sequence[jp]] [sequence[ip]] [sequence[dangle_ip]] [sequence[i+1]] +
coaxstack_m2 [sequence[i]] [sequence[j]] [sequence[i+1]] [sequence[dangle_ip]] );
sprintf(type, "coaxstack_m1[%d][%d][%d][%d]", sequence[jp], sequence[ip], sequence[dangle_ip], sequence[i+1]);
index_coax_ip1 = structure_type_index_PK_CC(type);
sprintf(type, "coaxstack_m2[%d][%d][%d][%d]", sequence[i], sequence[j], sequence[i+1], sequence[dangle_ip]);
index_coax_ip2 = structure_type_index_PK_CC(type);
}
if (DEBUG2)
{
printf("LEcoax_stack_energy_mismatch: i.j, dangle_i %d(%d).%d(%d) dangle %d(%d); ip.jp, dangle_ip %d(%d).%d(%d), dangle %d(%d); i+1 = %d(%d)\n",
i, sequence[i], j, sequence[j], dangle_i, sequence[dangle_i], ip, sequence[ip], jp, sequence[jp], dangle_ip, sequence[dangle_ip], i+1, sequence[i+1]);
printf(" coaxial_i = ");
if (dangle_i > 0)
printf("%d + %d = ", coaxstack_m1 [sequence[i]] [sequence[j]][sequence[i+1]] [sequence[dangle_i]],
coaxstack_m2 [sequence[i+1]] [sequence[dangle_i]] [sequence[ip]] [sequence[jp]], coaxial_i);
printf("%d; ", coaxial_i);
printf("coaxial_ip = ");
if (dangle_ip > 0)
printf("%d + %d = ", coaxstack_m1 [sequence[jp]] [sequence[ip]] [sequence[dangle_ip]] [sequence[i+1]],
coaxstack_m2 [sequence[i]] [sequence[j]] [sequence[i+1]] [sequence[dangle_ip]]);
printf("%d \n", coaxial_ip);
}
int coaxial = 0;
if (coaxial_i <= coaxial_ip)
{
coaxial = coaxial_i;
stack_dangle = 0; // i is part of the continuous backbone stack
index_coax1 = index_coax_i1;
index_coax2 = index_coax_i2;
}
else
{
coaxial = coaxial_ip;
stack_dangle = 1; // ip is part of the continuous backbone stack
index_coax1 = index_coax_ip1;
index_coax2 = index_coax_ip2;
}
int dangle_en0 = 0;
int dangle_en1 = 0;
int dangle_en2 = 0;
if (flag == COAX_MULTI) // between rightmost child and outer base pair of multiloop (here, ip > jp, so dangle_ip = ip - 1 and use dangle_bot, dangle 3')
{
// outer base pair and leftmost child stack
// dangle_ip dangle_i
// | |
// ( . . ( ) . )
// jp j i ip
// outer base pair and rightmost child stack
// dangle_ip dangle_i
// | |
// ( . ( ) . . )
// i ip jp j
if (ignore_dangles == 0)
{
// dangling energy of base between i and ip
if (ip < jp) // outer base pair and leftmost child stacking
dangle_en0 = s_dangling_energy_left(sequence, structure, i, j, ip, jp);
else // outer base pair and rightmost child stacking
dangle_en0 = s_dangling_energy_right(sequence, structure, ip, j, i, jp);
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// take dangle_en2 as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_mismatch, multi: dangle_en0 = %d, dangle_en1 = %d, dangle_en2 = %d\n", dangle_en0, dangle_en1, dangle_en2);
if (dangle_en0 + dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return;
}
else if (flag == COAX_OTHER) //e.g two children in a multiloop (here, ip < jp here so dangle_ip is jp+1, so use dangle_top, dangle 5')
{
// dangle_i dangle_ip
// | |
// . ( ) . ( ) .
// j i ip jp
if (ignore_dangles == 0)
{
// dangling energy of base between i and ip
dangle_en0 = s_dangling_energy(sequence, structure, j, i, ip, jp);
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0) // the next base pair to the left of j shares the dangling end
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0) // the next base pair to the right of jp shares the dangling end
{
if (simple_dangling_ends)
{
// return the current dangle_en2
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_mismatch, other: dangle_en0 = %d, dangle_en1 = %d, dangle_en2 = %d\n", dangle_en0, dangle_en1, dangle_en2);
if (dangle_en0 + dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return;
}
else // if (flag == COAX_PSEUDO)
{
// ignore danling, calculate just coaxial energy
// dangle_ip dangle_i
// | |
// ( . ( ) . )
// jp i ip j
if (ignore_dangles == 0)
{
// dangling energy of base between i and ip
dangle_en0 = s_dangling_energy(sequence, structure, j, i, ip, jp);
// NOTE: even though this is the dangling energy between two stems of a pseudoknot,
// simply using the schema shown below for the parameters of s_dangling_energy
// yields the correct result, since the dangling bases are now on the inside of
// base pairs i1.i2, i3.i4 in the implementation of s_dangling_energy
// ( ( ... ) )
// i4 i2 i3 i1
// dangling energy of unpaired base outside of i.j
if (dangle_i > 0)
{
dangle_en1 = MIN (0, dangle_bot[sequence[i]]
[sequence[j]]
[sequence[dangle_i]]);
if (other_j > 0)
{
if (simple_dangling_ends)
dangle_en1 = MIN (0, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
else
dangle_en1 = MIN (dangle_en1, dangle_top[sequence[j-2]]
[sequence[other_j]]
[sequence[j-1]]);
}
}
// dangling energy of unpaired base outside of ip.jp
if (dangle_ip > 0)
{
dangle_en2 = MIN (0, dangle_top[sequence[jp]]
[sequence[ip]]
[sequence[dangle_ip]]);
if (other_jp > 0)
{
if (simple_dangling_ends)
{
// leave as is
}
else
dangle_en2 = MIN (dangle_en2, dangle_bot[sequence[other_jp]]
[sequence[jp+2]]
[sequence[jp+1]]);
}
}
}
if (DEBUG2)
printf("LEcoax_stack_energy_mismatch, pseudo: dangle_en0 = %d, dangle_en1 = %d, dangle_en2 = %d\n", dangle_en0, dangle_en1, dangle_en2);
if (dangle_en0 + dangle_en1 + dangle_en2 <= coaxial) // if dangling bases yield lower energy, take dangling, include no coaxial stacking
return;
}
if (coaxial >= INF)
{
return;
}
if (index_coax1 == -1)
printf("ERROR: commonPK.cpp:: count_LEcoax_stack_energy_mismatch - index_coax1 == -1\n");
if (index_coax2 == -1)
printf("ERROR: commonPK.cpp:: count_LEcoax_stack_energy_mismatch - index_coax2 == -1\n");
counter[num_params_DP_and_pkfree + index_coax1 - 1]++;
counter[num_params_DP_and_pkfree + index_coax2 - 1]++;
return; // only case where we return coaxial (ie. use coaxial stacking)
}
///// END FOR PARAMETER TUNING ///////
// similar to simfold/src/s_specific_functions.cpp
int dangling_energy_res (int *sequence, int i1, int i2, int i3, int i4, int d_12, int d_34)
// ( )...( )
// i1..i2..i3..i4
// PRE: (i1, i2) and (i3, i4) are pairs, i2 and i3 are neighbours, i2 < i3
// d_12 = dangling end corresponding to base pair i1.i2
// d_34 = dangling end corresponding to base pair 13.i4
// similar to dangling_energy() if d_12 or d_13 are 1, they will be consider as restricted
// and not included in the dangling calculation
// POST: return dangling energy between i2 and i3
{
int energy;
int d_top, d_bot;
d_top = 0;
d_bot = 0;
if (d_12 == 1)
d_top = 0;
else
d_top = MIN (0, dangle_top[sequence[i2]]
[sequence[i1]]
[sequence[i2+1]]);
if (d_34 == 1)
d_bot = 0;
else
d_bot = MIN (0, dangle_bot[sequence[i4]]
[sequence[i3]]
[sequence[i3-1]]);
if (DEBUG2)
printf("dangling_energy_res: d_top(%d) = %d, d_bot(%d) = %d\n", i2+1, d_top, i3-1, d_bot);
if (i2+1 == i3-1) // see which is smaller
{
if (simple_dangling_ends)
energy = d_top;
else
energy = d_top < d_bot ? d_top : d_bot;
}
else if (i2+1 < i3-1)
{
energy = d_top + d_bot;
}
else // if there is no free base between the two branches, return 0
energy = 0;
return energy;
}
// similar to simfold/src/s_specific_functions.cpp
int dangling_energy_left_res (int *sequence, int i1, int i2, int i3, int i4, int d_12, int d_34)
// (....( ) )
// i1 i3 i4 i2
// PRE: (i1, i2) and (i3, i4) are pairs, i1 and i3 are neighbours, i3 < i2
// d_12 = dangling end corresponding to base pair i1.i2
// d_34 = dangling end corresponding to base pair 13.i4
// similar to dangling_energy_left() if d_12 or d_13 are 1, they will be consider as restricted
// and not included in the dangling calculation
// POST: return dangling energy between i1 and i3
{
int energy;
int d_top, d_bot;
d_top = 0;
d_bot = 0;
if (d_12 == 1)
d_top = 0;
else
d_top = MIN (0, dangle_top[sequence[i1]]
[sequence[i2]]
[sequence[i1+1]]);
if (d_34 == 1)
d_bot = 0;
else
d_bot = MIN (0, dangle_bot[sequence[i4]]
[sequence[i3]]
[sequence[i3-1]]);
if (DEBUG2)
printf("dangling_energy_left_res: d_top(%d) = %d, d_bot(%d) = %d\n", i1+1, d_top, i3-1, d_bot);
if (i1+1 == i3-1) // see which is smaller
{
if (simple_dangling_ends)
energy = d_top;
else
energy = d_top < d_bot ? d_top : d_bot;
}
else if (i1+1 < i3-1)
{
energy = d_top + d_bot;
}
else // if there is no free base between the two branches, return 0
energy = 0;
return energy;
}
// similar to simfold/src/s_specific_functions.cpp
int dangling_energy_right_res (int *sequence, int i1, int i2, int i3, int i4, int d_12, int d_34)
// ( ( )...)
// i1 i3 i4 i2
// d_12 = dangling end corresponding to base pair i1.i2
// d_34 = dangling end corresponding to base pair 13.i4
// similar to dangling_energy_right() if d_12 or d_13 are 1, they will be consider as restricted
// and not included in the dangling calculation
// PRE: (i1, i2) and (i3, i4) are pairs, i1 and i3 are neighbours, i3 < i2
// POST: return dangling energy between i4 and i2
{
int energy;
int d_top, d_bot;
d_top = 0;
d_bot = 0;
if (d_34 == 1)
d_top = 0;
else
d_top = MIN (0, dangle_top[sequence[i4]]
[sequence[i3]]
[sequence[i4+1]]);
if (d_12 == 1)
d_bot = 0;
else
d_bot = MIN (0, dangle_bot[sequence[i1]]
[sequence[i2]]
[sequence[i2-1]]);
if (DEBUG2)
printf("dangling_energy_right_res: d_top(%d) = %d, d_bot(%d) = %d\n", i4+1, d_top, i2-1, d_bot);
if (i4+1 == i2-1) // see which is smaller
{
if (simple_dangling_ends)
energy = d_top;
else
energy = d_top < d_bot ? d_top : d_bot;
}
else if (i4+1 < i2-1)
{
energy = d_top + d_bot;
}
else // if there is no free base between the two branches, return 0
energy = 0;
return energy;
}
// NOT USED: only handles two types of brackets
void detect_original_PKed_pairs_limited(char *structure, int *p_table)
// PRE: structure contains the desired structure
// POST: pairs will contain the index of each base pair
// or -1 if it does not pair
{
int i, j, struct_len;
stack_ds st; //stach used for (
stack_ds st_brack; // stack used for [
h_init (&st);
h_init (&st_brack);
/******************************************
** ASK MIRELA
*******************************************/
//remove_space (structure);
//printf("remove_space done \n");
/*****************************************/
struct_len = strlen (structure);
for (i=0; i <= struct_len; i++)
{
if (i == 0){
p_table[i] = 0;
}
else if (structure[i-1] == '.'){
p_table[i] = 0;
}
else if (structure[i-1] == '_'){
p_table[i] = 0;
}
else if (structure[i-1] == '('){
h_push (&st, i);
}
else if (structure[i-1] == '['){
h_push (&st_brack, i);
}
else if (structure[i-1] == ')')
{
j = h_pop (&st);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == ']')
{
j = h_pop (&st_brack);
p_table[i] = j;
p_table[j] = i;
}
}
if (st.top != 0 || st_brack.top != 0)
{
fprintf (stderr, "detect_orignal_PKed_pairs_limited::The given structure is not valid: %d more left parenthesis than right parentheses\n", st.top);
exit (1);
}
}
// handles 30 types of brackets
void detect_original_PKed_pairs_many (char *structure, short* p_table)
{
int i, j, struct_len;
// Assume brackets appear in the following order:
//my @pk_left = ('(','[','{','<','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
//my @pk_right = (')',']','}','>','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
char bl[] = "([{<ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char br[] = ")]}>abcdefghijklmnopqrstuvwxyz";
stack_ds st1; // (
stack_ds st2; // [
stack_ds st3; // {
stack_ds st4; // <
stack_ds st5; // a
stack_ds st6; // b
stack_ds st7; // c
stack_ds st8; // d
stack_ds st9; // e
stack_ds st10; // f
stack_ds st11; // g
stack_ds st12; // h
stack_ds st13; // i
stack_ds st14; // j
stack_ds st15; // k
stack_ds st16; // l
stack_ds st17; // m
stack_ds st18; // n
stack_ds st19; // o
stack_ds st20; // p
stack_ds st21; // q
stack_ds st22; // r
stack_ds st23; // s
stack_ds st24; // t
stack_ds st25; // u
stack_ds st26; // v
stack_ds st27; // w
stack_ds st28; // x
stack_ds st29; // y
stack_ds st30; // z
h_init (&st1);
h_init (&st2);
h_init (&st3);
h_init (&st4);
h_init (&st5);
h_init (&st6);
h_init (&st7);
h_init (&st8);
h_init (&st9);
h_init (&st10);
h_init (&st11);
h_init (&st12);
h_init (&st13);
h_init (&st14);
h_init (&st15);
h_init (&st16);
h_init (&st17);
h_init (&st18);
h_init (&st19);
h_init (&st20);
h_init (&st21);
h_init (&st22);
h_init (&st23);
h_init (&st24);
h_init (&st25);
h_init (&st26);
h_init (&st27);
h_init (&st28);
h_init (&st29);
h_init (&st30);
struct_len = strlen (structure);
for (i=0; i <= struct_len; i++)
{
//printf("Analyzing %d, character %c\n",i,structure[i-1]);
if (i == 0){
p_table[i] = 0;
}
else if (structure[i-1] == '.'){
p_table[i] = 0;
}
else if (structure[i-1] == '_'){
p_table[i] = 0;
}
else if (structure[i-1] == bl[0]){
//printf("Pushing %c ( for i = %d\n",structure[i-1],i);
h_push (&st1, i);
}
else if (structure[i-1] == bl[1]){
//printf("Pushing %c [ for i = %d\n",structure[i-1],i);
h_push (&st2, i);
}
else if (structure[i-1] == bl[2]){
h_push (&st3, i);
}
else if (structure[i-1] == bl[3]){
h_push (&st4, i);
}
else if (structure[i-1] == bl[4]){
h_push (&st5, i);
}
else if (structure[i-1] == bl[5]){
h_push (&st6, i);
}
else if (structure[i-1] == bl[6]){
h_push (&st7, i);
}
else if (structure[i-1] == bl[7]){
h_push (&st8, i);
}
else if (structure[i-1] == bl[8]){
h_push (&st9, i);
}
else if (structure[i-1] == bl[9]){
h_push (&st10, i);
}
else if (structure[i-1] == bl[10]){
h_push (&st11, i);
}
else if (structure[i-1] == bl[11]){
h_push (&st12, i);
}
else if (structure[i-1] == bl[12]){
h_push (&st13, i);
}
else if (structure[i-1] == bl[13]){
h_push (&st14, i);
}
else if (structure[i-1] == bl[14]){
h_push (&st15, i);
}
else if (structure[i-1] == bl[15]){
h_push (&st16, i);
}
else if (structure[i-1] == bl[16]){
h_push (&st17, i);
}
else if (structure[i-1] == bl[17]){
h_push (&st18, i);
}
else if (structure[i-1] == bl[18]){
h_push (&st19, i);
}
else if (structure[i-1] == bl[19]){
h_push (&st20, i);
}
else if (structure[i-1] == bl[20]){
h_push (&st21, i);
}
else if (structure[i-1] == bl[21]){
h_push (&st22, i);
}
else if (structure[i-1] == bl[22]){
h_push (&st23, i);
}
else if (structure[i-1] == bl[23]){
h_push (&st24, i);
}
else if (structure[i-1] == bl[24]){
h_push (&st25, i);
}
else if (structure[i-1] == bl[25]){
h_push (&st26, i);
}
else if (structure[i-1] == bl[26]){
h_push (&st27, i);
}
else if (structure[i-1] == bl[27]){
h_push (&st28, i);
}
else if (structure[i-1] == bl[28]){
h_push (&st29, i);
}
else if (structure[i-1] == bl[29]){
h_push (&st30, i);
}
else if (structure[i-1] == br[0]){
//printf("Popping %c )",structure[i-1]);
j = h_pop (&st1);
//printf(" for pair %d.%d\n",i,j);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[1]){
//printf("Popping %c ]",structure[i-1]);
j = h_pop (&st2);
//printf(" for pair %d.%d\n",i,j);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[2]){
j = h_pop (&st3);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[3]){
j = h_pop (&st4);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[4]){
j = h_pop (&st5);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[5]){
j = h_pop (&st6);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[6]){
j = h_pop (&st7);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[7]){
j = h_pop (&st8);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[8]){
j = h_pop (&st9);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[9]){
j = h_pop (&st10);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[10]){
j = h_pop (&st11);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[11]){
j = h_pop (&st12);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[12]){
j = h_pop (&st13);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[13]){
j = h_pop (&st14);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[14]){
j = h_pop (&st15);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[15]){
j = h_pop (&st16);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[16]){
j = h_pop (&st17);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[17]){
j = h_pop (&st18);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[18]){
j = h_pop (&st19);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[19]){
j = h_pop (&st20);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[20]){
j = h_pop (&st21);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[21]){
j = h_pop (&st22);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[22]){
j = h_pop (&st23);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[23]){
j = h_pop (&st24);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[24]){
j = h_pop (&st25);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[25]){
j = h_pop (&st26);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[26]){
j = h_pop (&st27);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[27]){
j = h_pop (&st28);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[28]){
j = h_pop (&st29);
p_table[i] = j;
p_table[j] = i;
}
else if (structure[i-1] == br[29]){
j = h_pop (&st30);
p_table[i] = j;
p_table[j] = i;
}
}
if (st1.top != 0 || st2.top != 0 || st3.top != 0 || st4.top != 0 || st5.top != 0 || st6.top != 0 || st7.top != 0
|| st8.top != 0 || st9.top != 0 || st10.top != 0 || st11.top != 0 || st12.top != 0 || st13.top != 0
|| st14.top != 0 || st15.top != 0 || st16.top != 0 || st17.top != 0 || st18.top != 0 || st19.top != 0
|| st20.top != 0 || st21.top != 0 || st22.top != 0 || st23.top != 0 || st24.top != 0 || st25.top != 0
|| st26.top != 0 || st27.top != 0 || st28.top != 0 || st29.top != 0 || st30.top != 0)
{
fprintf (stderr, "detect_original_PKed_pairs_many::The given structure is not valid: more left parenthesis than right parentheses\n");
exit (1);
}
}
void h_init (stack_ds *st)
// PRE: None
// POST: Initialize the stack st
{
st->top = 0;
}
void h_push (stack_ds *st, int el)
// PRE: st is a valid stack
// POST: Push an element to the stack
{
st->top = st->top +1;
st->elem[st->top] = el;
}
int h_pop (stack_ds *st)
// PRE: st is a valid stack, that is not empty
// POST: pop an element from the stack and return it
{
if (st->top <= 0)
{
fprintf (stderr, "h_pop::The given structure is not valid: more right parentheses than left parentheses\n");
exit (1);
}
int result = st->elem[st->top];
st->top = st->top -1 ;
return result;
}
int structure_type_index_PK(char type[])
{
// FOR DP ENERGY MODEL
// Assume the input type[] (left column) means the following (right column):
// ps: # double Ps; // pseudoloop initiation energy
// psm: # double Psm; // penalty for introducing pseudoknot inside a multiloop
// psp: # double Psp; // penalty for introducting pseudoknot inside a pseudoloop
// pb: # double Pb; // penalty for band
// pup: # double Pup; // penalty for unpaired base in pseudoloop or band
// pps: # double Pps; // penalty for nested closed region inside a pseudoloop
// stp: # double stP; // multiplicative penalty for stacked pair that spans a band
// intp: # double intP; // multiplicative penalty for internal loop that spans a band
// a: # double a;
// b: # double b;
// c: # double c;
// a_p: # double a_p; // penalty for introducing a multiloop that spans a band
// b_p: # double b_p; // penalty for multiloop base pair when the multiloop spans a band
// c_p: # double c_p; // penalty for unpaired base in multiloop that spans a band
if (type[0] == 'p')
{
if (type[1] == 's')
{
if (type[2] == '\0')
return 1;
if (type[2] == 'm')
return 2;
if (type[2] == 'p')
return 3;
}
if (type[1] == 'b')
return 4;
if (type[1] == 'u')
return 5;
if (type[1] == 'p')
return 6;
}
if (type[0] == 's')
return 7; // stP
if (type[0] == 'i')
return 8; // intP
if (type[0] == 'a')
{
if (type[1] == '\0')
return 9; // a
else
return 12; // a_p
}
if (type[0] == 'b')
{
if (type[1] == '\0')
return 10; // b
else
return 13; // b_p
}
if (type[0] == 'c')
{
if (type[1] == '\0')
return 11; // c
else
return 14; // c_p
}
printf("ERROR: invalid input to structure_type_index_PK: %s\n", type);
}
// fills an array string_params_PK_CC with readable form of the parameters
// used in the CC2006b model, in order that they appear in a list of
// parameters used for parameter tuning
void create_string_params_PK_CC()
{
// coaxial stacking parameters are first
// assumes parameters are in this order:
// coaxstack_f_b
// coaxstack_m1
// coaxstack_m2
int index = 0;
int i,j,k,l;
for (i=0; i < NUCL; i++) {
for (j=0; j < NUCL; j++) {
for (k=0; k < NUCL; k++) {
for (l=0; l < NUCL; l++)
{
if (coaxstack_f_b[i][j][k][l] < INF)
{
sprintf(string_params_PK_CC[index],"coaxstack_f_b[%d][%d][%d][%d]",i,j,k,l);
index++;
}
}
}
}
}
for (i=0; i < NUCL; i++) {
for (j=0; j < NUCL; j++) {
for (k=0; k < NUCL; k++) {
for (l=0; l < NUCL; l++)
{
if (coaxstack_m1[i][j][k][l] < INF)
{
sprintf(string_params_PK_CC[index],"coaxstack_m1[%d][%d][%d][%d]",i,j,k,l);
index++;
}
}
}
}
}
for (i=0; i < NUCL; i++) {
for (j=0; j < NUCL; j++) {
for (k=0; k < NUCL; k++) {
for (l=0; l < NUCL; l++)
{
if (coaxstack_m2[i][j][k][l] < INF)
{
sprintf(string_params_PK_CC[index],"coaxstack_m2[%d][%d][%d][%d]",i,j,k,l);
index++;
}
}
}
}
}
// read the CC2006b energy model parameters
// assumes the parameters are in this order:
// cc2006_s2_l1, cc2006_s1_l2, cc2006_s2_formula, cc2006_s1_formula
for (i=0; i < CC2006_STEMSIZE; i++) {
for (j=0; j < CC2006_LOOPSIZE; j++) {
if (cc2006_s2_l1[i][j] < INF)
{
sprintf(string_params_PK_CC[index],"cc2006_s2_l1[%d][%d]",i,j);
index++;
}
}
}
for (i=0; i < CC2006_STEMSIZE; i++) {
for (j=0; j < CC2006_LOOPSIZE; j++) {
if (cc2006_s1_l2[i][j] < INF)
{
sprintf(string_params_PK_CC[index],"cc2006_s1_l2[%d][%d]",i,j);
index++;
}
}
}
for (i=1; i < 4; i++) { // ignore the first row (l_min, which is not a parameter to be changed)
for (j=0; j < CC2006_STEMSIZE_FORMULA; j++) {
if (cc2006_s2_formula[i][j] < INF)
{
sprintf(string_params_PK_CC[index],"cc2006_s2_formula[%d][%d]",i,j);
index++;
}
}
}
for (i=1; i < 4; i++) { // ignore the first row (l_min, which is not a parameter to be changed)
for (j=0; j < CC2006_STEMSIZE_FORMULA; j++) {
if (cc2006_s1_formula[i][j] < INF)
{
sprintf(string_params_PK_CC[index],"cc2006_s1_formula[%d][%d]",i,j);
index++;
}
}
}
}
int structure_type_index_PK_CC(char type[])
{
int i = 0;
int start = 0;
int found = 0;
// only coaxial, CC model params, not the DP model params
int num_params = get_num_params_PK_CC2006b() - get_num_params_PK_DP();
// FOR CC ENERGY MODEL (DP model not included)
// Assumes coaxial stacking params come first, starting from index 1
for (i=start; i < num_params; i++)
{
if (strcmp (type, string_params_PK_CC[i]) == 0)
{
found = 1;
//printf ("%s found in %d steps\n", type, i-start+1);
break;
}
}
if (!found)
{
printf ("ERROR: commonPK.cpp:: structure_type_index_PK_CC - type not found: %s!!!\n", type);
exit(1);
}
return i+1;
}
// from simfold/init.cpp
double ascii_to_doublePK (char *string)
// PRE: string is either in float format or it is a '.'
// POST: convert in infinity (INF) if it is '.', in a float otherwise
{
char *ptr;
double en;
if (strcmp(string,".") == 0)
return INF;
en = strtod(string, &ptr);
return en;
}
// from simfold/init.cpp
int ascii_to_intPK (char *string)
// PRE: string is either in float format or it is a '.'
// POST: convert in infinity (INF) if it is '.', in a float otherwise
{
char *ptr;
double en;
if (strcmp(string,".") == 0)
return INF;
en = strtod(string, &ptr);
if (en < 0) en -= EPSILON;
else en += EPSILON;
return (int) (en*100);
}
// from simfold/init.cpp with my own additions for CC model
// converts input to int then multiplies by 100, then multiplies by multiplier
double ascii_to_CCdouble_PK (char *string, double multiplier)
// PRE: string is either in float format or it is a '.'
// POST: convert in infinity (INF) if it is '.', in a float otherwise
{
char *ptr;
double en;
if (strcmp(string,".") == 0)
return INF;
en = strtod(string, &ptr);
if (en < 0) en -= EPSILON;
else en += EPSILON;
return multiplier * (int) (en*100);
}
// from simfold/init.cpp
void giveupPK (char *string1, char *string2)
// to add: variable nb of parameters, as in scanf, printf
{
char temp[100];
sprintf (temp, "%s %s", string1, string2);
perror (temp);
exit(1);
}
double compute_PK_sensitivity (char *ref_structure, char *pred_structure)
// returns 0 if undefined (denominator is 0)
{
short ptable_ref[MaxN];
short ptable_pred[MaxN];
int len, i;
double sens;
int num_correct_bp;
int num_true_bp;
len = strlen(ref_structure);
// change ref_structure to bpseq
detect_original_PKed_pairs_many (ref_structure, ptable_ref);
// change pred_structure to bpseq
detect_original_PKed_pairs_many (pred_structure, ptable_pred);
num_correct_bp = 0;
num_true_bp = 0;
// Mirela: for some reason, detect_original_PKed_pairs_many starts from 1, and has everything incremented by 1
// So modify below accordingly.
//for (i=0; i < len; i++)
for (i=1; i <= len; i++)
{
//if (ptable_ref[i] > -1) // paired base
if (ptable_ref[i] > 0) // paired base
{
num_true_bp++;
if (ptable_pred[i] == ptable_ref[i])
num_correct_bp++;
}
}
if (num_true_bp == 0)
return -1.0;
sens = num_correct_bp*1.0/num_true_bp;
return sens;
}
double compute_PK_ppv (char *ref_structure, char *pred_structure)
// returns 0 if undefined (denominator is 0)
{
short ptable_ref[MAXSLEN];
short ptable_pred[MAXSLEN];
int len, i;
double ppv;
int num_correct_bp;
int num_pred_bp;
len = strlen(ref_structure);
// change ref_structure to bpseq
detect_original_PKed_pairs_many (ref_structure, ptable_ref);
// change pred_structure to bpseq
detect_original_PKed_pairs_many (pred_structure, ptable_pred);
num_correct_bp = 0;
num_pred_bp = 0;
// Mirela: for some reason, detect_original_PKed_pairs_many starts from 1, and has everything incremented by 1
// So modify below accordingly.
//for (i=0; i < len; i++)
for (i=1; i <= len; i++)
{
//if (ptable_ref[i] > -1 && ptable_pred[i] == ptable_ref[i]) // paired base
if (ptable_ref[i] > 0 && ptable_pred[i] == ptable_ref[i]) // paired base
num_correct_bp++;
//if (ptable_pred[i] > -1) // paired base
if (ptable_pred[i] > 0) // paired base
num_pred_bp++;
}
if (num_pred_bp == 0)
return -1.0;
ppv = num_correct_bp*1.0/num_pred_bp;
return ppv;
}
///////////// FUNCTIONS FROM SIMFOLD ///////////////////
// count_dangling_energy from params.cpp
void count_LEdangling_energy (int *sequence, char *structure, int link, int i1, int i2, int i3, int i4, double *counter)
// ( )...( )
// i1..i2..i3..i4
// PRE: (i1, i2) and (i3, i4) are pairs, i2 and i3 are neighbours, i2 < i3
// POST: return dangling energy between i2 and i3
// Mirela: Nov 23, 2003
// Feb 28, 2008. We might have a situation like this: < >...( ) or like this: ( )...< >.
// In that case, only add the parameter dangling onto the () pair, if it's at least 2 unpaired bases away
{
PARAMTYPE energy;
PARAMTYPE d_top, d_bot;
char type[100];
int index_top, index_bot;
int first_index; // first index should be dangle_top[0][3][0]
first_index = structure_type_index ("dangle_top[0][3][0]");
d_top = 0;
d_bot = 0;
if (i2 != link && structure[i2] != '>')
{
//d_top = MIN (0, IGINF(dangle_top[sequence[i2]][sequence[i1]][sequence[i2+1]]));
d_top = dangle_top[sequence[i2]] [sequence[i1]] [sequence[i2+1]];
sprintf (type, "dangle_top[%d][%d][%d]",sequence[i2], sequence[i1], sequence[i2+1]);
index_top = structure_type_index (type);
}
if (i3-1 != link && structure[i3] != '<')
{
//d_bot = MIN (0, IGINF(dangle_bot[sequence[i4]] [sequence[i3]] [sequence[i3-1]]));
d_bot = dangle_bot[sequence[i4]] [sequence[i3]] [sequence[i3-1]];
sprintf (type, "dangle_bot[%d][%d][%d]",sequence[i4], sequence[i3], sequence[i3-1]);
index_bot = structure_type_index (type);
}
if (structure[i2] == '>' && structure[i3] == '(') // pseudoknot, ignore dangling end dangling on it
{
if (i3 <= i2+2) // >.( or >( ignore completely
energy = 0;
else // >...(
{
energy = d_bot;
counter[index_bot]++;
}
}
else if (structure[i2] == ')' && structure[i3] == '<') // pseudoknot, ignore dangling end dangling on it
{
if (i3 <= i2+2) // ).< or )< ignore completely
energy = 0;
else // )...<
{
energy = d_top;
counter[index_top]++;
}
}
else if (structure[i2] == '>' && structure[i3] == '<') // case >..< ignore completely
{
energy = 0;
}
else if (i2+1 == i3-1 && i2 == link)
{
energy = d_bot;
counter[index_bot]++;
}
else if (i2+1 == i3-1 && i3-1 == link)
{
energy = d_top;
counter[index_top]++;
}
else if (i2+1 == i3-1) // see which is smaller
{
//energy = d_top < d_bot ? d_top : d_bot;
// NOTE: the comparison of d_top with d_bot is not right!
// NO! This is not right if we don't know which of d_top and d_bot is smaller
// if we restrict the 3' dangling ends to be less than the 5' ones, then it's ok to do what follows
// if we fix the dangling ends to the Turner parameters, we have to count this
//if (d_top < d_bot) counter[index_top]++;
//else counter[index_bot]++;
if (simple_dangling_ends)
{
energy = d_top;
counter[index_top]++;
}
else
{
if (d_top < d_bot)
{
energy = d_top;
counter[index_top]++;
}
else
{
energy = d_bot;
counter[index_bot]++;
}
}
// if we introduce another variable as min, we need to do this
//counter_min_dangle[index_top-first_index][index_bot-first_index]++;
}
else if (i2+1 < i3-1)
{
energy = d_top + d_bot;
counter[index_top]++;
counter[index_bot]++;
}
else // if there is no free base between the two branches, return 0
energy = 0;
// return energy;
}
void count_LEdangling_energy_left (int *sequence, char *structure, int link, int i1, int i2, int i3, int i4, double *counter)
// (....( ) )
// i1 i3 i4 i2
// PRE: (i1, i2) and (i3, i4) are pairs, i1 and i3 are neighbours, i3 < i2
// POST: return dangling energy between i1 and i3
// Mirela: Nov 23, 2003
// Feb 28, 2008. We might have a situation like this: (....< > ). In that case, only add the 3' dangling end.
// If it's (.< > ), don't add any
{
PARAMTYPE energy;
PARAMTYPE d_top, d_bot;
char type[100];
int index_top, index_bot;
d_top = 0;
d_bot = 0;
int first_index; // first index should be dangle_top[0][3][0]
first_index = structure_type_index ("dangle_top[0][3][0]");
// this will be used in multi-loops.
// add the dangle_top, even if it is positive
if (i1 != link)
{
//d_top = MIN (0, IGINF(dangle_top[sequence[i1]] [sequence[i2]] [sequence[i1+1]]));
d_top = dangle_top[sequence[i1]] [sequence[i2]] [sequence[i1+1]];
sprintf (type, "dangle_top[%d][%d][%d]",sequence[i1], sequence[i2], sequence[i1+1]);
index_top = structure_type_index (type);
}
// in the other parts of the multi-loop, the dangles are added only if they are negative
if (i3-1 != link && structure[i3] != '<')
{
//d_bot = MIN (0, IGINF(dangle_bot[sequence[i4]] [sequence[i3]] [sequence[i3-1]]));
d_bot = dangle_bot[sequence[i4]] [sequence[i3]] [sequence[i3-1]];
sprintf (type, "dangle_bot[%d][%d][%d]",sequence[i4], sequence[i3], sequence[i3-1]);
index_bot = structure_type_index (type);
}
if (structure[i3] == '<') // pseudoknot inside, ignore dangling end dangling on it
{
if (i3 <= i1+2) // (< or (.<, ignore completely
energy = 0;
else // (....<
{
energy = d_top;
counter[index_top]++;
}
}
else if (i1+1 == i3-1 && i1 == link)
{
energy = d_bot;
counter[index_bot]++;
}
else if (i1+1 == i3-1 && i3-1 == link)
{
energy = d_top;
counter[index_top]++;
}
else if (i1+1 == i3-1) // see which is smaller
{
//energy = d_top < d_bot ? d_top : d_bot;
// NOTE: the comparison of d_top with d_bot is not right!
//if (d_top < d_bot) counter[index_top]++;
//else counter[index_bot]++;
//counter_min_dangle[index_top-first_index][index_bot-first_index]++;
if (simple_dangling_ends)
{
energy = d_top;
counter[index_top]++;
}
else
{
if (d_top < d_bot)
{
energy = d_top;
counter[index_top]++;
}
else
{
energy = d_bot;
counter[index_bot]++;
}
}
}
else if (i1+1 < i3-1)
{
energy = d_top + d_bot;
counter[index_top]++;
counter[index_bot]++;
}
else // if there is no free base between the two branches, return 0
energy = 0;
// return energy;
}
void count_LEdangling_energy_right (int *sequence, char *structure, int link, int i1, int i2, int i3, int i4, double *counter)
// ( ( )...)
// i1 i3 i4 i2
// PRE: (i1, i2) and (i3, i4) are pairs, i1 and i3 are neighbours, i3 < i2
// POST: return dangling energy between i4 and i2
// Mirela: Nov 23, 2003
// Feb 28, 2008. We might have a situation like this: ( < >...)
// In that case, only add the 5' dangling end if it's at least two unpaired bases away
{
PARAMTYPE energy;
PARAMTYPE d_top, d_bot;
char type[100];
int index_top, index_bot;
int first_index; // first index should be dangle_top[0][3][0]
first_index = structure_type_index ("dangle_top[0][3][0]");
d_top = 0;
d_bot = 0;
if (i4 != link && structure[i3] != '<')
{
//d_top = MIN (0, IGINF(dangle_top[sequence[i4]] [sequence[i3]] [sequence[i4+1]]));
d_top = dangle_top[sequence[i4]] [sequence[i3]] [sequence[i4+1]];
sprintf (type, "dangle_top[%d][%d][%d]",sequence[i4], sequence[i3], sequence[i4+1]);
index_top = structure_type_index (type);
}
if (i2-1 != link)
{
//d_bot = MIN (0, IGINF(dangle_bot[sequence[i1]] [sequence[i2]] [sequence[i2-1]]));
d_bot = dangle_bot[sequence[i1]] [sequence[i2]] [sequence[i2-1]];
sprintf (type, "dangle_bot[%d][%d][%d]",sequence[i1], sequence[i2], sequence[i2-1]);
index_bot = structure_type_index (type);
}
if (structure[i4] == '>') // pseudoknot inside, ignore dangling end dangling on it
{
if (i2 <= i4+2) // >.) or >) ignore completely
energy = 0;
else // >...)
{
energy = d_bot;
counter[index_bot]++;
}
}
else if (i4+1 == i2-1 && i4 == link)
{
energy = d_bot;
counter[index_bot]++;
}
else if (i4+1 == i2-1 && i2-1 == link)
{
energy = d_top;
counter[index_top]++;
}
else if (i4+1 == i2-1) // see which is smaller
{
//energy = d_top < d_bot ? d_top : d_bot;
// NOTE: the comparison of d_top with d_bot is not right!
//if (d_top < d_bot) counter[index_top]++;
//else counter[index_bot]++;
//counter_min_dangle[index_top-first_index][index_bot-first_index]++;
if (simple_dangling_ends)
{
energy = d_top;
counter[index_top]++;
}
else
{
if (d_top < d_bot)
{
energy = d_top;
counter[index_top]++;
}
else
{
energy = d_bot;
counter[index_bot]++;
}
}
}
else if (i4+1 < i2-1)
{
energy = d_top + d_bot;
counter[index_top]++;
counter[index_bot]++;
}
else // if there is no free base between the two branches, return 0
energy = 0;
// return energy;
}
| mit |
layabox/layaair | src/layaAir/laya/ui/View.ts | 8283 | import { Widget } from "./Widget";
import { Animation } from "../display/Animation"
import { Scene } from "../display/Scene"
import { Sprite } from "../display/Sprite"
import { Text } from "../display/Text"
import { Event } from "../events/Event"
import { Box } from "./Box"
import { Button } from "./Button"
import { CheckBox } from "./CheckBox"
import { Image } from "./Image"
import { Label } from "./Label"
import { ProgressBar } from "./ProgressBar"
import { Radio } from "./Radio"
import { RadioGroup } from "./RadioGroup"
import { Tab } from "./Tab"
import { UIComponent } from "./UIComponent"
import { ViewStack } from "./ViewStack";
import { TextArea } from "./TextArea";
import { ColorPicker } from "./ColorPicker";
import { ScaleBox } from "./ScaleBox";
import { Clip } from "./Clip";
import { ComboBox } from "./ComboBox";
import { HScrollBar } from "./HScrollBar";
import { HSlider } from "./HSlider";
import { List } from "./List";
import { Panel } from "./Panel";
import { ScrollBar } from "./ScrollBar";
import { Slider } from "./Slider";
import { TextInput } from "./TextInput";
import { VScrollBar } from "./VScrollBar";
import { VSlider } from "./VSlider";
import { Tree } from "./Tree";
import { HBox } from "./HBox";
import { VBox } from "./VBox";
import { FontClip } from "./FontClip";
import { ILaya } from "../../ILaya";
import { ClassUtils } from "../utils/ClassUtils";
/**
* <code>View</code> 是一个视图类,2.0开始,更改继承至Scene类,相对于Scene,增加相对布局功能。
*/
export class View extends Scene {
/**@private 兼容老版本*/
static uiMap: any = {};
/**@internal */
_watchMap: any = {};
/**@private 相对布局组件*/
protected _widget: Widget;
/**@private 控件的数据源。 */
protected _dataSource: any;
/**X锚点,值为0-1,设置anchorX值最终通过pivotX值来改变节点轴心点。*/
protected _anchorX: number = NaN;
/**Y锚点,值为0-1,设置anchorY值最终通过pivotY值来改变节点轴心点。*/
protected _anchorY: number = NaN;
static __init__(): void {
ILaya.ClassUtils.regShortClassName([ViewStack, Button, TextArea, ColorPicker, Box, ScaleBox, CheckBox, Clip, ComboBox, UIComponent,
HScrollBar, HSlider, Image, Label, List, Panel, ProgressBar, Radio, RadioGroup, ScrollBar, Slider, Tab, TextInput, View, /*Dialog,*/
VScrollBar, VSlider, Tree, HBox, VBox, Animation, Text, FontClip]);
}
constructor() {
super(false); // 先不要createChildren 因为 this._widget还没有赋值
this._widget = Widget.EMPTY;
this.createChildren();
}
/**
* @private 兼容老版本
* 注册组件类映射。
* <p>用于扩展组件及修改组件对应关系。</p>
* @param key 组件类的关键字。
* @param compClass 组件类对象。
*/
static regComponent(key: string, compClass: new () => any): void {
ILaya.ClassUtils.regClass(key, compClass);
}
/**
* @private 兼容老版本
* 注册UI视图类的逻辑处理类。
* 注册runtime解析。
* @param key UI视图类的关键字。
* @param compClass UI视图类对应的逻辑处理类。
*/
static regViewRuntime(key: string, compClass: new () => any): void {
ILaya.ClassUtils.regClass(key, compClass);
}
/**
* @private 兼容老版本
* 注册UI配置信息,比如注册一个路径为"test/TestPage"的页面,UI内容是IDE生成的json
* @param url UI的路径
* @param json UI内容
*/
static regUI(url: string, json: any): void {
ILaya.loader.cacheRes(url, json);
}
/**
* @inheritDoc
* @override
*/
/*override*/ destroy(destroyChild: boolean = true): void {
this._watchMap = null;
super.destroy(destroyChild);
}
/**@private */
changeData(key: string): void {
var arr: any[] = this._watchMap[key];
if (!arr) return;
for (var i: number = 0, n: number = arr.length; i < n; i++) {
var watcher: any = arr[i];
watcher.exe(this);
}
}
/**
* <p>从组件顶边到其内容区域顶边之间的垂直距离(以像素为单位)。</p>
*/
get top(): number {
return this._widget.top;
}
set top(value: number) {
if (value != this._widget.top) {
this._getWidget().top = value;
}
}
/**
* <p>从组件底边到其内容区域底边之间的垂直距离(以像素为单位)。</p>
*/
get bottom(): number {
return this._widget.bottom;
}
set bottom(value: number) {
if (value != this._widget.bottom) {
this._getWidget().bottom = value;
}
}
/**
* <p>从组件左边到其内容区域左边之间的水平距离(以像素为单位)。</p>
*/
get left(): number {
return this._widget.left;
}
set left(value: number) {
if (value != this._widget.left) {
this._getWidget().left = value;
}
}
/**
* <p>从组件右边到其内容区域右边之间的水平距离(以像素为单位)。</p>
*/
get right(): number {
return this._widget.right;
}
set right(value: number) {
if (value != this._widget.right) {
this._getWidget().right = value;
}
}
/**
* <p>在父容器中,此对象的水平方向中轴线与父容器的水平方向中心线的距离(以像素为单位)。</p>
*/
get centerX(): number {
return this._widget.centerX;
}
set centerX(value: number) {
if (value != this._widget.centerX) {
this._getWidget().centerX = value;
}
}
/**
* <p>在父容器中,此对象的垂直方向中轴线与父容器的垂直方向中心线的距离(以像素为单位)。</p>
*/
get centerY(): number {
return this._widget.centerY;
}
set centerY(value: number) {
if (value != this._widget.centerY) {
this._getWidget().centerY = value;
}
}
/**X锚点,值为0-1,设置anchorX值最终通过pivotX值来改变节点轴心点。*/
get anchorX(): number {
return this._anchorX;
}
set anchorX(value: number) {
if (this._anchorX != value) {
this._anchorX = value;
this.callLater(this._sizeChanged);
}
}
/**Y锚点,值为0-1,设置anchorY值最终通过pivotY值来改变节点轴心点。*/
get anchorY(): number {
return this._anchorY;
}
set anchorY(value: number) {
if (this._anchorY != value) {
this._anchorY = value
this.callLater(this._sizeChanged);
}
}
/**
* @private
* @override
*/
/*override*/ protected _sizeChanged(): void {
if (!isNaN(this._anchorX)) this.pivotX = this.anchorX * this.width;
if (!isNaN(this._anchorY)) this.pivotY = this.anchorY * this.height;
this.event(Event.RESIZE);
}
/**
* @private
* <p>获取对象的布局样式。请不要直接修改此对象</p>
*/
private _getWidget(): Widget {
this._widget === Widget.EMPTY && (this._widget = this.addComponent(Widget));
return this._widget;
}
/**@private 兼容老版本*/
protected loadUI(path: string): void {
var uiView: any = View.uiMap[path];
View.uiMap && this.createView(uiView);
}
/**
* @implements
* laya.ui.UIComponent#dataSource
* */
get dataSource(): any {
return this._dataSource;
}
set dataSource(value: any) {
this._dataSource = value;
for (var name in value) {
var comp: any = this.getChildByName(name);
if (comp instanceof UIComponent) comp.dataSource = value[name];
else if (name in this && !((this as any)[name] instanceof Function)) (this as any)[name] = value[name];
}
}
}
ILaya.regClass(View);
ClassUtils.regClass("laya.ui.View", View);
ClassUtils.regClass("Laya.View", View);
//dialog 依赖于view,放到这里的话,谁在前都会报错,所以不能放到这里了
| mit |
ampedandwired/bottle-swagger | test/test_bottle_swagger.py | 10499 | from unittest import TestCase
from bottle import Bottle, redirect
from bottle_swagger import SwaggerPlugin
from webtest import TestApp
class TestBottleSwagger(TestCase):
VALID_JSON = {"id": "123", "name": "foo"}
INVALID_JSON = {"not_id": "123", "name": "foo"}
SWAGGER_DEF = {
"swagger": "2.0",
"info": {"version": "1.0.0", "title": "bottle-swagger"},
"consumes": ["application/json"],
"produces": ["application/json"],
"definitions": {
"Thing": {
"type": "object",
"required": ["id"],
"properties": {
"id": {"type": "string"},
"name": {"type": "string"}
}
}
},
"paths": {
"/thing": {
"get": {
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/Thing"
}
}
}
},
"post": {
"parameters": [{
"name": "thing",
"in": "body",
"required": True,
"schema": {
"$ref": "#/definitions/Thing"
}
}],
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/Thing"
}
}
}
}
},
"/thing/{thing_id}": {
"get": {
"parameters": [{
"name": "thing_id",
"in": "path",
"required": True,
"type": "string"
}],
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/Thing"
}
}
}
}
},
"/thing_query": {
"get": {
"parameters": [{
"name": "thing_id",
"in": "query",
"required": True,
"type": "string"
}],
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/Thing"
}
}
}
}
},
"/thing_header": {
"get": {
"parameters": [{
"name": "thing_id",
"in": "header",
"required": True,
"type": "string"
}],
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/Thing"
}
}
}
}
},
"/thing_formdata": {
"post": {
"consumes": [
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"parameters": [{
"name": "thing_id",
"in": "formData",
"required": True,
"type": "string"
}],
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/Thing"
}
}
}
}
}
}
}
def test_valid_get_request_and_response(self):
response = self._test_request()
self.assertEqual(response.status_int, 200)
def test_valid_post_request_and_response(self):
response = self._test_request(method='POST')
self.assertEqual(response.status_int, 200)
def test_invalid_request(self):
response = self._test_request(method='POST', request_json=self.INVALID_JSON)
self._assert_error_response(response, 400)
def test_invalid_response(self):
response = self._test_request(response_json=self.INVALID_JSON)
self._assert_error_response(response, 500)
def test_disable_request_validation(self):
self._test_disable_validation(validate_requests=False, expected_request_status=200,
expected_response_status=500)
def test_disable_response_validation(self):
self._test_disable_validation(validate_responses=False, expected_request_status=400,
expected_response_status=200)
def test_disable_all_validation(self):
self._test_disable_validation(validate_requests=False, validate_responses=False, expected_request_status=200,
expected_response_status=200)
def test_exception_handling(self):
def throw_ex():
raise Exception("Exception occurred")
response = self._test_request(response_json=throw_ex)
self._assert_error_response(response, 500)
def test_invalid_route(self):
response = self._test_request(url="/invalid")
self._assert_error_response(response, 404)
def test_ignore_invalid_route(self):
swagger_plugin = self._make_swagger_plugin(ignore_undefined_routes=True)
response = self._test_request(swagger_plugin=swagger_plugin, url="/invalid")
self.assertEqual(response.status_int, 200)
response = self._test_request(swagger_plugin=swagger_plugin, url="/invalid", method='POST',
request_json=self.INVALID_JSON, response_json=self.INVALID_JSON)
self.assertEqual(response.status_int, 200)
def test_redirects(self):
def _test_redirect(swagger_plugin):
def redir():
redirect("/actual_thing")
response = self._test_request(response_json=redir, swagger_plugin=swagger_plugin)
self.assertEqual(response.status_int, 302)
_test_redirect(self._make_swagger_plugin())
_test_redirect(self._make_swagger_plugin(ignore_undefined_routes=True))
def test_path_parameters(self):
response = self._test_request(url="/thing/123", route_url="/thing/<thing_id>")
self.assertEqual(response.status_int, 200)
def test_query_parameters(self):
response = self._test_request(url="/thing_query?thing_id=123", route_url="/thing_query")
self.assertEqual(response.status_int, 200)
def test_header_parameters(self):
response = self._test_request(url="/thing_header", route_url="/thing_header", headers={'thing_id': '123'})
self.assertEqual(response.status_int, 200)
def test_formdata_parameters(self):
response = self._test_request(url="/thing_formdata", route_url="/thing_formdata", method='POST', request_json='thing_id=123', content_type='multipart/form-data')
self.assertEqual(response.status_int, 200)
def test_get_swagger_schema(self):
bottle_app = Bottle()
bottle_app.install(self._make_swagger_plugin())
test_app = TestApp(bottle_app)
response = test_app.get(SwaggerPlugin.DEFAULT_SWAGGER_SCHEMA_URL)
self.assertEquals(response.json, self.SWAGGER_DEF)
def _test_request(self, swagger_plugin=None, method='GET', url='/thing', route_url=None, request_json=VALID_JSON,
response_json=VALID_JSON, headers=None, content_type='application/json'):
if swagger_plugin is None:
swagger_plugin = self._make_swagger_plugin()
if response_json is None:
response_json = {}
if route_url is None:
route_url = url
bottle_app = Bottle()
bottle_app.install(swagger_plugin)
@bottle_app.route(route_url, method)
def do_thing(*args, **kwargs):
return response_json() if hasattr(response_json, "__call__") else response_json
test_app = TestApp(bottle_app)
if method.upper() == 'GET':
response = test_app.get(url, expect_errors=True, headers=headers)
elif method.upper() == 'POST':
if content_type == 'application/json':
response = test_app.post_json(url, request_json, expect_errors=True, headers=headers)
else:
response = test_app.post(url, request_json, content_type=content_type, expect_errors=True, headers=headers)
else:
raise Exception("Invalid method {}".format(method))
return response
def _test_disable_validation(self, validate_requests=True, validate_responses=True, expected_request_status=200,
expected_response_status=200):
swagger_plugin = self._make_swagger_plugin(validate_requests=validate_requests,
validate_responses=validate_responses)
response = self._test_request(swagger_plugin=swagger_plugin, method='POST', request_json=self.INVALID_JSON)
self.assertEqual(response.status_int, expected_request_status)
response = self._test_request(swagger_plugin=swagger_plugin, response_json=self.INVALID_JSON)
self.assertEqual(response.status_int, expected_response_status)
def _assert_error_response(self, response, expected_status):
self.assertEqual(response.status_int, expected_status)
self.assertEqual(response.json['code'], expected_status)
self.assertIsNotNone(response.json['message'])
def _make_swagger_plugin(self, *args, **kwargs):
return SwaggerPlugin(self.SWAGGER_DEF, *args, **kwargs)
| mit |
asiboro/asiboro.github.io | vsdoc/search--/s_3780.js | 85 | search_result['3780']=["topic_000000000000090D.html","UserDto.LastName Property",""]; | mit |
japaz/WasThreadStackProcessor | spec/threadStack_spec.rb | 4084 | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require 'threadStack'
describe ThreadStack do
describe "After creation" do
it "must contains the stack passed as an Array" do
stack = ['at com/ibm/io/async/AsyncLibrary.aio_getioev3(Native Method)',
'at com/ibm/io/async/AsyncLibrary.getCompletionData3(AsyncLibrary.java:602(Compiled Code))',
'at com/ibm/io/async/ResultHandler.runEventProcessingLoop(ResultHandler.java:287(Compiled Code))',
'at com/ibm/io/async/ResultHandler$2.run(ResultHandler.java:881(Compiled Code))',
'at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1551(Compiled Code))']
threadStack = ThreadStack.new(stack)
threadStack.call.text.should == 'at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1551(Compiled Code))'
threadStack.call.count.should == 1
threadStack.call.children[0].text.should == 'at com/ibm/io/async/ResultHandler$2.run(ResultHandler.java:881(Compiled Code))'
threadStack.call.children[0].children[0].text.should == 'at com/ibm/io/async/ResultHandler.runEventProcessingLoop(ResultHandler.java:287(Compiled Code))'
end
end
describe "A merge" do
before(:each) do
@threadStack = ThreadStack.new(['at com/ibm/io/async/AsyncLibrary.aio_getioev3(Native Method)',
'at com/ibm/io/async/AsyncLibrary.getCompletionData3(AsyncLibrary.java:602(Compiled Code))',
'at com/ibm/io/async/ResultHandler.runEventProcessingLoop(ResultHandler.java:287(Compiled Code))',
'at com/ibm/io/async/ResultHandler$2.run(ResultHandler.java:881(Compiled Code))',
'at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1551(Compiled Code))'])
@threadStack2 = ThreadStack.new(['at java/lang/Object.wait(Native Method)',
'at com/ibm/io/async/ResultHandler$2.run(ResultHandler.java:881(Compiled Code))',
'at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1551(Compiled Code))'])
@threadStack3 = ThreadStack.new(['at java/lang/Object.wait(Native Method)',
'at com/ibm/io/async/ResultHandler$2.run(ResultHandler.java:881(Compiled Code))'])
@threadStack4 = ThreadStack.new(['at com/ibm/io/async/AsyncLibrary.aio_getioev3(Native Method)',
'at com/ibm/io/async/AsyncLibrary.getCompletionData3(AsyncLibrary.java:602(Compiled Code))',
'at com/ibm/io/async/ResultHandler.runEventProcessingLoop(ResultHandler.java:287(Compiled Code))',
'at com/ibm/io/async/ResultHandler$2.run(ResultHandler.java:881(Compiled Code))',
'at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1551(Compiled Code))'])
end
it "must contains two branches after a merge with other ThreadStack with common calls" do
@threadStack.merge(@threadStack2)
@threadStack.call.text.should == 'at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1551(Compiled Code))'
@threadStack.call.count.should == 2
@threadStack.call.children[0].text.should == 'at com/ibm/io/async/ResultHandler$2.run(ResultHandler.java:881(Compiled Code))'
@threadStack.call.children[0].count.should == 2
@threadStack.call.children[0].children[0].text.should == 'at com/ibm/io/async/ResultHandler.runEventProcessingLoop(ResultHandler.java:287(Compiled Code))'
@threadStack.call.children[0].children[0].count.should == 1
@threadStack.call.children[0].children[1].text.should == 'at java/lang/Object.wait(Native Method)'
@threadStack.call.children[0].children[1].count.should == 1
end
it "must return true if the merge is done" do
@threadStack.merge(@threadStack2).should be true
end
it "must return false if the merge is not done" do
@threadStack.merge(@threadStack3).should be false
end
it "must put count to two in all calls if the thread stacks are the same" do
@threadStack.merge(@threadStack4)
@threadStack.call.count.should == 2
@threadStack.call.children[0].count.should == 2
@threadStack.call.children[0].children[0].count.should == 2
@threadStack.call.children[0].children[0].children[0].count.should == 2
@threadStack.call.children[0].children[0].children[0].children[0].count.should == 2
end
end
end | mit |
wilkenstein/redis-mock-java | src/test/java/org/rarefiedredis/redis/adapter/jedis/JedisIRedisClientHashIT.java | 30499 | package org.rarefiedredis.redis.adapter.jedis;
import org.junit.Test;
import org.junit.Before;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import org.rarefiedredis.redis.IRedisClient;
import org.rarefiedredis.redis.RandomKey;
import org.rarefiedredis.redis.ScanResult;
import org.rarefiedredis.redis.ArgException;
import org.rarefiedredis.redis.BitArgException;
import org.rarefiedredis.redis.NotFloatException;
import org.rarefiedredis.redis.WrongTypeException;
import org.rarefiedredis.redis.NotIntegerException;
import org.rarefiedredis.redis.SyntaxErrorException;
import org.rarefiedredis.redis.NotFloatHashException;
import org.rarefiedredis.redis.NotIntegerHashException;
import org.rarefiedredis.redis.NotImplementedException;
import java.util.Map;
import java.util.HashMap;
public class JedisIRedisClientHashIT {
private JedisPool pool;
private IRedisClient redis;
private RandomKey rander;
@Before public void initPool() {
pool = new JedisPool(new JedisPoolConfig(), "localhost");
redis = new JedisIRedisClient(pool);
rander = new RandomKey();
}
@Test public void hdelShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hdel(k, f);
}
catch (WrongTypeException wte) {
assertEquals(true, true);
}
catch (Exception e) {
assertEquals(false, true);
}
try {
redis.hdel(k, f, f, f);
}
catch (WrongTypeException wte) {
assertEquals(true, true);
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hdelShouldReturnZeroIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(0L, (long)redis.hdel(k, f));
}
@Test public void hdelShouldReturnZeroIfFieldDoesNotExistInKey() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field", f1 = "f1", f2 = "f2";
redis.hset(k, f, v);
assertEquals(0L, (long)redis.hdel(k, f1));
assertEquals(0L, (long)redis.hdel(k, f2, f1));
}
@Test public void hdelShouldReturnOneWhenDeletingASingleField() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.hset(k, f, v);
assertEquals(1L, (long)redis.hdel(k, f));
assertEquals(0, redis.hkeys(k).size());
}
@Test public void hdelShouldReturnTheDeletedCountWhenDeletingMultipleFields() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f1 = "f1", f2 = "f2", f3 = "f3";
redis.hset(k, f1, v);
redis.hset(k, f2, v);
redis.hset(k, f3, v);
assertEquals(2L, (long)redis.hdel(k, f1, f2));
assertEquals(1, redis.hkeys(k).size());
redis.hset(k, f1, v);
redis.hset(k, f2, v);
assertEquals(3L, (long)redis.hdel(k, f1, f2, f3));
assertEquals(0, redis.hkeys(k).size());
}
@Test public void hexistsShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hexists(k, f);
}
catch (WrongTypeException wte) {
assertEquals(true, true);
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hexistsShouldReturnZeroIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(false, redis.hexists(k, f));
}
@Test public void hexistsShouldReturnZeroIfFieldDoesNotExistInKey() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f1 = "f1", f2 = "f2";
redis.hset(k, f1, v);
assertEquals(false, redis.hexists(k, f2));
}
@Test public void hexistsShouldReturnOneIfFieldExistsInKey() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f1 = "f1", f2 = "f2";
redis.hset(k, f1, v);
assertEquals(true, redis.hexists(k, f1));
redis.hset(k, f2, v);
assertEquals(true, redis.hexists(k, f2));
}
@Test public void hgetShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hget(k, f);
}
catch (WrongTypeException wte) {
assertEquals(true, true);
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hgetShouldReturnNothingIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(null, redis.hget(k, f));
}
@Test public void hgetShouldReturnNothingIfFieldIsNotInKey() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field", f1 = "f1";
redis.hset(k, f, v);
assertEquals(null, redis.hget(k, f1));
}
@Test public void hgetShouldReturnTheFieldValue() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.hset(k, f, v);
assertEquals(v, redis.hget(k, f));
}
@Test public void hgetallShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hgetall(k);
}
catch (WrongTypeException wte) {
assertEquals(true, true);
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hgetallShouldReturnEmptyHashIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(0, redis.hgetall(k).size());
}
@Test public void hgetallShouldReturnAllTheKeysAndValuesInTheHash() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String v1 = "v1", v2 = "v2", v3 = "v3";
String f1 = "f1", f2 = "f2", f3 = "f3";
redis.hmset(k, f1, v1, f2, v2, f3, v3);
Map<String, String> hgetall = redis.hgetall(k);
assertEquals(3, hgetall.size());
assertEquals(v1, hgetall.get(f1));
assertEquals(v2, hgetall.get(f2));
assertEquals(v3, hgetall.get(f3));
}
@Test public void hincrbyShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hincrby(k, f, 1L);
}
catch (WrongTypeException wte) {
assertEquals(true, true);
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hincrbyShouldSetTheKeyAndFieldIfNeitherExistToTheIncrement() throws WrongTypeException, NotIntegerHashException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(1L, (long)redis.hincrby(k, f, 1L));
assertEquals(1L, (long)Long.valueOf(redis.hget(k, f)));
redis.del(k);
assertEquals(-4L, (long)redis.hincrby(k, f, -4L));
assertEquals(-4L, (long)Long.valueOf(redis.hget(k, f)));
}
@Test public void hincrbyShouldThrowAnErrorIfFieldIsNotAnInteger() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2";
String v1 = "Five", v2 = "Yo Momma";
redis.hmset(k, f1, v1, f2, v2);
try {
redis.hincrby(k, f1, 1L);
}
catch (NotIntegerHashException nihe) {
assertEquals(true, true);
}
catch (Exception e) {
assertEquals(false, true);
}
assertEquals(v1, redis.hget(k, f1));
try {
redis.hincrby(k, f2, -4L);
}
catch (NotIntegerHashException nihe) {
assertEquals(v2, redis.hget(k, f2));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hincrbyShouldIncrTheValueAtFieldByTheIncrement() throws WrongTypeException, NotIntegerHashException, NotImplementedException {
String k = rander.randkey();
String f = "f";
Long v = 123L;
redis.hset(k, f, String.valueOf(v));
assertEquals(v + 2L, (long)redis.hincrby(k, f, 2L));
assertEquals(v + 2L, (long)Long.valueOf(redis.hget(k, f)));
assertEquals(v - 2L, (long)redis.hincrby(k, f, -4L));
assertEquals(v - 2L, (long)Long.valueOf(redis.hget(k, f)));
}
@Test public void hincrbyfloatShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hincrbyfloat(k, f, 1.1d);
}
catch (WrongTypeException wte) {
assertEquals(true, true);
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hincrbyfloatShouldSetTheKeyAndFieldIfNeitherExistToTheIncrement() throws WrongTypeException, NotFloatHashException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals("1.1", redis.hincrbyfloat(k, f, 1.1d));
assertEquals("1.1", redis.hget(k, f));
}
@Test public void hincrbyfloatShouldThrowAnErrorIfFieldIsNotAFloat() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2";
String v1 = "Five", v2 = "Yo Momma";
redis.hmset(k, f1, v1, f2, v2);
try {
redis.hincrbyfloat(k, f1, 1.1d);
}
catch (NotFloatHashException nfhe) {
assertEquals(v1, redis.hget(k, f1));
}
catch (Exception e) {
assertEquals(false, true);
}
try {
redis.hincrbyfloat(k, f2, -3.1415d);
}
catch (NotFloatHashException nfhe) {
assertEquals(v2, redis.hget(k, f2));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hincrbyfloatShouldIncrTheValueAtFieldByTheIncrement() throws WrongTypeException, NotFloatHashException, NotImplementedException {
String k = rander.randkey();
String f = "field";
Double v = 123.456d;
redis.hset(k, f, String.valueOf(v));
assertEquals(v + 2.22d, Double.parseDouble(redis.hincrbyfloat(k, f, 2.22d)), 0.01d);
assertEquals(v + 2.22d, Double.parseDouble(redis.hget(k, f)), 0.01d);
assertEquals(v + 2.22d - 3.1415d, Double.parseDouble(redis.hincrbyfloat(k, f, -3.1415d)), 0.01d);
assertEquals(v + 2.22d - 3.1415d, Double.parseDouble(redis.hget(k, f)), 0.01d);
}
@Test public void hkeysShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hkeys(k);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(true, false);
}
@Test public void hkeysShouldReturnAnEmptySetIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(0, redis.hkeys(k).size());
}
@Test public void hkeysShouldReturnAllTheKeysInAHash() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String v1 = "v1", v2 = "v2", v3 = "v3";
String f1 = "f1", f2 = "f2", f3 = "f3";
redis.hmset(k, f1, v1, f2, v2, f3, v3);
Set<String> keys = redis.hkeys(k);
assertEquals(3, keys.size());
assertEquals(true, keys.contains(f1));
assertEquals(true, keys.contains(f2));
assertEquals(true, keys.contains(f3));
}
@Test public void hlenShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hlen(k);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hlenShoulReturnZeroIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(0L, (long)redis.hlen(k));
}
@Test public void hlenShouldReturnTheHashLength() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String v1 = "v1", v2 = "v2", v3 = "v3";
String f1 = "f1", f2 = "f2", f3 = "f3";
redis.hmset(k, f1, v1, f2, v2, f3, v3);
assertEquals(3L, (long)redis.hlen(k));
}
@Test public void hmgetShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hmget(k, f);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
}
catch (Exception e) {
assertEquals(false, true);
}
try {
redis.hmget(k, f ,f ,f);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hmgetShouldReturnEmptyListIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(2, redis.hmget(k, f, f).size());
}
@Test public void hmgetShouldTheFieldsInTheHashAndNilsWhenAFieldIsNotInTheHash() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2", f3 = "f3";
String v1 = "v1", v2 = "v2", v3 = "v3";
redis.hmset(k, f1, v1, f2, v2, f3, v3);
List<String> get = redis.hmget(k, f1, f2, f3);
assertEquals(3, get.size());
get = redis.hmget(k, f1, f2, f3, f2, "na", f2, "na");
assertEquals(7, get.size());
assertEquals(redis.hget(k, f1), get.get(0));
assertEquals(redis.hget(k, f2), get.get(1));
assertEquals(redis.hget(k, f3), get.get(2));
assertEquals(redis.hget(k, f2), get.get(3));
assertEquals(null, get.get(4));
assertEquals(redis.hget(k, f2), get.get(5));
assertEquals(null, get.get(6));
}
@Test public void hmsetShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hmset(k, f, v, f, v);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hmsetShouldThrowAnErrorIfArgsAreBad() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
try {
redis.hmset(k, f, v, f);
}
catch (ArgException ae) {
assertEquals(true, true);
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hmsetShouldSetNewFieldsInTheHash() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2", f3 = "f3", f4 = "f4", f5 = "f5";
String v = "v", v1 = "v1";
assertEquals("OK", redis.hmset(k, f1, v, f2, v));
assertEquals(2L, (long)redis.hlen(k));
assertEquals(v, redis.hget(k, f1));
assertEquals(v, redis.hget(k, f2));
assertEquals("OK", redis.hmset(k, f3, v, f4, v, f5, v, f1, v1));
assertEquals(5L, (long)redis.hlen(k));
assertEquals(v, redis.hget(k, f3));
assertEquals(v, redis.hget(k, f4));
assertEquals(v, redis.hget(k, f5));
assertEquals(v1, redis.hget(k, f1));
}
@Test public void hsetShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hset(k, f, v);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hsetShouldSetANewFiledInAHashAndReturnOne() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2";
String v = "v";
assertEquals(true, redis.hset(k, f1, v));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v, redis.hget(k, f1));
assertEquals(true, redis.hset(k, f2, v));
assertEquals(2L, (long)redis.hlen(k));
assertEquals(v, redis.hget(k, f2));
}
@Test public void hsetShouldUpdateAnExistingFieldInAHashAndReturnZero() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String f = "f";
String v1 = "v1", v2 = "v2", v3 = "v3";
assertEquals(true, redis.hset(k, f, v1));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v1, redis.hget(k, f));
assertEquals(false, redis.hset(k, f, v2));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v2, redis.hget(k, f));
assertEquals(false, redis.hset(k, f, v3));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v3, redis.hget(k, f));
}
@Test public void hsetnxShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String f = "field";
String v = "value";
redis.set(k, v);
try {
redis.hsetnx(k, f, v);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hsetnxShouldSetANewFieldInAHashAndReturnOne() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2";
String v = "v";
assertEquals(true, redis.hsetnx(k, f1, v));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v, redis.hget(k, f1));
assertEquals(true, redis.hsetnx(k, f2, v));
assertEquals(2L, (long)redis.hlen(k));
assertEquals(v, redis.hget(k, f2));
}
@Test public void hsetnxShouldNotUpdateAnExistingFieldAndReturnZero() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String f = "f";
String v1 = "v1", v2 = "v2", v3 = "v3";
assertEquals(true, redis.hsetnx(k, f, v1));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v1, redis.hget(k, f));
assertEquals(false, redis.hsetnx(k, f, v2));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v1, redis.hget(k, f));
assertEquals(false, redis.hsetnx(k, f, v3));
assertEquals(1L, (long)redis.hlen(k));
assertEquals(v1, redis.hget(k, f));
}
@Ignore("jedis does not support hstrlen") @Test public void hstrlenShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hstrlen(k, f);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Ignore("jedis does not support hstrlen") @Test public void hstrlenShouldReturnZeroForKeyOrFieldThatDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2";
String v1 = "v1";
assertEquals(0L, (long)redis.hstrlen(k, f1));
redis.hset(k, f1, v1);
assertEquals(0L, (long)redis.hstrlen(k, f2));
}
@Ignore("jedis does not support hstrlen") @Test public void hstrlenShouldReturnTheLengthOfTheStringAtField() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2";
String v1 = "v1", v2 = "123";
redis.hmset(k, f1, v1, f2, v2);
assertEquals((long)v1.length(), (long)redis.hstrlen(k, f1));
assertEquals((long)v2.length(), (long)redis.hstrlen(k, f2));
}
@Test public void hvalsShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
redis.set(k, v);
try {
redis.hvals(k);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hvalsShouldReturnAnEmptyListIfKeyDoesNotExist() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
String v = "value";
String f = "field";
assertEquals(0, redis.hvals(k).size());
}
@Test public void hvalsShouldReturnAllTheValuesInAHash() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2", f3 = "f3";
String v1 = "v1", v2 = "v2", v3 = "v3";
redis.hmset(k, f1, v1, f2, v2, f3, v3);
List<String> vals = redis.hvals(k);
assertEquals(3, vals.size());
assertEquals(true, vals.contains(v1));
assertEquals(true, vals.contains(v2));
assertEquals(true, vals.contains(v3));
}
@Test public void hscanShouldThrowAnErrorIfKeyIsNotAHash() throws WrongTypeException, SyntaxErrorException, NotImplementedException {
String k = rander.randkey();
String v = "value";
redis.set(k, v);
try {
redis.hscan(k, 0L);
}
catch (WrongTypeException wte) {
assertEquals(v, redis.get(k));
return;
}
catch (Exception e) {
}
assertEquals(false, true);
}
@Test public void hscanShouldScanThroughASmallHashAndReturnEveryFieldAndValue() throws WrongTypeException, ArgException, NotImplementedException {
String k = rander.randkey();
String f1 = "f1", f2 = "f2", f3 = "f3", f4 = "f4";
String v1 = "v1", v2 = "v2", v3 = "v3", v4 = "v4";
redis.hmset(k, f1, v1, f2, v2, f3, v3);
ScanResult<Map<String, String>> scan = redis.hscan(k, 0L);
assertEquals(0L, (long)scan.cursor);
assertEquals(3, scan.results.size());
assertEquals(redis.hget(k, f1), scan.results.get(f1));
assertEquals(redis.hget(k, f2), scan.results.get(f2));
assertEquals(redis.hget(k, f3), scan.results.get(f3));
}
@Test public void hscanShouldScanThroughALargeSetWithCursoring() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
Map<String, String> hash = new HashMap<String, String>();
for (int idx = 0; idx < 62; ++idx) {
hash.put(String.valueOf(idx), String.valueOf(idx));
}
for (String key : hash.keySet()) {
redis.hset(k, key, hash.get(key));
}
ScanResult<Map<String, String>> scan = new ScanResult<Map<String, String>>();
Map<String, String> scanned = new HashMap<String, String>();
while (true) {
scan = redis.hscan(k, scan.cursor);
for (String key : scan.results.keySet()) {
scanned.put(key, scan.results.get(key));
}
if (scan.cursor == 0L) {
break;
}
}
assertEquals(hash.size(), scanned.size());
for (String key : scanned.keySet()) {
assertEquals(hash.get(key), scanned.get(key));
}
}
@Test public void hscanShouldScanThroughALargeSetWithCursoringAndACount() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
Map<String, String> hash = new HashMap<String, String>();
for (int idx = 0; idx < 62; ++idx) {
hash.put(String.valueOf(idx), String.valueOf(idx));
}
for (String key : hash.keySet()) {
redis.hset(k, key, hash.get(key));
}
ScanResult<Map<String, String>> scan = new ScanResult<Map<String, String>>();
Map<String, String> scanned = new HashMap<String, String>();
Long count = 5L;
while (true) {
scan = redis.hscan(k, scan.cursor, "count", String.valueOf(count));
for (String key : scan.results.keySet()) {
scanned.put(key, scan.results.get(key));
}
if (scan.cursor == 0L) {
break;
}
}
assertEquals(hash.size(), scanned.size());
for (String key : scanned.keySet()) {
assertEquals(hash.get(key), scanned.get(key));
}
}
@Test public void hscanShouldScanThroughALargeSetWithCursoringAndAMatch() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
Map<String, String> hash = new HashMap<String, String>();
for (int idx = 0; idx < 62; ++idx) {
hash.put(String.valueOf(idx), String.valueOf(idx));
}
for (String key : hash.keySet()) {
redis.hset(k, key, hash.get(key));
}
ScanResult<Map<String, String>> scan = new ScanResult<Map<String, String>>();
Map<String, String> scanned = new HashMap<String, String>();
String match = "[0-9]"; // All single digit #s.
while (true) {
scan = redis.hscan(k, scan.cursor, "match", match);
for (String key : scan.results.keySet()) {
scanned.put(key, scan.results.get(key));
}
if (scan.cursor == 0L) {
break;
}
}
assertEquals(10, scanned.size());
for (String key : scanned.keySet()) {
assertEquals(hash.get(key), scanned.get(key));
}
}
@Test public void hscanShouldScanThroughALargeSetWithCursoringACountAndAMatch() throws WrongTypeException, NotImplementedException {
String k = rander.randkey();
Map<String, String> hash = new HashMap<String, String>();
for (int idx = 0; idx < 62; ++idx) {
hash.put(String.valueOf(idx), String.valueOf(idx));
}
for (String key : hash.keySet()) {
redis.hset(k, key, hash.get(key));
}
ScanResult<Map<String, String>> scan = new ScanResult<Map<String, String>>();
Map<String, String> scanned = new HashMap<String, String>();
Long count = 5L;
String match = "[0-9]"; // All single digit #s.
while (true) {
scan = redis.hscan(k, scan.cursor, "count", String.valueOf(count), "match", match);
for (String key : scan.results.keySet()) {
scanned.put(key, scan.results.get(key));
}
if (scan.cursor == 0L) {
break;
}
}
assertEquals(10, scanned.size());
for (String key : scanned.keySet()) {
assertEquals(hash.get(key), scanned.get(key));
}
}
} | mit |
dvhassel/player | src/extensions/coreplayer-seadragon-extension/extension.ts | 8973 | /// <reference path="../../js/jquery.d.ts" />
/// <reference path="../../js/extensions.d.ts" />
import baseExtension = require("../../modules/coreplayer-shared-module/baseExtension");
import utils = require("../../utils");
import baseProvider = require("../../modules/coreplayer-shared-module/baseProvider");
import provider = require("./provider");
import shell = require("../../modules/coreplayer-shared-module/shell");
import header = require("../../modules/coreplayer-pagingheaderpanel-module/pagingHeaderPanel");
import left = require("../../modules/coreplayer-treeviewleftpanel-module/treeViewLeftPanel");
import thumbsView = require("../../modules/coreplayer-treeviewleftpanel-module/thumbsView");
import treeView = require("../../modules/coreplayer-treeviewleftpanel-module/treeView");
import center = require("../../modules/coreplayer-seadragoncenterpanel-module/seadragonCenterPanel");
import right = require("../../modules/coreplayer-moreinforightpanel-module/moreInfoRightPanel");
import footer = require("../../modules/coreplayer-shared-module/footerPanel");
import help = require("../../modules/coreplayer-dialogues-module/helpDialogue");
import embed = require("../../extensions/coreplayer-seadragon-extension/embedDialogue");
import IProvider = require("../../modules/coreplayer-shared-module/iProvider");
import ISeadragonProvider = require("./iSeadragonProvider");
import dependencies = require("./dependencies");
export class Extension extends baseExtension.BaseExtension {
headerPanel: header.PagingHeaderPanel;
leftPanel: left.TreeViewLeftPanel;
centerPanel: center.SeadragonCenterPanel;
rightPanel: right.MoreInfoRightPanel;
footerPanel: footer.FooterPanel;
$helpDialogue: JQuery;
helpDialogue: help.HelpDialogue;
$embedDialogue: JQuery;
embedDialogue: embed.EmbedDialogue;
currentRotation: number = 0;
static mode: string;
// events
static MODE_CHANGED: string = 'onModeChanged';
// modes
static PAGE_MODE: string = "pageMode";
static IMAGE_MODE: string = "imageMode";
constructor(provider: IProvider) {
super(provider);
}
create(overrideDependencies?: any): void {
super.create();
var that = this;
// events.
$.subscribe(header.PagingHeaderPanel.FIRST, (e) => {
this.viewPage(0);
});
$.subscribe(header.PagingHeaderPanel.LAST, (e) => {
this.viewPage(this.provider.getTotalCanvases() - 1);
});
$.subscribe(header.PagingHeaderPanel.PREV, (e) => {
if (this.provider.canvasIndex != 0) {
this.viewPage(Number(this.provider.canvasIndex) - 1);
}
});
$.subscribe(header.PagingHeaderPanel.NEXT, (e) => {
if (this.provider.canvasIndex != this.provider.getTotalCanvases() - 1) {
this.viewPage(Number(this.provider.canvasIndex) + 1);
}
});
$.subscribe(header.PagingHeaderPanel.MODE_CHANGED, (e, mode: string) => {
Extension.mode = mode;
$.publish(Extension.MODE_CHANGED, [mode]);
});
$.subscribe(header.PagingHeaderPanel.PAGE_SEARCH, (e, value: string) => {
this.viewLabel(value);
});
$.subscribe(header.PagingHeaderPanel.IMAGE_SEARCH, (e, index: number) => {
this.viewPage(index);
});
$.subscribe(treeView.TreeView.NODE_SELECTED, (e, data: any) => {
this.treeNodeSelected(data);
});
$.subscribe(thumbsView.ThumbsView.THUMB_SELECTED, (e, index: number) => {
this.viewPage(index);
});
$.subscribe(center.SeadragonCenterPanel.SEADRAGON_ANIMATION_FINISH, (e, viewer) => {
this.setParam(baseProvider.params.zoom, this.centerPanel.serialiseBounds(this.centerPanel.currentBounds));
});
$.subscribe(center.SeadragonCenterPanel.SEADRAGON_ROTATION, (e, rotation) => {
this.currentRotation = rotation;
this.setParam(baseProvider.params.rotation, rotation);
});
$.subscribe(center.SeadragonCenterPanel.PREV, (e) => {
if (this.provider.canvasIndex != 0) {
this.viewPage(Number(this.provider.canvasIndex) - 1);
}
});
$.subscribe(center.SeadragonCenterPanel.NEXT, (e) => {
if (this.provider.canvasIndex != this.provider.getTotalCanvases() - 1) {
this.viewPage(Number(this.provider.canvasIndex) + 1);
}
});
$.subscribe(footer.FooterPanel.EMBED, (e) => {
$.publish(embed.EmbedDialogue.SHOW_EMBED_DIALOGUE);
});
// dependencies
var deps = overrideDependencies || dependencies;
require(_.values(deps), function () {
//var deps = _.object(_.keys(dependencies), arguments);
that.createModules();
that.setParams();
var canvasIndex;
if (!that.provider.isReload){
canvasIndex = parseInt(that.getParam(baseProvider.params.canvasIndex)) || 0;
}
that.viewPage(canvasIndex || 0);
// initial sizing
$.publish(baseExtension.BaseExtension.RESIZE);
// publish created event
$.publish(Extension.CREATED);
});
}
createModules(): void{
this.headerPanel = new header.PagingHeaderPanel(shell.Shell.$headerPanel);
if (this.isLeftPanelEnabled()){
this.leftPanel = new left.TreeViewLeftPanel(shell.Shell.$leftPanel);
}
this.centerPanel = new center.SeadragonCenterPanel(shell.Shell.$centerPanel);
if (this.isRightPanelEnabled()){
this.rightPanel = new right.MoreInfoRightPanel(shell.Shell.$rightPanel);
}
this.footerPanel = new footer.FooterPanel(shell.Shell.$footerPanel);
this.$helpDialogue = utils.Utils.createDiv('overlay help');
shell.Shell.$overlays.append(this.$helpDialogue);
this.helpDialogue = new help.HelpDialogue(this.$helpDialogue);
this.$embedDialogue = utils.Utils.createDiv('overlay embed');
shell.Shell.$overlays.append(this.$embedDialogue);
this.embedDialogue = new embed.EmbedDialogue(this.$embedDialogue);
if (this.isLeftPanelEnabled()){
this.leftPanel.init();
}
if (this.isRightPanelEnabled()){
this.rightPanel.init();
}
}
setParams(): void{
if (!this.provider.isHomeDomain) return;
// set sequenceIndex hash param.
this.setParam(baseProvider.params.sequenceIndex, this.provider.sequenceIndex);
}
isLeftPanelEnabled(): boolean{
return utils.Utils.getBool(this.provider.config.options.leftPanelEnabled, true)
&& this.provider.isMultiCanvas();
}
isRightPanelEnabled(): boolean{
return utils.Utils.getBool(this.provider.config.options.rightPanelEnabled, true);
}
viewPage(canvasIndex: number): void {
this.viewCanvas(canvasIndex, () => {
var canvas = this.provider.getCanvasByIndex(canvasIndex);
var uri = (<ISeadragonProvider>this.provider).getImageUri(canvas);
$.publish(Extension.OPEN_MEDIA, [uri]);
this.setParam(baseProvider.params.canvasIndex, canvasIndex);
});
}
getMode(): string {
if (Extension.mode) return Extension.mode;
switch (this.provider.getManifestType()) {
case 'monograph':
return Extension.PAGE_MODE;
break;
case 'archive',
'boundmanuscript':
return Extension.IMAGE_MODE;
break;
default:
return Extension.IMAGE_MODE;
}
}
getViewerBounds(): string{
if (!this.centerPanel) return;
var bounds = this.centerPanel.getBounds();
if (bounds) return this.centerPanel.serialiseBounds(bounds);
return "";
}
getViewerRotation(): number{
if (!this.centerPanel) return;
return this.currentRotation;
}
viewStructure(path: string): void {
var index = this.provider.getStructureIndex(path);
this.viewPage(index);
}
viewLabel(label: string): void {
if (!label) {
this.showDialogue(this.provider.config.modules.genericDialogue.content.emptyValue);
return;
}
var index = this.provider.getCanvasIndexByOrderLabel(label);
if (index != -1) {
this.viewPage(index);
} else {
this.showDialogue(this.provider.config.modules.genericDialogue.content.pageNotFound);
}
}
treeNodeSelected(data: any): void{
if (!data.type) return;
if (data.type == 'manifest') {
this.viewManifest(data);
} else {
this.viewStructure(data.path);
}
}
}
| mit |
tinylabproductions/tlplib | parts/0000-TLPLib/Assets/Vendor/TLPLib/unity/Utilities/ArrayUtils.cs | 603 | using System;
using System.Collections.Generic;
using tlplib.exts;
namespace com.tinylabproductions.TLPLib.Utilities {
public static class ArrayUtils {
static readonly Dictionary<Type, object> emptyArrays =
new Dictionary<Type, object>();
/**
* When you have a serialized array in Unity if the asset was not opened
* in editor and reserialized, runtime will return null for that array
* instead of empty array. Yay Unity!
*/
public static A[] ensureNotNull<A>(this A[] array) =>
array ?? (A[]) emptyArrays.getOrUpdate(typeof (A), () => new A[0]);
}
} | mit |
edbiler/BazaarCorner | file/cache_for_deletion/block/file_94.php | 325 | <?php defined('PHPFOX') or exit('NO DICE!'); ?>
<?php $aContent = array (
'block_id' => '94',
'type_id' => '0',
'ordering' => '4',
'm_connection' => 'photo.index',
'component' => 'cloud',
'location' => '3',
'disallow_access' => NULL,
'can_move' => '0',
'module_id' => 'tag',
'source_parsed' => NULL,
); ?> | mit |
MaSys/m_cfdi | lib/m_cfdi/key.rb | 495 | module MCFDI
require 'openssl'
# openssl pkcs8 -inform DER -in file.key -passin pass:password >> file.pem
class Key < OpenSSL::PKey::RSA
def initialize(file, password=nil)
if file.is_a? String
file = File.read(file)
end
super file, password
end
def seal(invoice)
original_string = invoice.original_string
invoice.stamp = Base64::encode64(
self.sign(OpenSSL::Digest::SHA1.new, original_string)).gsub(/\n/, '')
end
end
end
| mit |
mathiasbynens/unicode-data | 3.2.0/scripts/GOTHIC-code-points.js | 338 | // All code points in the `GOTHIC` script as per Unicode v3.2.0:
[
0x10330,
0x10331,
0x10332,
0x10333,
0x10334,
0x10335,
0x10336,
0x10337,
0x10338,
0x10339,
0x1033A,
0x1033B,
0x1033C,
0x1033D,
0x1033E,
0x1033F,
0x10340,
0x10341,
0x10342,
0x10343,
0x10344,
0x10345,
0x10346,
0x10347,
0x10348,
0x10349,
0x1034A
]; | mit |
mattiasliljenzin/webapi-cart | CrazyCart/CrazyCart.Tests/Properties/AssemblyInfo.cs | 1365 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("webapi_cart.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("webapi_cart.Tests")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b71fd020-52a1-4aca-a6b4-1b17e23b29c4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
cosminseceleanu/react-sb-admin-bootstrap4 | src/components/pages/admin.js | 468 | import React from 'react';
import {Container} from 'reactstrap';
import Dashboard from './dashboard';
import NavigationContainer from '../../containers/navigation-container';
const Admin = () => {
return (
<div>
<NavigationContainer/>
<div className="content-wrapper">
<Container fluid>
<Dashboard/>
</Container>
</div>
</div>
)
};
export default Admin; | mit |
Promact/trappist | Trappist/src/Promact.Trappist.Web/wwwroot/app/profile/profile-edit/profile-edit.component.ts | 1414 | import { Component, OnInit, ViewChild } from '@angular/core';
import { MdSnackBar } from '@angular/material';
import { Router } from '@angular/router';
import { ApplicationUser } from '../profile.model';
import { ProfileService } from '../profile.service';
@Component({
moduleId: module.id,
selector: 'profile-edit',
templateUrl: 'profile-edit.html'
})
export class ProfileEditComponent implements OnInit {
editUser: ApplicationUser = new ApplicationUser();
nameLength: boolean = false;
loader: boolean;
constructor(public profileService: ProfileService, private router: Router, public snackBar: MdSnackBar) { }
ngOnInit() {
this.getUserDetails();
}
/**
* Get details of the user and display them in the profile edit page so that the user can edit them
*/
getUserDetails() {
this.profileService.getUserDetails().subscribe((response) => {
this.editUser = response;
});
}
/**
* Update the details of a user
*/
updateUserDetails() {
this.loader = true;
this.profileService.updateUserDetails(this.editUser).subscribe((response) => {
this.loader = false;
// Open Snackbar
this.snackBar.open('Saved changes successfully.', 'Dismiss', {
duration: 3000,
});
this.router.navigate(['/profile']);
});
}
}
| mit |
gnuine/ubiquo_versions | lib/ubiquo_versions/extensions.rb | 357 | module UbiquoVersions
module Extensions
autoload :ActiveRecord, 'ubiquo_versions/extensions/active_record'
autoload :Helpers, 'ubiquo_versions/extensions/helpers'
end
end
ActiveRecord::Base.send(:include, UbiquoVersions::Extensions::ActiveRecord)
Ubiquo::Extensions::Loader.append_helper(:UbiquoController, UbiquoVersions::Extensions::Helpers)
| mit |
thewizardplusplus/wizard-budget | app/src/main/assets/web/scripts/main.js | 39555 | var LOADING_LOG_CLEAN_DELAY = 2000;
var LOADING_LOG = {
getTypeMark: function(type) {
if (type == 'success') {
return '<i class = "fa fa-check-circle"></i>';
} else if (type == 'error') {
return '<i class = "fa fa-times-circle"></i>';
} else {
return '<i class = "fa fa-info-circle"></i>';
}
},
getTypeClass: function(type) {
if (type == 'success' || type == 'error') {
return type;
} else {
return '';
}
},
addMessage: function(message, type) {
type = type || 'info';
var loading_log = $('.loading-log');
loading_log.show();
loading_log.prepend(
'<p '
+ 'class = "'
+ 'content-padded '
+ LOADING_LOG.getTypeClass(type)
+ '">'
+ LOADING_LOG.getTypeMark(type) + ' '
+ message
+ '</p>'
);
},
finish: function(callback, message, type) {
callback = callback || function() {};
message = message || 'All done.'
type = type || 'success';
LOADING_LOG.addMessage(message, type);
setTimeout(
function() {
LOADING_LOG.clean();
callback();
},
LOADING_LOG_CLEAN_DELAY
);
},
clean: function() {
var loading_log = $('.loading-log');
loading_log.empty();
loading_log.hide();
}
};
var HOURS_VIEW_PRECISION = 2;
function ProcessHours() {
var work_calendar = JSON.parse(activity.getSetting('work_calendar'));
var worked_hours = JSON.parse(activity.getSetting('worked_hours'));
var hours_start_date = moment(activity.getSetting('hours_start_date'));
var hours_end_date = moment(activity.getSetting('hours_end_date'));
var start_day = hours_start_date.date();
var end_day = hours_end_date.date();
var month_data = [];
if (work_calendar) {
month_data = work_calendar[hours_start_date.month()];
}
var current_date = new Date();
var is_current_month = current_date.getMonth() == hours_start_date.month();
var expected_hours = 0;
var month_worked_hours = 0;
var month_rest_days = 0;
for (var day = start_day; day <= end_day; day++) {
var day_type = month_data[day - 1];
if (typeof day_type !== 'undefined') {
if (!is_current_month || day <= current_date.getDate()) {
if (day_type === 'ordinary') {
expected_hours += 8;
} else if (day_type === 'short') {
expected_hours += 7;
}
} else {
if (day_type === 'ordinary' || day_type === 'short') {
month_rest_days++;
}
}
}
if (worked_hours) {
var day_worked_hours = worked_hours[day.toString()];
if (typeof day_worked_hours !== 'undefined') {
month_worked_hours += day_worked_hours;
}
}
}
var difference = expected_hours - month_worked_hours;
var working_off = difference / month_rest_days;
var hours_data = {
start_day: start_day,
expected_hours: expected_hours,
month_worked_hours: month_worked_hours,
difference: difference,
working_off: working_off,
working_off_mode:
(isNaN(working_off) || working_off == Number.NEGATIVE_INFINITY
? 'none'
: (working_off == Infinity
? 'infinity'
: 'normal'))
};
activity.setSetting('hours_data', JSON.stringify(hours_data));
ShowHours(hours_data);
activity.updateWidget();
}
function ShowHours(hours_data) {
var hours_range_start = moment().date(hours_data.start_day).format('ll');
$('.hours-range-start').text(hours_range_start);
var hours_view = $('#hours-segment .hours-view');
$('.expected-hours-view', hours_view).text(
hours_data.expected_hours
);
$('.hours-worked-view', hours_view).text(
hours_data.month_worked_hours.toFixed(HOURS_VIEW_PRECISION)
);
var difference_view = $('.difference-view', hours_view);
difference_view.text(
hours_data.difference.toFixed(HOURS_VIEW_PRECISION)
);
if (hours_data.difference <= 0) {
difference_view.removeClass('lack').addClass('excess');
} else {
difference_view.removeClass('excess').addClass('lack');
}
var working_off_view = $('.working-off-view', hours_view);
if (
!isNaN(hours_data.working_off)
&& hours_data.working_off != Number.NEGATIVE_INFINITY
) {
if (hours_data.working_off != Infinity) {
working_off_view.text(
hours_data.working_off.toFixed(HOURS_VIEW_PRECISION)
);
var working_off_limit = parseFloat(
activity.getSetting('working_off_limit')
);
if (hours_data.working_off <= working_off_limit) {
working_off_view.removeClass('lack').addClass('excess');
} else {
working_off_view.removeClass('excess').addClass('lack');
}
} else {
working_off_view.html('∞');
working_off_view.removeClass('excess').addClass('lack');
}
} else {
working_off_view.html('—');
working_off_view.removeClass('lack').addClass('excess');
}
}
function RequestToHarvest(request_name, path) {
var harvest_subdomain = activity.getSetting('harvest_subdomain');
var url = 'https://' + harvest_subdomain + '.harvestapp.com' + path;
var harvest_username = activity.getSetting('harvest_username');
var harvest_password = activity.getSetting('harvest_password');
var headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization:
'Basic '
+ Base64.encode(harvest_username + ':' + harvest_password)
};
activity.httpRequest(request_name, url, JSON.stringify(headers));
}
var HTTP_HANDLERS = {
harvest_user_id: function(data) {
LOADING_LOG.addMessage('Start the Harvest user ID processing.');
var parsed_data = JSON.parse(data);
var user_id = parsed_data.user.id;
var start = moment().startOf('month').format('YYYYMMDD');
var end = moment().format('YYYYMMDD');
var path =
'/people/'
+ user_id
+ '/entries?from='
+ start
+ '&to='
+ end;
LOADING_LOG.addMessage(
'The Harvest user ID processing has finished.',
'success'
);
RequestToHarvest('harvest_time_entries', path);
},
harvest_time_entries: function(data) {
LOADING_LOG.addMessage('Start the Harvest time entries processing.');
var parsed_data = JSON.parse(data);
var entries = Object.create(null);
for (var i = 0; i < parsed_data.length; i++) {
var entry = parsed_data[i].day_entry;
var day = entry.spent_at.split('-')[2].replace(/^0/, '');
if (!entries[day]) {
entries[day] = 0;
}
entries[day] += entry.hours;
}
activity.setSetting('worked_hours', JSON.stringify(entries));
LOADING_LOG.addMessage(
'The Harvest time entries processing has finished.',
'success'
);
activity.httpRequest(
'work_calendar',
'http://www.calend.ru/work/',
JSON.stringify(null)
);
},
work_calendar: function(data) {
LOADING_LOG.addMessage('Start the work calendar processing.');
var dom = $(data);
var work_hours = [];
$('.time_of_death > tbody > tr:not(:first-child) > td', dom).each(
function() {
var month = [];
$('tr:nth-child(n+3)', $(this)).each(
function() {
$('td', $(this)).each(
function(index) {
var element = $(this);
if (!element.hasClass('day')) {
return;
}
var day_type = 'ordinary';
if (element.hasClass('col5')) {
if (index < 6) {
day_type = 'holiday';
} else {
day_type = 'weekend';
}
} else if (element.hasClass('col6')) {
day_type = 'short';
}
month.push(day_type);
}
);
}
);
work_hours.push(month);
}
);
activity.setSetting('work_calendar', JSON.stringify(work_hours));
LOADING_LOG.addMessage(
'The work calendar processing has finished.',
'success'
);
ProcessHours();
LOADING_LOG.finish(
function() {
$('.refresh-button').removeClass('disabled');
}
);
}
};
var GUI = {
hideMainMenu: function() {
var event = new CustomEvent('touchend');
$('.backdrop').get(0).dispatchEvent(event);
},
refresh: function() {
activity.updateWidget();
activity.updateBuyWidget();
PUSH({url: 'history.html'});
},
back: function() {
if (!/\bhistory\b/.test(window.location)) {
PUSH({url: 'history.html'});
} else {
var remove_dialog = $('#remove-dialog');
if (remove_dialog.hasClass('active')) {
remove_dialog.removeClass('active');
} else {
remove_dialog = $('#remove-buy-dialog');
if (remove_dialog.hasClass('active')) {
remove_dialog.removeClass('active');
} else {
if ($('.popover').hasClass('visible')) {
this.hideMainMenu();
} else {
activity.quit();
}
}
}
}
},
addLoadingLogMessage: function(message) {
LOADING_LOG.addMessage(message);
},
setHttpResult: function(request, data) {
if (data.substr(0, 6) != 'error:') {
LOADING_LOG.addMessage(
'The "' + request + '" HTTP request has finished.',
'success'
);
var handler = HTTP_HANDLERS[request];
if (handler) {
handler(data);
}
} else {
LOADING_LOG.addMessage('Error: "' + data.substr(6) + '".', 'error');
}
},
debug: function(message) {
$('.debug').text(message);
}
};
$(document).ready(
function() {
function LoadActiveSpending() {
var json = activity.getSetting('active_spending');
SaveActiveSpending(null);
return JSON.parse(json);
}
function SaveActiveSpending(active_spending) {
var json = JSON.stringify(active_spending);
activity.setSetting('active_spending', json);
}
function LoadActiveBuy() {
var json = activity.getSetting('active_buy');
SaveActiveBuy(null);
return JSON.parse(json);
}
function SaveActiveBuy(active_buy) {
var json = JSON.stringify(active_buy);
activity.setSetting('active_buy', json);
}
function UpdateSpendingList() {
var SPENDING_PRECISION = 2;
var spendings_sum_view = $('.spendings-sum-view');
var spendings_sum = spending_manager.getSpendingsSum();
spendings_sum_view.text(spendings_sum);
if (spendings_sum <= 0) {
spendings_sum_view.addClass('excess').removeClass('lack');
} else {
spendings_sum_view.addClass('lack').removeClass('excess');
}
var spending_list = $('.spending-list');
spending_list.empty();
var raw_spendings = spending_manager.getAllSpendings();
var spendings = JSON.parse(raw_spendings);
spendings.map(
function(spending) {
spending_list.append(
'<li class = "table-view-cell media">'
+ '<button '
+ 'class = "btn second-list-button '
+ 'edit-spending-button"'
+ 'data-spending-id = "' + spending.id + '"'
+ 'data-income = "'
+ (spending.amount < 0
? 'true'
: 'false') + '"'
+ 'data-timestamp = "'
+ spending.timestamp + '">'
+ '<i class = "fa fa-pencil"></i>'
+ '</button>'
+ '<button '
+ 'class = "btn remove-spending-button"'
+ 'data-spending-id = "' + spending.id + '">'
+ '<i class = "fa fa-trash"></i>'
+ '</button>'
+ '<span '
+ 'class = "'
+ 'media-object '
+ 'pull-left '
+ 'mark-container'
+ '">'
+ (spending.has_credit_card_tag
? '<i class = "fa fa-credit-card mark"></i>'
: '')
+ '<i class = "fa fa-'
+ (spending.amount > 0
? 'shopping-cart'
: 'money')
+ ' fa-2x"></i>'
+ '</span>'
+ '<div class = "media-body">'
+ '<p>'
+ '<span class = "underline">'
+ '<strong>'
+ '<span class = "date-view">'
+ spending.date
+ '</span>'
+ '</strong> '
+ '<span class = "time-view">'
+ spending.time
+ '</span>:'
+ '</span>'
+ '</p>'
+ '<p>'
+ '<span class = "amount-view">'
+ Math
.abs(spending.amount)
.toFixed(SPENDING_PRECISION)
+ '</span> '
+ '<i class = "fa fa-ruble"></i>'
+ (spending.comment.length
? ' — '
+ '<em>'
+ '<span '
+ 'class = "comment-view">'
+ spending.comment
+ '</span>'
+ '</em>'
: '')
+ '.</p>'
+ '</div>'
+ '</li>'
);
}
);
var remove_dialog = $('#remove-dialog');
$('.close-remove-dialog', remove_dialog).click(
function() {
remove_dialog.removeClass('active');
SaveActiveSpending(null);
return false;
}
);
var remove_dialog_date_view = $('.date-view', remove_dialog);
var remove_dialog_time_view = $('.time-view', remove_dialog);
var remove_dialog_amount_view = $('.amount-view', remove_dialog);
var remove_dialog_comment_view = $('.comment-view', remove_dialog);
$('.remove-spending-button', remove_dialog).click(
function() {
var active_spending = LoadActiveSpending();
if ($.type(active_spending) !== "null") {
spending_manager.deleteSpending(active_spending.id);
activity.updateWidget();
PUSH({url: 'history.html'});
}
}
);
$('.edit-spending-button', spending_list).click(
function() {
var button = $(this);
active_spending = {};
active_spending.id = parseInt(button.data('spending-id'));
active_spending.income_flag =
button.data('income')
? true
: null;
var timestamp = moment(
parseInt(button.data('timestamp')) * 1000
);
active_spending.date = timestamp.format('YYYY-MM-DD');
active_spending.time = timestamp.format('HH:mm');
var list_item = button.parent();
active_spending.amount =
$('.amount-view', list_item)
.text();
active_spending.comment =
$('.comment-view', list_item)
.text();
SaveActiveSpending(active_spending);
PUSH({url: 'editor.html'});
}
);
$('.remove-spending-button', spending_list).click(
function() {
var button = $(this);
active_spending = {};
active_spending.id = parseInt(button.data('spending-id'));
SaveActiveSpending(active_spending);
var list_item = button.parent();
var date = $('.date-view', list_item).text();
var time = $('.time-view', list_item).text();
var amount = $('.amount-view', list_item).text();
var comment = $('.comment-view', list_item).text();
remove_dialog_date_view.text(date);
remove_dialog_time_view.text(time);
remove_dialog_amount_view.text(amount);
if (comment.length) {
remove_dialog_comment_view.html(' — ' + comment);
}
remove_dialog.addClass('active');
}
);
}
function UpdateBuyList() {
var BUY_COST_PRECISION = 2;
var total_costs_sum_view = $('.total-costs-sum-view');
var total_costs_sum = buy_manager.getAnyCostsSum();
total_costs_sum_view.text(total_costs_sum);
var monthly_costs_sum_view = $('.monthly-costs-sum-view');
var monthly_costs_sum = buy_manager.getMonthlyCostsSum();
monthly_costs_sum_view.text(monthly_costs_sum);
var single_costs_sum_view = $('.single-costs-sum-view');
var single_costs_sum = buy_manager.getSingleCostsSum();
single_costs_sum_view.text(single_costs_sum);
var buy_list = $('.buy-list');
buy_list.empty();
var raw_buys = buy_manager.getAllBuys();
var buys = JSON.parse(raw_buys);
buys.map(
function(buy) {
buy_list.append(
'<li '
+ 'class = "'
+ 'table-view-cell '
+ 'media '
+ (buy.status
? 'buyed'
: 'not-buyed') + '"'
+ 'data-id = "' + buy.id + '">'
+ '<button '
+ 'class = "btn second-list-button '
+ 'edit-buy-button"'
+ 'data-buy-id = "' + buy.id + '"'
+ 'data-status = "' + buy.status + '"'
+ 'data-monthly = "' + buy.monthly + '">'
+ '<i class = "fa fa-pencil"></i>'
+ '</button>'
+ '<button '
+ 'class = "btn remove-buy-button"'
+ 'data-buy-id = "' + buy.id + '">'
+ '<i class = "fa fa-trash"></i>'
+ '</button>'
+ '<span '
+ 'class = "'
+ 'media-object '
+ 'pull-left '
+ 'mark-container'
+ '">'
+ (buy.monthly
? '<i class = "fa fa-calendar mark"></i>'
: '')
+ '<i '
+ 'class = "'
+ 'fa '
+ 'fa-' + (buy.status
? 'gift'
: 'shopping-cart') + ' '
+ 'fa-2x'
+ '">'
+ '</i>'
+ '</span>'
+ '<div class = "media-body">'
+ '<p>'
+ '<span class = "underline">'
+ '<strong>'
+ '<span class = "name-view">'
+ buy.name
+ '</span>:'
+ '</strong>'
+ '</span>'
+ '</p>'
+ '<p>'
+ '<span class = "cost-view">'
+ buy.cost.toFixed(BUY_COST_PRECISION)
+ '</span> '
+ '<i class = "fa fa-ruble"></i>.'
+ '</p>'
+ '</div>'
+ '</li>'
);
}
);
var remove_dialog = $('#remove-buy-dialog');
$('.close-remove-dialog', remove_dialog).click(
function() {
remove_dialog.removeClass('active');
SaveActiveBuy(null);
return false;
}
);
var remove_dialog_name_view = $('.name-view', remove_dialog);
var remove_dialog_cost_view = $('.cost-view', remove_dialog);
$('.remove-buy-button', remove_dialog).click(
function() {
var active_buy = LoadActiveBuy();
if ($.type(active_buy) !== "null") {
buy_manager.deleteBuy(active_buy.id);
activity.updateWidget();
activity.updateBuyWidget();
PUSH({url: 'history.html'});
}
}
);
$('.edit-buy-button', buy_list).click(
function() {
var button = $(this);
active_buy = {};
active_buy.id = parseInt(button.data('buy-id'));
active_buy.status =
button.data('status')
? true
: null;
active_buy.monthly =
button.data('monthly')
? true
: null;
var list_item = button.parent();
active_buy.name = $('.name-view', list_item).text();
active_buy.cost = $('.cost-view', list_item).text();
SaveActiveBuy(active_buy);
PUSH({url: 'buy_editor.html'});
}
);
$('.remove-buy-button', buy_list).click(
function() {
var button = $(this);
active_buy = {};
active_buy.id = parseInt(button.data('buy-id'));
SaveActiveBuy(active_buy);
var list_item = button.parent();
var name = $('.name-view', list_item).text();
var cost = $('.cost-view', list_item).text();
remove_dialog_name_view.text(name);
remove_dialog_cost_view.text(cost);
remove_dialog.addClass('active');
}
);
buy_list.sortable(
{
draggable: '.not-buyed',
handle: '.media-object',
ghostClass: 'placeholder',
onStart: function(event) {
var item = $('li', buy_list)
.filter(
function() {
return $(this).css('position') == 'fixed';
}
)
.addClass('moving');
setTimeout(
function() {
var position = item.offset();
position.top -= 95;
item.offset(position);
},
1
);
},
onUpdate: function() {
var order = $('li', buy_list).map(
function() {
return $(this).data('id');
}
);
var serialized_order = JSON.stringify(order.get());
buy_manager.updateBuyOrder(serialized_order);
}
}
);
}
function UpdateControlButtons() {
$('.backup-button').click(
function() {
GUI.hideMainMenu();
var filename = backup_manager.backup();
if (
activity.getSetting('save_backup_to_dropbox') == "true"
&& filename.length
) {
activity.saveToDropbox(filename);
}
}
);
$('.restore-button').click(
function() {
GUI.hideMainMenu();
activity.selectBackupForRestore();
}
);
$('.settings-button').click(
function() {
GUI.hideMainMenu();
activity.openSettings();
}
);
$('.add-button').click(
function() {
if ($('#buys-segment').hasClass('active')) {
PUSH({url: 'buy_editor.html'});
} else {
PUSH({url: 'editor.html'});
}
}
);
}
function SetCurrentSegment(current_segment) {
$('.control-item, .control-content').removeClass('active');
$('.' + current_segment + '-segment').addClass('active');
}
function UpdateHoursDataIfNeed() {
if (
activity.getSetting('current_segment') == 'hours'
&& activity.getSetting('analysis_harvest') === 'true'
) {
if (activity.getSetting('need_update_hours') === 'true') {
activity.setSetting('need_update_hours', 'false');
$('.refresh-button').click();
}
}
}
function UpdateSegments() {
var RESET_SEGMENT_TIMEOUT = 100;
var current_segment = activity.getSetting('current_segment');
if (
(current_segment == 'stats'
&& activity.getSetting('collect_stats') !== 'true')
|| (current_segment == 'hours'
&& activity.getSetting('analysis_harvest') !== 'true')
) {
current_segment = 'history';
activity.setSetting('current_segment', 'history');
}
SetCurrentSegment(current_segment);
if (activity.getSetting('collect_stats') !== 'true') {
$('.stats-segment').hide();
}
if (activity.getSetting('analysis_harvest') !== 'true') {
$('.hours-segment').hide();
}
var add_button = $('.add-button');
if (current_segment == 'stats' || current_segment == 'hours') {
add_button.hide();
} else {
add_button.show();
}
var refresh_button = $('.refresh-button');
if (current_segment == 'hours') {
refresh_button.show();
} else {
refresh_button.hide();
}
$('.control-item').on(
'touchend',
function() {
var self = $(this);
if (self.hasClass('buys-segment')) {
activity.setSetting('current_segment', 'buys');
add_button.show();
refresh_button.hide();
} else if (self.hasClass('stats-segment')) {
if (
activity.getSetting('collect_stats') === 'true'
) {
activity.setSetting('current_segment', 'stats');
add_button.hide();
refresh_button.hide();
} else {
activity.setSetting('current_segment', 'history');
add_button.show();
refresh_button.hide();
setTimeout(
function() {
SetCurrentSegment('history');
},
RESET_SEGMENT_TIMEOUT
);
}
} else if (self.hasClass('hours-segment')) {
if (
activity.getSetting('analysis_harvest') === 'true'
) {
activity.setSetting('current_segment', 'hours');
add_button.hide();
refresh_button.show();
} else {
activity.setSetting('current_segment', 'history');
add_button.show();
refresh_button.hide();
setTimeout(
function() {
SetCurrentSegment('history');
},
RESET_SEGMENT_TIMEOUT
);
}
} else {
activity.setSetting('current_segment', 'history');
add_button.show();
refresh_button.hide();
}
}
);
}
function DrawStatsView(number_of_last_days, comment_prefix) {
var spendings_sum_view = $('.stats-sum-view');
var spendings_sum = spending_manager.getStatsSum(
number_of_last_days,
comment_prefix
);
spendings_sum_view.text(spendings_sum);
var selected_tag_list = $('.selected-tag-list');
selected_tag_list.empty();
var selected_tags =
comment_prefix
.split(',')
.map(
function(tag) {
return tag.trim();
}
)
.filter(
function(tag) {
return tag.length != 0;
}
);
var selected_tags_copy = selected_tags.slice();
selected_tags.unshift('root');
selected_tags.map(
function(tag, index) {
var list_item = '';
if (index != 0) {
list_item += ' / ';
}
if (index < selected_tags.length - 1) {
list_item +=
'<button '
+ 'class = "btn btn-info unselect-tag-button"'
+ 'data-tag = "' + escape(tag) + '">'
+ tag
+ '</button>';
} else {
list_item += tag;
}
selected_tag_list.append(list_item);
}
);
$('.unselect-tag-button', selected_tag_list).click(
function() {
var self = $(this);
var tag = unescape(self.data('tag'));
var new_comment_prefix = '';
var index = selected_tags_copy.lastIndexOf(tag);
if (index != -1) {
new_comment_prefix =
selected_tags_copy
.slice(
0,
index + 1
)
.join(', ');
}
activity.setSetting('stats_tags', new_comment_prefix);
DrawStatsView(number_of_last_days, new_comment_prefix);
}
);
var stats_view = $('.stats-view tbody');
stats_view.empty();
var raw_stats = spending_manager.getStats(
number_of_last_days,
comment_prefix
);
var stats = JSON.parse(raw_stats);
stats = stats.sort(
function(first, second) {
return second.sum - first.sum;
}
);
var maximal_sum = 0;
stats.forEach(
function(row) {
if (row.sum > maximal_sum) {
maximal_sum = row.sum;
}
}
);
stats.forEach(
function(row) {
var percents = 100 * row.sum / maximal_sum;
var percents_string =
percents
.toFixed(2)
.replace(/(\.0)?0+$/g, '$1');
stats_view.append(
'<tr>'
+ '<td class = "tag-column">'
+ '<button '
+ 'class = "'
+ 'btn '
+ 'btn-info '
+ 'select-tag-button'
+ '"'
+ 'data-tag = "' + escape(row.tag) + '"'
+ (row.is_rest
? 'disabled = "disabled"'
: '') + '>'
+ (row.is_rest
? '<em>rest</em>'
: row.tag)
+ '</button>'
+ '</td>'
+ '<td class = "sum-column">'
+ row.sum + ' '
+ '<i class = "fa fa-ruble"></i><br />'
+ '<em>(' + percents_string + '%)</em>'
+ '</td>'
+ '<td class = "view-column">'
+ '<progress '
+ 'max = "' + maximal_sum + '"'
+ 'value = "' + row.sum + '">'
+ '</progress>'
+ '</td>'
+ '</tr>'
);
}
);
$('.select-tag-button', stats_view).click(
function() {
var self = $(this);
var tag = unescape(self.data('tag'));
var new_comment_prefix = comment_prefix;
if (new_comment_prefix.length) {
new_comment_prefix += ', ';
}
new_comment_prefix += tag;
activity.setSetting('stats_tags', new_comment_prefix);
DrawStatsView(number_of_last_days, new_comment_prefix);
}
);
}
function UpdateStats() {
var STATS_RANGE_SAVING_TIMEOUT = 500;
$('.stats-range-form').on(
'submit',
function(event) {
event.preventDefault();
return false;
}
);
var number_of_last_days = activity.getSetting('stats_range');
var range_editor = $('.stats-range-editor');
range_editor.val(number_of_last_days);
var integral_range = parseInt(number_of_last_days);
if (integral_range == 0) {
$('.stats-range-view').hide();
$('.stats-range-dummy').show();
} else {
$('.stats-range-view').show();
var stats_range_start =
moment()
.subtract(integral_range, 'd')
.format('ll');
$('.stats-range-start').text(stats_range_start);
$('.stats-range-dummy').hide();
}
$('.stats-range-end').text(moment().format('ll'));
var comment_prefix = activity.getSetting('stats_tags');
var range_update_timer = null;
range_editor.on(
'keyup',
function() {
clearTimeout(range_update_timer);
range_update_timer = setTimeout(
function() {
var number_of_last_days = range_editor.val();
activity.setSetting(
'stats_range',
number_of_last_days
);
var integral_range = parseInt(number_of_last_days);
if (integral_range == 0) {
$('.stats-range-view').hide();
$('.stats-range-dummy').show();
} else {
$('.stats-range-view').show();
var stats_range_start =
moment()
.subtract(integral_range, 'd')
.format('ll');
$('.stats-range-start').text(stats_range_start);
$('.stats-range-dummy').hide();
}
DrawStatsView(integral_range, comment_prefix);
},
STATS_RANGE_SAVING_TIMEOUT
);
}
);
DrawStatsView(integral_range, comment_prefix);
}
function UpdateHours() {
$('.hours-range-form').on(
'submit',
function(event) {
event.preventDefault();
return false;
}
);
var hours_start_date = activity.getSetting('hours_start_date');
var hours_start_date_editor = $('.hours-range-start-editor');
hours_start_date_editor.val(hours_start_date);
var hours_end_date = activity.getSetting('hours_end_date');
var hours_end_date_editor = $('.hours-range-end-editor');
hours_end_date_editor.val(hours_end_date);
hours_start_date_editor.change(
function() {
var self = $(this);
var new_date = self.val();
var wrapped_new_date = moment(new_date);
var current_year = moment().year();
if (wrapped_new_date.year() != current_year) {
wrapped_new_date = wrapped_new_date.year(current_year);
new_date = wrapped_new_date.format('YYYY-MM-DD');
self.val(new_date);
}
activity.setSetting('hours_start_date', new_date);
var hours_end_date = moment(hours_end_date_editor.val());
var new_month = wrapped_new_date.month();
if (hours_end_date.month() != new_month) {
var new_hours_end_date =
hours_end_date
.month(new_month)
.endOf('month');
var formatted_new_hours_end_date =
new_hours_end_date
.format('YYYY-MM-DD');
hours_end_date_editor.val(formatted_new_hours_end_date);
activity.setSetting(
'hours_end_date',
formatted_new_hours_end_date
);
}
ProcessHours();
}
);
hours_end_date_editor.change(
function() {
var self = $(this);
var new_date = self.val();
var wrapped_new_date = moment(new_date);
var current_year = moment().year();
if (wrapped_new_date.year() != current_year) {
new_date =
wrapped_new_date
.year(current_year)
.format('YYYY-MM-DD');
self.val(new_date);
}
activity.setSetting('hours_end_date', new_date);
var hours_start_date = moment(
hours_start_date_editor.val()
);
var new_month = wrapped_new_date.month();
if (hours_start_date.month() != new_month) {
var new_hours_start_date =
hours_start_date
.month(new_month)
.startOf('month');
var formatted_new_hours_start_date =
new_hours_start_date
.format('YYYY-MM-DD');
hours_start_date_editor.val(
formatted_new_hours_start_date
);
activity.setSetting(
'hours_start_date',
formatted_new_hours_start_date
);
}
ProcessHours();
}
);
$('.refresh-button').click(
function() {
var self = $(this);
if (!self.hasClass('disabled')) {
self.addClass('disabled');
} else {
return;
}
RequestToHarvest('harvest_user_id', '/account/who_am_i');
}
);
ProcessHours();
}
function UpdateIndexPage() {
UpdateControlButtons();
UpdateSegments();
UpdateSpendingList();
UpdateBuyList();
UpdateStats();
UpdateHours();
UpdateHoursDataIfNeed();
}
function UpdateEditorPage() {
var CORRECT_SPENDING_PRECISION = 6;
var active_spending = LoadActiveSpending();
var edit_spending_button = $('form .edit-spending-button');
var spending_type = $('form .spending-type');
if ($.type(active_spending) === "null") {
$('.title').text('Add spending');
$('.button-icon', edit_spending_button)
.removeClass('fa-save')
.addClass('fa-plus');
$('.button-text', edit_spending_button).text('Add');
} else {
$('.title').text('Edit spending');
$('.button-icon', edit_spending_button)
.removeClass('fa-plus')
.addClass('fa-save');
$('.button-text', edit_spending_button).text('Save');
$('option[value=sum]', spending_type).hide();
}
var date_editor = $('.date-editor');
if ($.type(active_spending) !== "null") {
date_editor.val(active_spending.date);
date_editor.show();
}
var time_editor = $('.time-editor');
if ($.type(active_spending) !== "null") {
time_editor.val(active_spending.time);
time_editor.show();
}
if ($.type(active_spending) !== "null") {
$('hr').show();
}
var amount_editor = $('.amount-editor');
if ($.type(active_spending) !== "null") {
amount_editor.val(active_spending.amount);
}
amount_editor.focus();
var raw_tags = spending_manager.getSpendingTags();
var tags = JSON.parse(raw_tags);
var raw_buy_names = buy_manager.getBuyNames();
var buy_names = JSON.parse(raw_buy_names);
tags = tags.concat(buy_names);
var raw_priorities_tags = spending_manager.getPrioritiesTags();
var priorities_tags = JSON.parse(raw_priorities_tags);
var default_tags =
$.type(active_spending) !== "null"
? active_spending.comment.split(',')
: [];
var tags_editor = new WizardTags(
'.tags-editor',
{
tags: tags,
search_mode: 'words',
sort: 'priorities-desc',
priorities_tags: priorities_tags,
default_tags: default_tags,
separators: ',',
only_unique: true
}
);
if (
$.type(active_spending) !== "null"
&& active_spending.income_flag
) {
spending_type.val('income');
} else {
spending_type.val('spending');
}
edit_spending_button.click(
function() {
var signed_amount = parseFloat(amount_editor.val());
var amount = Math.abs(signed_amount);
tags_editor.addCurrentText();
var tags = tags_editor.getTags();
var comment = tags.join(', ');
if (spending_type.val() == 'income') {
amount *= -1;
} else if (spending_type.val() == 'sum') {
var sum = parseFloat(
spending_manager.getSpendingsSum()
);
var difference = signed_amount - sum;
amount = parseFloat(
difference.toFixed(CORRECT_SPENDING_PRECISION)
);
}
if ($.type(active_spending) === "null") {
spending_manager.createSpending(amount, comment);
} else {
var date = date_editor.val();
var time = time_editor.val();
spending_manager.updateSpending(
active_spending.id,
date,
time,
amount,
comment
);
}
var serialized_tags = JSON.stringify(tags);
buy_manager.mayBeBuy(serialized_tags);
activity.updateWidget();
activity.updateBuyWidget();
PUSH({url: 'history.html'});
return false;
}
);
}
function UpdateBuyEditorPage() {
var active_buy = LoadActiveBuy();
var edit_buy_button = $('form .edit-buy-button');
if ($.type(active_buy) === "null") {
$('.title').text('Add buy');
$('.button-icon', edit_buy_button)
.removeClass('fa-save')
.addClass('fa-plus');
$('.button-text', edit_buy_button).text('Add');
} else {
$('.title').text('Edit buy');
$('.button-icon', edit_buy_button)
.removeClass('fa-plus')
.addClass('fa-save');
$('.button-text', edit_buy_button).text('Save');
}
var name_editor = $('.name-editor');
if ($.type(active_buy) !== "null") {
name_editor.val(active_buy.name);
}
name_editor.focus();
var cost_editor = $('.cost-editor');
if ($.type(active_buy) !== "null") {
cost_editor.val(active_buy.cost);
}
var status_flag = $('.status');
if ($.type(active_buy) !== "null") {
if (active_buy.status) {
status_flag.addClass('active');
}
} else {
status_flag.parent().hide();
}
var monthly_flag = $('.monthly');
if ($.type(active_buy) !== "null") {
if (active_buy.monthly) {
monthly_flag.addClass('active');
}
}
edit_buy_button.click(
function() {
var name = name_editor.val();
var cost = parseFloat(cost_editor.val());
var status = status_flag.hasClass('active') ? 1 : 0;
var monthly = monthly_flag.hasClass('active') ? 1 : 0;
if ($.type(active_buy) === "null") {
buy_manager.createBuy(name, cost, monthly);
} else {
buy_manager.updateBuy(
active_buy.id,
name,
cost,
status,
monthly
);
}
activity.updateWidget();
activity.updateBuyWidget();
PUSH({url: 'history.html'});
return false;
}
);
}
function UpdateSmsPage() {
var UPDATE_INPUT_BUTTON_TIMEOUT = 100;
var sms_list = $('.sms-list');
sms_list.empty();
var raw_spendings = spending_manager.getSpendingsFromSms();
var spendings = JSON.parse(raw_spendings);
spendings.map(
function(spending) {
sms_list.append(
'<li '
+ 'class = "table-view-cell media" '
+ 'data-timestamp = "'
+ spending.timestamp
+ '" '
+ 'data-amount = "' + spending.amount + '" '
+ 'data-residue = "' + spending.residue + '">'
+ '<div class = "toggle import-flag">'
+ '<div class = "toggle-handle"></div>'
+ '</div>'
+ '<span class = "'
+ 'media-object '
+ 'pull-left '
+ 'mark-container'
+ '">'
+ '<i class = "fa fa-credit-card mark"></i>'
+ '<i class = "fa fa-'
+ (spending.amount > 0
? 'shopping-cart'
: 'money')
+ ' fa-2x"></i>'
+ '</span>'
+ '<div class = "media-body">'
+ '<p>'
+ '<span class = "underline">'
+ '<strong>'
+ spending.date
+ '</strong>'
+ ' ' + spending.time + ':'
+ '</span>'
+ '</p>'
+ '<p>'
+ Math.abs(spending.amount)
+ '<i class = "fa fa-ruble"></i>.'
+ '</p>'
+ '</div>'
+ '</li>'
);
}
);
var import_button = $('.import-sms-button');
import_button.click(
function() {
var sms_data = [];
$('li', sms_list).each(
function() {
var list_item = $(this);
if ($('.import-flag.active', list_item).length) {
sms_data.push(
{
timestamp: list_item.data('timestamp'),
amount: list_item.data('amount'),
residue: list_item.data('residue'),
}
);
}
}
);
var sms_data_in_string = JSON.stringify(sms_data);
spending_manager.importSms(sms_data_in_string);
activity.updateWidget();
activity.setSetting('current_segment', 'history');
PUSH({url: 'history.html'});
}
);
var UpdateImportButton = function() {
if ($('.sms-list .import-flag.active').length) {
import_button.show();
} else {
import_button.hide();
}
};
$('.sms-list').click(
function() {
setTimeout(UpdateImportButton, UPDATE_INPUT_BUTTON_TIMEOUT);
}
);
UpdateImportButton();
}
window.addEventListener(
'push',
function(event) {
if (/\bhistory\b/.test(event.detail.state.url)) {
activity.setSetting('current_page', 'history');
UpdateIndexPage();
} else if (/\beditor\b/.test(event.detail.state.url)) {
activity.setSetting('current_page', 'editor');
UpdateEditorPage();
} else if (/\bbuy_editor\b/.test(event.detail.state.url)) {
activity.setSetting('current_page', 'buy_editor');
UpdateBuyEditorPage();
} else if (/\bsms\b/.test(event.detail.state.url)) {
activity.setSetting('current_page', 'sms');
UpdateSmsPage();
} else if (/\bauthors\b/.test(event.detail.state.url)) {
activity.setSetting('current_page', 'authors');
} else {
activity.setSetting('current_page', 'history');
}
}
);
PUSH({url: activity.getSetting('current_page') + '.html'});
}
);
| mit |
mastermike14/imdb | lib/imdb/movie_list.rb | 961 | module Imdb
class MovieList
def movies
@movies ||= parse_movies
end
private
def parse_movies
document.search("a[@href^='/title/tt']").reject do |element|
element.inner_html.imdb_strip_tags.empty? ||
element.inner_html.imdb_strip_tags == "X" ||
element.parent.inner_html =~ /media from/i
end.map do |element|
id = element['href'][/\d+/]
data = element.parent.inner_html.split("<br />")
title = (!data[0].nil? && !data[1].nil? && data[0] =~ /img/) ? data[1] : data[0]
title = title.imdb_strip_tags.imdb_unescape_html
title.gsub!(/\s+\(\d\d\d\d\)$/, '')
alternative_titles = []
if title =~ /\saka\s/
titles = title.split(/\saka\s/)
title = titles.shift.strip.imdb_unescape_html
end
[id, title]
end.uniq.map do |values|
Imdb::Movie.new(*values)
end
end
end # MovieList
end # Imdb
| mit |
QuinntyneBrown/azure-search-getting-started | src/Chloe/Server/Dtos/ProductsViewContainerComponentAddOrUpdateResponseDto.cs | 331 | using Chloe.Server.Models;
namespace Chloe.Server.Dtos
{
public class ProductsViewContainerComponentAddOrUpdateResponseDto: ProductsViewContainerComponentDto
{
public ProductsViewContainerComponentAddOrUpdateResponseDto(ProductsViewContainerComponent entity)
:base(entity)
{
}
}
}
| mit |
matis140/BeeKeeper | e2e-tests/scenarios.js | 932 | 'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
describe('BeeKeeper app', function() {
it('should automatically redirect to /home when location hash/fragment is empty', function() {
browser.get('index.html');
expect(browser.getLocationAbsUrl()).toMatch("/home");
});
describe('home', function() {
beforeEach(function() {
browser.get('index.html#/home');
});
it('should render home when user navigates to /home', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for home/);
});
});
describe('diary', function() {
beforeEach(function() {
browser.get('index.html#/diary');
});
it('should render view2 when user navigates to /diary', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for diary/);
});
});
});
| mit |
Quantisan/WholeCell | simulation/doc/doxygen/html/class_transcription.js | 864 | var class_transcription =
[
[ "plotBound_Transcription_Factors", "class_transcription.html#a11f7566cf08407dad38696e22c8a2dcf", null ],
[ "plotNMPs", "class_transcription.html#a3e0acc8ade4757b798dd9a00406b0e25", null ],
[ "plotNTPs", "class_transcription.html#a80e75448c1cdfc7eeef9a010f862b36c", null ],
[ "plotRNA_Polymerase_Bound_Transcription_Units", "class_transcription.html#ae1b6c49b56bfc9876d6c47f3e49f0751", null ],
[ "plotRNA_Polymerase_State_Occupancies", "class_transcription.html#a2f72f65b804b07d6fa350be536b6dff8", null ],
[ "plotRNA_Polymerase_States", "class_transcription.html#a07f6f02cd3ea84f0898226e660817b2a", null ],
[ "plotRNA_Polymerases", "class_transcription.html#a9abeb1f927aa16ba9079d31e2ea3eceb", null ],
[ "plotTranscription_Limits", "class_transcription.html#ab788626de719b2646a267c5310eeea6c", null ]
]; | mit |
thilehoffer/Student-Assessment-Web | KindAssessment/KindAssessment/Scripts/TypeScript/Assessments/ScoreCard.js | 1066 | var App;
(function (App) {
var Assessments;
(function (Assessments) {
var ScoreCard = (function () {
function ScoreCard(total, $countElement, $totalElement) {
this.total = total;
this.$countElement = $countElement;
this.$totalElement = $totalElement;
this.$totalElement.html(total.toString());
}
ScoreCard.prototype.setScore = function (score) {
console.log("current score is " + score.toString());
this.$countElement.html(score.toString());
};
ScoreCard.prototype.allCorrect = function () {
this.$countElement.text(this.total);
};
ScoreCard.prototype.allIncorrect = function () {
this.$countElement.text("0");
};
return ScoreCard;
}());
Assessments.ScoreCard = ScoreCard;
})(Assessments = App.Assessments || (App.Assessments = {}));
})(App || (App = {}));
//# sourceMappingURL=ScoreCard.js.map | mit |
wazsmwazsm/QinBlog | application/home/views/home/archive.php | 687 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="uk-width-medium-1-1">
<div class="position">
<span>当前位置 : <?php echo anchor('Home/index','首页'); ?> -> <?php echo anchor('Home/archive','归档'); ?></span>
</div>
<div class="uk-panel uk-panel-box">
<h3 class="uk-panel-title uk-text-bold uk-text-primary">月份归档</h3>
<ul id="normal_links" class="uk-list">
<?php foreach($archives as $archive => $count): ?>
<?php echo anchor('Article/article_list/archive/'.strtotime($archive), $archive.' ('.$count.')'); ?>
<?php endforeach; ?>
</div>
</div> | mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_91/safe/CWE_91__exec__func_FILTER-CLEANING-number_float_filter__ID_test-concatenation_simple_quote.php | 1586 | <?php
/*
Safe sample
input : use exec to execute the script /tmp/tainted.php and store the output in $tainted
Uses a number_float_filter via filter_var function
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$script = "/tmp/tainted.php";
exec($script, $result, $return);
$tainted = $result[0];
$sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_FLOAT);
if (filter_var($sanitized, FILTER_VALIDATE_FLOAT))
$tainted = $sanitized ;
else
$tainted = "" ;
$query = "//User[@id='". $tainted . "']";
$xml = simplexml_load_file("users.xml");//file load
echo "query : ". $query ."<br /><br />" ;
$res=$xml->xpath($query);//execution
print_r($res);
echo "<br />" ;
?> | mit |
mibitzi/stwm | entities/workspace/workspace_test.go | 1538 | package workspace
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/mibitzi/stwm/layout/tiling"
"github.com/mibitzi/stwm/rect"
"github.com/mibitzi/stwm/test/client"
)
func TestAddClient(t *testing.T) {
ws := New("ws", tiling.New(rect.New(0, 0, 100, 100)))
ws.Show()
client := client.New()
assert.NoError(t, ws.AddClient(client), "AddClient")
assert.True(t, ws.HasClient(client.Id()), "ws.HasClient")
assert.True(t, ws.tiling.HasClient(client.Id()), "ws.tiling.HasClient")
assert.True(t, client.Visible(), "client.IsVisible")
}
func TestAddClientHidden(t *testing.T) {
ws := New("ws", tiling.New(rect.New(0, 0, 100, 100)))
ws.Hide()
client := client.New()
ws.AddClient(client)
assert.False(t, client.Visible(), "client.IsVisible")
}
func TestShowHide(t *testing.T) {
ws := New("ws", tiling.New(rect.New(0, 0, 100, 100)))
ws.Show()
client0 := client.New()
client1 := client.New()
ws.AddClient(client0)
ws.AddClient(client1)
ws.Hide()
assert.False(t, client0.Visible(), "client0.IsVisible")
assert.False(t, client1.Visible(), "client1.IsVisible")
ws.Show()
assert.True(t, client0.Visible(), "client0.IsVisible")
assert.True(t, client1.Visible(), "client1.IsVisible")
}
func TestRemoveClient(t *testing.T) {
ws := New("ws", tiling.New(rect.New(0, 0, 100, 100)))
ws.Show()
client := client.New()
ws.AddClient(client)
ws.RemoveClient(client)
assert.False(t, ws.HasClient(client.Id()), "ws.HasClient")
assert.False(t, ws.tiling.HasClient(client.Id()), "ws.tiling.HasClient")
}
| mit |
Serulab/Py4Bio | code/ch14/scatter.py | 618 | from bokeh.charts import Scatter, output_file, show
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [2.1, 6.45, 3, 1.4, 4.55, 3.85, 5.2, 0.7]
z = [.5, 1.1, 1.9, 2.5, 3.1, 3.9, 4.85, 5.2]
species = ['cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'mouse', 'mouse']
country = ['US', 'US', 'US', 'US', 'UK', 'UK', 'BR', 'BR']
df = {'time': x, 'weight 1': y, 'weight 2': z, 'species':species, 'country': country}
scatter = Scatter(df, x='time', y='weight 1', color='country', marker='species',
title="Auto MPG", xlabel="Time in days",
ylabel="Weight in grams")
output_file('scatter.html')
show(scatter)
| mit |
PaulSolt/GLUT-Object-Oriented-Framework | src/PerformanceTimer.cpp | 2790 | /*
* The MIT License
*
* Copyright (c) 2010 Paul Solt, PaulSolt@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "PerformanceTimer.h"
namespace glutFramework {
PerformanceTimer::PerformanceTimer() {
#ifdef WIN32
QueryPerformanceFrequency(&_freq); // Retrieves the frequency of the high-resolution performance counter
_start.QuadPart = 0;
_end.QuadPart = 0;
#else
_start.tv_sec = 0;
_start.tv_usec = 0;
_end.tv_sec = 0;
_end.tv_usec = 0;
#endif
_isStopped = true;
}
PerformanceTimer::~PerformanceTimer() {
}
void PerformanceTimer::start() {
#ifdef WIN32
QueryPerformanceCounter(&_start); // Retrieves the current value of the high-resolution performance counter
#else
gettimeofday(&_start, NULL); // Get the starting time
#endif
_isStopped = false;
}
void PerformanceTimer::stop() {
#ifdef WIN32
QueryPerformanceCounter(&_end);
#else
gettimeofday(&_end, NULL);
#endif
_isStopped = true;
}
bool PerformanceTimer::isStopped() const {
return _isStopped;
}
double PerformanceTimer::getElapsedMicroseconds() {
double microSecond = 0;
if(!_isStopped) {
#ifdef WIN32
QueryPerformanceCounter(&_end);
#else
gettimeofday(&_end, NULL);
#endif
}
#ifdef WIN32
if(_start.QuadPart != 0 && _end.QuadPart != 0) {
microSecond = (_end.QuadPart - _start.QuadPart) * (1000000.0 / _freq.QuadPart);
}
#else
microSecond = (_end.tv_sec * 1000000.0 + _end.tv_usec) - (_start.tv_sec * 1000000.0 + _start.tv_usec);
#endif
return microSecond;
}
double PerformanceTimer::getElapsedMilliseconds() {
return getElapsedMicroseconds() / 1000.0;
}
double PerformanceTimer::getElapsedSeconds() {
return getElapsedMicroseconds() / 1000000.0;
}
}
| mit |
victor-timoshin/WCFService_Customers | ave.DTO.Customers/ResponseServiceObject.cs | 192 | using System.Runtime.Serialization;
namespace ave.DTO.Customers
{
[DataContract]
public class ResponseServiceObject
{
[DataMember]
public ResponseService response { get; set; }
}
} | mit |
pelleanka/Opus | webroot/config.php | 1531 | <?php
/**
* Config-file for Opus. Change settings here to affect installation.
*
*/
/**
* Set the error reporting.
*
*/
error_reporting(-1); // Report all type of errors
ini_set('display_errors', 1); // Display all errors
ini_set('output_buffering', 0); // Do not buffer outputs, write directly
/**
* Define Opus paths.
*
*/
define('OPUS_INSTALL_PATH', __DIR__ . '/..');
define('OPUS_THEME_PATH', OPUS_INSTALL_PATH . '/theme/render.php');
/**
* Include bootstrapping functions.
*
*/
include(OPUS_INSTALL_PATH . '/src/bootstrap.php');
/**
* Start the session.
*
*/
session_name(preg_replace('/[^a-z\d]/i', '', __DIR__));
session_start();
/**
* Create the Opus variable.
*
*/
$opus = array();
/**
* Site wide settings.
*
*/
$opus['lang'] = 'sv';
$opus['title_append'] = ' | Opus en webbtemplate';
/**
* Theme related settings.
*
*/
$opus['stylesheets'] = array('css/style.css');
$opus['favicon'] = 'favicon.ico';
/**
* Settings for JavaScript.
*
*/
$opus['modernizr'] = 'js/modernizr.js';
/**
* Settings for JavaScript.
*
*/
$opus['jquery'] = '//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';
//$opus['jquery'] = null; // To disable jQuery
/**
* Settings for JavaScript.
*
*/
$opus['javascript_include'] = array();
//$opus['javascript_include'] = array('js/main.js'); // To add extra javascript files
/**
* Google analytics.
*
*/
$opus['google_analytics'] = null; //'UA-22093351-1'; // Set to null to disable google analytics | mit |
pavel-pimenov/sandbox | mediainfo/MediaInfoLib/Source/MediaInfo/Audio/File_Pcm_M2ts.cpp | 6573 | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_PCMM2TS_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Pcm_M2ts.h"
#if MEDIAINFO_DEMUX
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#endif //MEDIAINFO_DEMUX
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Infos
//***************************************************************************
//---------------------------------------------------------------------------
static int8u Pcm_M2TS_channel_assignment[16]=
{
0,
1,
0,
2,
3,
3,
4,
4,
5,
6,
7,
8,
0,
0,
0,
0,
};
//---------------------------------------------------------------------------
static int32u Pcm_M2TS_sampling_frequency[16]=
{
0,
48000,
0,
0,
96000,
192000,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
//---------------------------------------------------------------------------
static int8u Pcm_M2TS_bits_per_sample[4]=
{
0,
16,
20,
24,
};
//---------------------------------------------------------------------------
extern const char* Pcm_VOB_ChannelsPositions(int8u channel_assignment);
extern const char* Pcm_VOB_ChannelsPositions2(int8u channel_assignment);
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
//---------------------------------------------------------------------------
File_Pcm_M2ts::File_Pcm_M2ts()
{
//Configuration
ParserName="PCM M2TS";
IsRawStream=true;
PTS_DTS_Needed=true;
}
//***************************************************************************
// Streams management
//***************************************************************************
//---------------------------------------------------------------------------
void File_Pcm_M2ts::Streams_Fill()
{
Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, 0, Audio_Format, "PCM");
Fill(Stream_Audio, 0, Audio_Codec, "PCM");
Fill(Stream_Audio, 0, Audio_Codec_Family, "PCM");
Fill(Stream_Audio, 0, Audio_MuxingMode, "Blu-ray");
Fill(Stream_Audio, 0, Audio_BitRate_Mode, "CBR");
int8u Channels=Pcm_M2TS_channel_assignment[channel_assignment];
if (Channels)
{
if (Pcm_M2TS_sampling_frequency[sampling_frequency])
Fill(Stream_Audio, 0, Audio_SamplingRate, Pcm_M2TS_sampling_frequency[sampling_frequency]);
if (Pcm_M2TS_bits_per_sample[bits_per_sample])
Fill(Stream_Audio, 0, Audio_BitDepth, Pcm_M2TS_bits_per_sample[bits_per_sample]);
Fill(Stream_Audio, 0, Audio_Channel_s_, Channels);
Fill(Stream_Audio, 0, Audio_ChannelPositions, Pcm_VOB_ChannelsPositions(channel_assignment));
Fill(Stream_Audio, 0, Audio_ChannelPositions_String2, Pcm_VOB_ChannelsPositions2(channel_assignment));
if (Pcm_M2TS_sampling_frequency[sampling_frequency] && Pcm_M2TS_bits_per_sample[bits_per_sample])
{
if (Channels%2)
Fill(Stream_Audio, 0, Audio_BitRate_Encoded, Pcm_M2TS_sampling_frequency[sampling_frequency]*(Channels+1)*Pcm_M2TS_bits_per_sample[bits_per_sample]); //Always by pair
Fill(Stream_Audio, 0, Audio_BitRate, Pcm_M2TS_sampling_frequency[sampling_frequency]*Channels*Pcm_M2TS_bits_per_sample[bits_per_sample]);
}
}
Fill(Stream_Audio, 0, Audio_Format_Settings, "Big");
Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, "Big");
Fill(Stream_Audio, 0, Audio_Codec_Settings, "Big");
Fill(Stream_Audio, 0, Audio_Codec_Settings_Endianness, "Big");
Fill(Stream_Audio, 0, Audio_Format_Settings, "Signed");
Fill(Stream_Audio, 0, Audio_Format_Settings_Sign, "Signed");
Fill(Stream_Audio, 0, Audio_Codec_Settings, "Signed");
Fill(Stream_Audio, 0, Audio_Codec_Settings_Sign, "Signed");
}
//***************************************************************************
// Buffer - Global
//***************************************************************************
//---------------------------------------------------------------------------
void File_Pcm_M2ts::Read_Buffer_Continue()
{
if (Buffer_Size==0)
return;
//Parsing
int16u audio_data_payload_size;
Get_B2 ( audio_data_payload_size, "audio_data_payload_size");
BS_Begin();
Get_S1 (4, channel_assignment, "channel_assignment"); Param_Info2(Pcm_M2TS_channel_assignment[channel_assignment], " channel(s)");
Get_S1 (4, sampling_frequency, "sampling_frequency"); Param_Info2(Pcm_M2TS_sampling_frequency[sampling_frequency], " Hz");
Get_S1 (2, bits_per_sample, "bits_per_sample"); Param_Info2(Pcm_M2TS_bits_per_sample[bits_per_sample], " bits");
Skip_SB( "start_flag");
Skip_S1(5, "reserved");
BS_End();
Skip_XX(audio_data_payload_size, "audio_data_payload");
FILLING_BEGIN_PRECISE();
if (!Status[IsAccepted])
{
Accept();
Finish();
}
FILLING_END();
}
//***************************************************************************
// C++
//***************************************************************************
} //NameSpace
#endif //MEDIAINFO_PCMM2TS_YES
| mit |
victor-prado/broker-manager | broker-manager/Main.py | 1905 | import tkinter as tk
import pandas as pd
#from Data import Data
from NewClient import NewClient
from NewCorporation import NewCorporation
from SearchClient import SearchClient
from SearchDate import SearchDate
from SearchCorporation import SearchCorporation
from Dates import Reminder
def addClient():
"Execute class NewClient"
top = tk.Tk()
new_client = NewClient(master=top)
new_client.addButtons()
def addCorporation():
"Execute class NewCorporation"
top = tk.Tk()
new_corporation = NewCorporation(master=top)
new_corporation.addButtons()
def searchClient():
"Execute class SearchClient"
top = tk.Tk()
client_search = SearchClient(master=top)
def searchDate():
"Execute class searchDate"
top = tk.Tk()
date_search = SearchDate(master=top)
def editCorporation():
"Execute class EditCorporation"
top = tk.Tk()
corp = SearchCorporation(master=top)
#data = Data()
root = tk.Tk()
menubar = tk.Menu(root)
frame1 = tk.Frame(root)
frame1.grid()
for i in range(5):
tk.Label(frame1, text=' ').grid()
frame2 = tk.LabelFrame(root, text="Vencimentos")
frame2.grid()
reminder = Reminder(frame2)
addmenu = tk.Menu(menubar, tearoff=0)
addmenu.add_command(label="Novo Cliente", command=addClient)
addmenu.add_command(label="Nova Corporação", command=addCorporation)
menubar.add_cascade(label="Adicionar", menu=addmenu)
searchmenu = tk.Menu(menubar, tearoff=0)
searchmenu.add_command(label="Buscar Cliente", command=searchClient)
searchmenu.add_command(label="Buscar Datas", command=searchDate)
menubar.add_cascade(label="Consultar", menu=searchmenu)
editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="Editar Corporação", command=editCorporation)
menubar.add_cascade(label="Editar", menu=editmenu)
root.config(menu=menubar)
root.mainloop()
#data.db.close()
| mit |
mauretto78/in-memory-list | tests/Command/StatisticsCommandTest.php | 3257 | <?php
use InMemoryList\Command\StatisticsCommand;
use InMemoryList\Tests\BaseTestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
class StatisticsCommandTest extends BaseTestCase
{
/**
* @var Application
*/
private $app;
public function setUp()
{
parent::setUp(); // TODO: Change the autogenerated stub
$this->app = new Application();
$this->app->add(new StatisticsCommand());
}
/**
* @test
*/
public function it_displays_correctly_apcu_statistics()
{
$this->app->add(new StatisticsCommand('apcu'));
$command = $this->app->find('iml:cache:statistics');
$commandTester = new CommandTester($command);
$commandTester->execute([
'command' => $command->getName(),
]);
$output = $commandTester->getDisplay();
$this->assertContains('num_slots', $output);
$this->assertContains('ttl', $output);
$this->assertContains('num_hits', $output);
$this->assertContains('num_misses', $output);
$this->assertContains('num_inserts', $output);
$this->assertContains('num_entries', $output);
$this->assertContains('expunges', $output);
$this->assertContains('start_time', $output);
$this->assertContains('start_time', $output);
$this->assertContains('mem_size', $output);
$this->assertContains('memory_type', $output);
$this->assertContains('deleted_list', $output);
$this->assertContains('slot_distribution', $output);
}
/**
* @test
*/
public function it_displays_correctly_memcached_statistics()
{
$this->app->add(new StatisticsCommand('memcached', $this->memcached_parameters));
$command = $this->app->find('iml:cache:statistics');
$commandTester = new CommandTester($command);
$commandTester->execute([
'command' => $command->getName(),
]);
$output = $commandTester->getDisplay();
// if $this->memcached_parameters is a monodimensional array convert to multidimensional
if (!isset($this->memcached_parameters[0])) {
$this->memcached_parameters = [$this->memcached_parameters];
}
$this->assertContains($this->memcached_parameters[0]['host'], $output);
$this->assertContains($this->memcached_parameters[0]['port'], $output);
}
/**
* @test
*/
public function it_displays_correctly_redis_statistics()
{
$this->app->add(new StatisticsCommand('redis', $this->redis_parameters));
$command = $this->app->find('iml:cache:statistics');
$commandTester = new CommandTester($command);
$commandTester->execute([
'command' => $command->getName(),
]);
$output = $commandTester->getDisplay();
$this->assertContains('Clients', $output);
$this->assertContains('CPU', $output);
$this->assertContains('Memory', $output);
$this->assertContains('Persistence', $output);
$this->assertContains('Replication', $output);
$this->assertContains('Server', $output);
$this->assertContains('Stats', $output);
}
}
| mit |
wipu/iwant | essential/iwant-core/src/main/java/org/fluentjava/iwant/core/ScriptGeneratedContent.java | 2779 | package org.fluentjava.iwant.core;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Copy;
public class ScriptGeneratedContent implements Content {
private final Path script;
private final SortedSet<Path> ingredients = new TreeSet<Path>();
private ScriptGeneratedContent(Path script) {
this.script = script;
ingredients.add(script);
}
public static ScriptGeneratedContent of(Path script) {
return new ScriptGeneratedContent(script);
}
@Override
public SortedSet<Path> ingredients() {
return ingredients;
}
@Override
public void refresh(RefreshEnvironment refresh) throws Exception {
File tmpDir = refresh.freshTemporaryDirectory();
File tmpScript = new File(tmpDir.getCanonicalPath() + "/script");
Project project = new Project();
Copy copy = new Copy();
copy.setFile(new File(script.asAbsolutePath(refresh.locations())));
copy.setTofile(tmpScript);
PrintStream syserr = System.err;
try {
ByteArrayOutputStream err = new ByteArrayOutputStream();
// Please shut up, Copy
System.setErr(new PrintStream(err));
copy.execute();
} finally {
System.setErr(syserr);
}
Chmod chmod = new Chmod();
chmod.setProject(project);
chmod.setFile(tmpScript);
chmod.setPerm("u+x");
chmod.execute();
String[] cmd = { tmpScript.getAbsolutePath(),
refresh.destination().getAbsolutePath() };
Process process = new ProcessBuilder(cmd).directory(tmpDir)
.redirectErrorStream(true).start();
// err is redirected to out so we need to stream only out, and we stream
// it to err.
// TODO reuse code with PrintPrefixes.multiLineErr:
InputStream out = process.getInputStream();
boolean readingOut = true;
boolean lineStart = true;
while (readingOut) {
if (readingOut) {
int c = out.read();
if (c < 0) {
readingOut = false;
} else {
if (lineStart) {
System.err.print(PrintPrefixes.fromSystemProperty()
.errPrefix());
lineStart = false;
}
System.err.print((char) c);
}
if ('\n' == c) {
lineStart = true;
}
}
}
int result = process.waitFor();
if (result > 0) {
throw new IllegalStateException(
"Script exited with non-zero status " + result);
}
}
@Override
public String definitionDescription() {
StringBuilder b = new StringBuilder();
b.append(getClass().getSimpleName());
b.append(" {\n");
b.append(" script:").append(script).append("\n");
b.append("}\n");
return b.toString();
}
@Override
public String toString() {
return definitionDescription();
}
}
| mit |
occiware/OCCInterface | src/components/buttons/EditButton.js | 2635 | import React from 'react';
import { connect } from 'react-redux';
import {callAPI} from '../../utils.js';
import * as actions from '../../actions/actionIndex.js';
class EditButton extends React.Component{
editButton = () => {
//we delete the error message
this.props.setErrorMessage('', '');
//we delete the ok message
this.props.dispatch(actions.setOkMessage(''));
var relativeUrl = this.props.currentPath;
//we make a call in order to get the data without the html formating
//window.alert("edit !!: "+relativeUrl);
console.log("edit button: relativeUrl: ",relativeUrl);
callAPI(
'GET',
relativeUrl,
(data) => {
this.props.dispatch(actions.setCurrentQueryPath(relativeUrl));
this.props.dispatch(actions.setEditableCode());
this.props.dispatch(actions.setCurrentJson(data));
},
(xhr) => {
this.props.setErrorMessage('Impossible to edit this resource',xhr.status+' '+xhr.responseText);
}
);
}
postButton = () => {
this.editData('POST');
}
putButton = () => {
this.editData('PUT');
}
editData = (operationType) => {
var relativeUrl = this.props.currentPath;
//we need to send a string
var json = (typeof this.props.currentJson === 'string' || this.props.currentJson instanceof String) ? this.props.currentJson : JSON.stringify(this.props.currentJson);
callAPI(
operationType,
relativeUrl,
(data) => {
this.props.dispatch(actions.setCurrentQueryPath(relativeUrl));
this.props.dispatch(actions.setReadableCode());
this.props.dispatch(actions.setCurrentJson(data));
},
(xhr) => {
this.props.dispatch(actions.setErrorMessage(''+xhr.responseText));
},
{'Content-Type': 'application/json'},
json
);
}
render() {
if(this.props.codeRights === 'write'){
var itemsPostPut = <div>
<button className="ui yellow button playgroundButton" id="postButton" onClick={this.postButton}>POST</button>
<button className="ui orange button playgroundButton" id="putButton" onClick={this.putButton}>PUT</button>
</div>;
}
else{
var itemEdit = <button className="ui orange button playgroundButton" onClick={this.editButton}>EDIT</button>;
}
return (
<div>
{itemEdit}
{itemsPostPut}
</div>
);
}
}
const mapStateToProps = (state) => ({
currentJson: state.currentJson,
currentPath: state.currentPath,
codeRights: state.codeRights
})
export default EditButton = connect(mapStateToProps)(EditButton);
| mit |
christianlimanto95/ericwee | application/controllers/Home.php | 644 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
//include general controller supaya bisa extends General_controller
require_once("application/core/General_controller.php");
class Home extends General_controller {
public function __construct() {
parent::__construct();
$this->load->model("Home_model");
}
public function index()
{
parent::set_url_referrer("home");
$data = array(
"title" => "Ericweephoto",
"opening_words" => ""
);
$data["front_works"] = $this->Home_model->get_front_works();
$data["front_home"] = $this->Home_model->get_home_image()[0];
parent::view("home", $data);
}
}
| mit |
abdurrachman-habibi/gulp-lazy-minify | index.js | 2081 | var fs = require('fs');
var path = require('path');
var through = require('through2');
var gutil = require('gulp-util');
var gulpFile = require('gulp-file');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var File = gutil.File;
var PluginError = gutil.PluginError;
var fn = function (fileType) {
if (fileType === 'js') {
return uglify();
}
if (fileType === 'css') {
return minifyCss();
}
return true;
};
var lazyMinify = function() {
var stream = through.obj(function (file, enc, callback) {
var subs = file.path.toLowerCase().split('.');
var isMinified = subs.length > 2 && subs[subs.length - 2] === 'min';
if (isMinified) {
//console.log('source-minified: ' + file.path);
callback(null, file);
}
else {
var fileType = subs[subs.length - 1];
var minPath = subs[0];
for (var i = 0; i < subs.length - 2; i++) {
minPath += '.' + subs[i];
}
minPath += '.min.' + fileType;
var basename = path.basename(file.path);
var filename = basename.substring(0, basename.lastIndexOf('.')) + '.min.' + fileType;
fs.readFile(minPath, function (err, data) {
if (err == null) {
//console.log('pre-minified: ' + minPath);
var minFile = new File({
path: filename,
contents: data
});
callback(null, minFile);
} else {
//console.log('to-minify: ' + file.path);
gulpFile(filename, file.contents, { src: true })
.pipe(fn(fileType))
.pipe(through.obj(function (minFile, enc, cb) {
cb();
callback(null, minFile);
}));
}
});
}
});
return stream;
};
module.exports = lazyMinify; | mit |
arider/riderml | riderml/tests/util/test_preprocessing.py | 6108 | import numpy
import unittest
from unittest import TestCase
from ...util.preprocessing import (
as_matrix,
as_row,
sparse_filtering_normalizer,
bin_data,
sparse_encoding,
sparse_implicit_encoding,
row_indicators)
class SparseFilteringNormNormalizerTest(TestCase):
def test_list_normalize(self):
data = [1, 2, 3]
normalizer = sparse_filtering_normalizer(data)
normalized = normalizer.normalize(data)
self.assertAlmostEqual(0.26726124, normalized[0])
self.assertAlmostEqual(0.53452248, normalized[1])
self.assertAlmostEqual(0.80178373, normalized[2])
denormalized = normalizer.denormalize(normalized)
self.assertAlmostEqual(1, denormalized[0])
self.assertAlmostEqual(2, denormalized[1])
self.assertAlmostEqual(3, denormalized[2])
def test_matrix(self):
data = numpy.zeros([3, 2])
data[:, 0] = [1, 2, 3]
data[:, 1] = [10, 20, 30]
normalizer = sparse_filtering_normalizer(data)
normalized = normalizer.normalize(data)
denormalized = normalizer.denormalize(normalized)
for row in normalized:
for el in row:
self.assertAlmostEqual(0.70710678, el, 2)
for ri, row in enumerate(denormalized):
for ci, el in enumerate(row):
self.assertAlmostEqual(el, data[ri, ci])
class AsMatrixTest(TestCase):
def test_1d(self):
data = [1, 2, 3]
copy = as_matrix(data)
self.assertEqual(copy.shape[0], 3)
self.assertEqual(copy.shape[1], 1)
def test_2d(self):
data = [[1, 2, 3], [4, 5, 6]]
copy = as_matrix(data)
self.assertEqual(copy.shape[0], 2)
self.assertEqual(copy.shape[1], 3)
def test_is_array(self):
data = numpy.array([[1, 2, 3], [4, 5, 6]])
copy = as_matrix(data)
self.assertEqual(copy.shape[0], 2)
self.assertEqual(copy.shape[1], 3)
class AsRowTest(TestCase):
def test_1d(self):
data = [1, 2, 3]
copy = as_row(data)
self.assertEqual(copy.shape[0], 1)
self.assertEqual(copy.shape[1], 3)
def test_scalar(self):
data = 2
copy = as_row(data)
self.assertEqual(copy.shape[0], 1)
self.assertEqual(copy.shape[1], 1)
def test_2d(self):
data = [[1, 2, 3], [4, 5, 6]]
try:
as_row(data)
self.assertTrue(False)
except:
self.assertTrue(True)
class BinDataTest(TestCase):
def test_upper_edge(self):
x = range(10)
bins = bin_data(x, 5)
self.assertItemsEqual(bins, [2, 2, 2, 2, 2])
def test_no_binning(self):
x = range(10)
bins = bin_data(x, 10)
self.assertItemsEqual(bins, [1] * 10)
def test_uniform_input(self):
x = [10] * 10
bins = bin_data(x, 5)
self.assertEqual(bins[0], 10)
self.assertEqual(bins[1:].sum(), 0)
class RowIndicatorsTest(TestCase):
def test(self):
solution = numpy.array([[1., 0., 0.],
[1., 0., 0.],
[0., 1., 0.],
[0., 1., 0.],
[0., 0., 1.],
[0., 0., 1.]])
indicators = numpy.array(row_indicators(3, 2).todense())
for i in range(len(indicators)):
self.assertItemsEqual(solution[i], indicators[i])
def test_again(self):
solution = numpy.array([[1, 0],
[1, 0],
[1, 0],
[0, 1],
[0, 1],
[0, 1]])
out = numpy.array(row_indicators(2, 3).todense())
for i in range(len(out)):
self.assertItemsEqual(solution[i], out[i])
class SparseEncodingIndicatorsTest(TestCase):
def test(self):
data = numpy.array([[2, 4],
[4, 6],
[6, 8]])
solution = numpy.array([[1., 0.],
[0., 1.],
[1., 0.],
[0., 1.],
[1., 0.],
[0., 1.]])
indicators = numpy.array(sparse_encoding(data, 2).todense())
for i in range(len(indicators)):
self.assertItemsEqual(solution[i], indicators[i])
def test_not_binary(self):
data = numpy.array([[1, 2, 3],
[4, 5, 6]])
solution = numpy.array([[1., 0., 0.],
[0., 2., 0.],
[0., 0., 3.],
[4., 0., 0.],
[0., 5., 0.],
[0., 0., 6.]])
out = numpy.array(sparse_encoding(data, False).todense())
for i in range(len(out)):
self.assertItemsEqual(solution[i], out[i])
class SparseImplicitEncodingTest(TestCase):
def test_self_interactions_binary(self):
data = numpy.array([[1, 1],
[1, 0],
[1, 1]])
solution = numpy.array([[.5, .5],
[.5, .5],
[1., 0.],
[1., 0.],
[.5, .5],
[.5, .5]])
out = numpy.array(sparse_implicit_encoding(data).todense())
for i in range(len(out)):
self.assertItemsEqual(solution[i], out[i])
def test_self_interactions_not_binary(self):
data = numpy.array([[2, 4],
[4, 0],
[6, 8]])
out = numpy.array(sparse_implicit_encoding(data, False).todense())
self.assertAlmostEqual(out[0, 0], .333, 2)
self.assertAlmostEqual(out[0, 1], .666, 2)
self.assertAlmostEqual(out[4, 0], .428, 2)
if __name__ == '__main__':
unittest.main()
| mit |
looking-promising/privfiles | client/test/spec/controllers/about.js | 552 | 'use strict';
describe('Controller: AboutCtrl', function () {
// load the controller's module
beforeEach(module('privfilesApp'));
var AboutCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AboutCtrl = $controller('AboutCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
console.log(JSON.stringify(scope));
expect(scope.awesomeThings.length).toBe(3);
});
});
| mit |
1ed/gitlab-cookbook | recipes/database.rb | 1095 | #
# Cookbook Name:: gitlab
# Recipe:: database
#
# Copyright (C) 2013 Gábor Egyed
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
include_recipe "mysql::client"
include_recipe "mysql::server"
include_recipe "mysql::ruby"
# include the secure password from openssl recipe
::Chef::Recipe.send(:include, Opscode::OpenSSL::Password)
# generate database password
node.set_unless[:gitlab][:database_config][:password] = secure_password
ruby_block "save node data" do
block do
node.save
end
not_if { Chef::Config[:solo] }
end
connection = {
:host => "localhost",
:username => "root",
:password => node[:mysql][:server_root_password]
}
mysql_database node[:gitlab][:database_config][:database] do
connection connection
action :create
end
mysql_database_user node[:gitlab][:database_config][:username] do
connection connection
password node[:gitlab][:database_config][:password]
database_name node[:gitlab][:database_config][:database]
host "localhost"
action [:create, :grant]
end
| mit |
strava/go.serversets | watch_test.go | 2224 | package serversets
import (
"sort"
"testing"
)
func TestWatchSortEndpoints(t *testing.T) {
set := New(Test, "gotest", []string{TestServer})
watch, err := set.Watch()
if err != nil {
t.Fatal(err)
}
defer watch.Close()
ep1, err := set.RegisterEndpoint("localhost", 1002, nil)
if err != nil {
t.Fatal(err)
}
defer ep1.Close()
<-watch.Event()
ep2, err := set.RegisterEndpoint("localhost", 1001, nil)
if err != nil {
t.Fatal(err)
}
defer ep2.Close()
<-watch.Event()
ep3, err := set.RegisterEndpoint("localhost", 1003, nil)
if err != nil {
t.Fatal(err)
}
defer ep3.Close()
<-watch.Event()
endpoints := watch.Endpoints()
if len(endpoints) != 3 {
t.Errorf("should have 3 endpoint, got %v", endpoints)
}
if !sort.StringsAreSorted(endpoints) {
t.Errorf("endpoint list should be sorted, got %v", endpoints)
}
}
func TestWatchUpdateEndpoints(t *testing.T) {
set := New(Test, "gotest", []string{TestServer})
watch, err := set.Watch()
if err != nil {
t.Fatal(err)
}
defer watch.Close()
ep1, err := set.RegisterEndpoint("localhost", 1002, nil)
if err != nil {
t.Fatal(err)
}
defer ep1.Close()
<-watch.Event()
conn, _, err := set.connectToZookeeper()
if err != nil {
t.Fatal(err)
}
defer conn.Close()
eps, err := watch.updateEndpoints(conn, []string{MemberPrefix + "random"})
if err != nil {
t.Fatalf("should not have error, got %v", err)
}
if len(eps) != 0 {
t.Errorf("should not have any endpoints, got %v", eps)
}
}
func TestWatchIsClosed(t *testing.T) {
set := New(Test, "gotest", []string{TestServer})
watch, err := set.Watch()
if err != nil {
t.Fatal(err)
}
watch.Close()
if watch.IsClosed() == false {
t.Error("should say it's closed right after we close it")
}
}
func TestWatchMultipleClose(t *testing.T) {
set := New(Test, "gotest", []string{TestServer})
watch, err := set.Watch()
if err != nil {
t.Fatal(err)
}
watch.Close()
watch.Close()
watch.Close()
}
func TestWatchTriggerEvent(t *testing.T) {
set := New(Test, "gotest", []string{TestServer})
watch, err := set.Watch()
if err != nil {
t.Fatal(err)
}
defer watch.Close()
watch.triggerEvent()
watch.triggerEvent()
watch.triggerEvent()
watch.triggerEvent()
}
| mit |
Azure/azure-sdk-for-go | services/containerinstance/mgmt/2021-09-01/containerinstance/models.go | 67303 | package containerinstance
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"encoding/json"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/date"
"github.com/Azure/go-autorest/autorest/to"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// The package's fully qualified name.
const fqdn = "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-09-01/containerinstance"
// AzureFileVolume the properties of the Azure File volume. Azure File shares are mounted as volumes.
type AzureFileVolume struct {
// ShareName - The name of the Azure File share to be mounted as a volume.
ShareName *string `json:"shareName,omitempty"`
// ReadOnly - The flag indicating whether the Azure File shared mounted as a volume is read-only.
ReadOnly *bool `json:"readOnly,omitempty"`
// StorageAccountName - The name of the storage account that contains the Azure File share.
StorageAccountName *string `json:"storageAccountName,omitempty"`
// StorageAccountKey - The storage account access key used to access the Azure File share.
StorageAccountKey *string `json:"storageAccountKey,omitempty"`
}
// CachedImages the cached image and OS type.
type CachedImages struct {
// OsType - The OS type of the cached image.
OsType *string `json:"osType,omitempty"`
// Image - The cached image name.
Image *string `json:"image,omitempty"`
}
// CachedImagesListResult the response containing cached images.
type CachedImagesListResult struct {
autorest.Response `json:"-"`
// Value - The list of cached images.
Value *[]CachedImages `json:"value,omitempty"`
// NextLink - The URI to fetch the next page of cached images.
NextLink *string `json:"nextLink,omitempty"`
}
// CachedImagesListResultIterator provides access to a complete listing of CachedImages values.
type CachedImagesListResultIterator struct {
i int
page CachedImagesListResultPage
}
// NextWithContext advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *CachedImagesListResultIterator) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CachedImagesListResultIterator.NextWithContext")
defer func() {
sc := -1
if iter.Response().Response.Response != nil {
sc = iter.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err = iter.page.NextWithContext(ctx)
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *CachedImagesListResultIterator) Next() error {
return iter.NextWithContext(context.Background())
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter CachedImagesListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter CachedImagesListResultIterator) Response() CachedImagesListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter CachedImagesListResultIterator) Value() CachedImages {
if !iter.page.NotDone() {
return CachedImages{}
}
return iter.page.Values()[iter.i]
}
// Creates a new instance of the CachedImagesListResultIterator type.
func NewCachedImagesListResultIterator(page CachedImagesListResultPage) CachedImagesListResultIterator {
return CachedImagesListResultIterator{page: page}
}
// IsEmpty returns true if the ListResult contains no values.
func (cilr CachedImagesListResult) IsEmpty() bool {
return cilr.Value == nil || len(*cilr.Value) == 0
}
// hasNextLink returns true if the NextLink is not empty.
func (cilr CachedImagesListResult) hasNextLink() bool {
return cilr.NextLink != nil && len(*cilr.NextLink) != 0
}
// cachedImagesListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (cilr CachedImagesListResult) cachedImagesListResultPreparer(ctx context.Context) (*http.Request, error) {
if !cilr.hasNextLink() {
return nil, nil
}
return autorest.Prepare((&http.Request{}).WithContext(ctx),
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(cilr.NextLink)))
}
// CachedImagesListResultPage contains a page of CachedImages values.
type CachedImagesListResultPage struct {
fn func(context.Context, CachedImagesListResult) (CachedImagesListResult, error)
cilr CachedImagesListResult
}
// NextWithContext advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *CachedImagesListResultPage) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CachedImagesListResultPage.NextWithContext")
defer func() {
sc := -1
if page.Response().Response.Response != nil {
sc = page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
for {
next, err := page.fn(ctx, page.cilr)
if err != nil {
return err
}
page.cilr = next
if !next.hasNextLink() || !next.IsEmpty() {
break
}
}
return nil
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *CachedImagesListResultPage) Next() error {
return page.NextWithContext(context.Background())
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page CachedImagesListResultPage) NotDone() bool {
return !page.cilr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page CachedImagesListResultPage) Response() CachedImagesListResult {
return page.cilr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page CachedImagesListResultPage) Values() []CachedImages {
if page.cilr.IsEmpty() {
return nil
}
return *page.cilr.Value
}
// Creates a new instance of the CachedImagesListResultPage type.
func NewCachedImagesListResultPage(cur CachedImagesListResult, getNextPage func(context.Context, CachedImagesListResult) (CachedImagesListResult, error)) CachedImagesListResultPage {
return CachedImagesListResultPage{
fn: getNextPage,
cilr: cur,
}
}
// Capabilities the regional capabilities.
type Capabilities struct {
// ResourceType - READ-ONLY; The resource type that this capability describes.
ResourceType *string `json:"resourceType,omitempty"`
// OsType - READ-ONLY; The OS type that this capability describes.
OsType *string `json:"osType,omitempty"`
// Location - READ-ONLY; The resource location.
Location *string `json:"location,omitempty"`
// IPAddressType - READ-ONLY; The ip address type that this capability describes.
IPAddressType *string `json:"ipAddressType,omitempty"`
// Gpu - READ-ONLY; The GPU sku that this capability describes.
Gpu *string `json:"gpu,omitempty"`
// Capabilities - READ-ONLY; The supported capabilities.
Capabilities *CapabilitiesCapabilities `json:"capabilities,omitempty"`
}
// MarshalJSON is the custom marshaler for Capabilities.
func (c Capabilities) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// CapabilitiesCapabilities the supported capabilities.
type CapabilitiesCapabilities struct {
// MaxMemoryInGB - READ-ONLY; The maximum allowed memory request in GB.
MaxMemoryInGB *float64 `json:"maxMemoryInGB,omitempty"`
// MaxCPU - READ-ONLY; The maximum allowed CPU request in cores.
MaxCPU *float64 `json:"maxCpu,omitempty"`
// MaxGpuCount - READ-ONLY; The maximum allowed GPU count.
MaxGpuCount *float64 `json:"maxGpuCount,omitempty"`
}
// MarshalJSON is the custom marshaler for CapabilitiesCapabilities.
func (c CapabilitiesCapabilities) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// CapabilitiesListResult the response containing list of capabilities.
type CapabilitiesListResult struct {
autorest.Response `json:"-"`
// Value - The list of capabilities.
Value *[]Capabilities `json:"value,omitempty"`
// NextLink - The URI to fetch the next page of capabilities.
NextLink *string `json:"nextLink,omitempty"`
}
// CapabilitiesListResultIterator provides access to a complete listing of Capabilities values.
type CapabilitiesListResultIterator struct {
i int
page CapabilitiesListResultPage
}
// NextWithContext advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *CapabilitiesListResultIterator) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CapabilitiesListResultIterator.NextWithContext")
defer func() {
sc := -1
if iter.Response().Response.Response != nil {
sc = iter.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err = iter.page.NextWithContext(ctx)
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *CapabilitiesListResultIterator) Next() error {
return iter.NextWithContext(context.Background())
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter CapabilitiesListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter CapabilitiesListResultIterator) Response() CapabilitiesListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter CapabilitiesListResultIterator) Value() Capabilities {
if !iter.page.NotDone() {
return Capabilities{}
}
return iter.page.Values()[iter.i]
}
// Creates a new instance of the CapabilitiesListResultIterator type.
func NewCapabilitiesListResultIterator(page CapabilitiesListResultPage) CapabilitiesListResultIterator {
return CapabilitiesListResultIterator{page: page}
}
// IsEmpty returns true if the ListResult contains no values.
func (clr CapabilitiesListResult) IsEmpty() bool {
return clr.Value == nil || len(*clr.Value) == 0
}
// hasNextLink returns true if the NextLink is not empty.
func (clr CapabilitiesListResult) hasNextLink() bool {
return clr.NextLink != nil && len(*clr.NextLink) != 0
}
// capabilitiesListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (clr CapabilitiesListResult) capabilitiesListResultPreparer(ctx context.Context) (*http.Request, error) {
if !clr.hasNextLink() {
return nil, nil
}
return autorest.Prepare((&http.Request{}).WithContext(ctx),
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(clr.NextLink)))
}
// CapabilitiesListResultPage contains a page of Capabilities values.
type CapabilitiesListResultPage struct {
fn func(context.Context, CapabilitiesListResult) (CapabilitiesListResult, error)
clr CapabilitiesListResult
}
// NextWithContext advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *CapabilitiesListResultPage) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CapabilitiesListResultPage.NextWithContext")
defer func() {
sc := -1
if page.Response().Response.Response != nil {
sc = page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
for {
next, err := page.fn(ctx, page.clr)
if err != nil {
return err
}
page.clr = next
if !next.hasNextLink() || !next.IsEmpty() {
break
}
}
return nil
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *CapabilitiesListResultPage) Next() error {
return page.NextWithContext(context.Background())
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page CapabilitiesListResultPage) NotDone() bool {
return !page.clr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page CapabilitiesListResultPage) Response() CapabilitiesListResult {
return page.clr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page CapabilitiesListResultPage) Values() []Capabilities {
if page.clr.IsEmpty() {
return nil
}
return *page.clr.Value
}
// Creates a new instance of the CapabilitiesListResultPage type.
func NewCapabilitiesListResultPage(cur CapabilitiesListResult, getNextPage func(context.Context, CapabilitiesListResult) (CapabilitiesListResult, error)) CapabilitiesListResultPage {
return CapabilitiesListResultPage{
fn: getNextPage,
clr: cur,
}
}
// CloudError an error response from the Container Instance service.
type CloudError struct {
Error *CloudErrorBody `json:"error,omitempty"`
}
// CloudErrorBody an error response from the Container Instance service.
type CloudErrorBody struct {
// Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically.
Code *string `json:"code,omitempty"`
// Message - A message describing the error, intended to be suitable for display in a user interface.
Message *string `json:"message,omitempty"`
// Target - The target of the particular error. For example, the name of the property in error.
Target *string `json:"target,omitempty"`
// Details - A list of additional details about the error.
Details *[]CloudErrorBody `json:"details,omitempty"`
}
// Container a container instance.
type Container struct {
// Name - The user-provided name of the container instance.
Name *string `json:"name,omitempty"`
// ContainerProperties - The properties of the container instance.
*ContainerProperties `json:"properties,omitempty"`
}
// MarshalJSON is the custom marshaler for Container.
func (c Container) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if c.Name != nil {
objectMap["name"] = c.Name
}
if c.ContainerProperties != nil {
objectMap["properties"] = c.ContainerProperties
}
return json.Marshal(objectMap)
}
// UnmarshalJSON is the custom unmarshaler for Container struct.
func (c *Container) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
for k, v := range m {
switch k {
case "name":
if v != nil {
var name string
err = json.Unmarshal(*v, &name)
if err != nil {
return err
}
c.Name = &name
}
case "properties":
if v != nil {
var containerProperties ContainerProperties
err = json.Unmarshal(*v, &containerProperties)
if err != nil {
return err
}
c.ContainerProperties = &containerProperties
}
}
}
return nil
}
// ContainerAttachResponse the information for the output stream from container attach.
type ContainerAttachResponse struct {
autorest.Response `json:"-"`
// WebSocketURI - The uri for the output stream from the attach.
WebSocketURI *string `json:"webSocketUri,omitempty"`
// Password - The password to the output stream from the attach. Send as an Authorization header value when connecting to the websocketUri.
Password *string `json:"password,omitempty"`
}
// ContainerExec the container execution command, for liveness or readiness probe
type ContainerExec struct {
// Command - The commands to execute within the container.
Command *[]string `json:"command,omitempty"`
}
// ContainerExecRequest the container exec request.
type ContainerExecRequest struct {
// Command - The command to be executed.
Command *string `json:"command,omitempty"`
// TerminalSize - The size of the terminal.
TerminalSize *ContainerExecRequestTerminalSize `json:"terminalSize,omitempty"`
}
// ContainerExecRequestTerminalSize the size of the terminal.
type ContainerExecRequestTerminalSize struct {
// Rows - The row size of the terminal
Rows *int32 `json:"rows,omitempty"`
// Cols - The column size of the terminal
Cols *int32 `json:"cols,omitempty"`
}
// ContainerExecResponse the information for the container exec command.
type ContainerExecResponse struct {
autorest.Response `json:"-"`
// WebSocketURI - The uri for the exec websocket.
WebSocketURI *string `json:"webSocketUri,omitempty"`
// Password - The password to start the exec command.
Password *string `json:"password,omitempty"`
}
// ContainerGroup a container group.
type ContainerGroup struct {
autorest.Response `json:"-"`
// Identity - The identity of the container group, if configured.
Identity *ContainerGroupIdentity `json:"identity,omitempty"`
// ContainerGroupProperties - The container group properties
*ContainerGroupProperties `json:"properties,omitempty"`
// ID - READ-ONLY; The resource id.
ID *string `json:"id,omitempty"`
// Name - READ-ONLY; The resource name.
Name *string `json:"name,omitempty"`
// Type - READ-ONLY; The resource type.
Type *string `json:"type,omitempty"`
// Location - The resource location.
Location *string `json:"location,omitempty"`
// Tags - The resource tags.
Tags map[string]*string `json:"tags"`
// Zones - The zones for the container group.
Zones *[]string `json:"zones,omitempty"`
}
// MarshalJSON is the custom marshaler for ContainerGroup.
func (cg ContainerGroup) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if cg.Identity != nil {
objectMap["identity"] = cg.Identity
}
if cg.ContainerGroupProperties != nil {
objectMap["properties"] = cg.ContainerGroupProperties
}
if cg.Location != nil {
objectMap["location"] = cg.Location
}
if cg.Tags != nil {
objectMap["tags"] = cg.Tags
}
if cg.Zones != nil {
objectMap["zones"] = cg.Zones
}
return json.Marshal(objectMap)
}
// UnmarshalJSON is the custom unmarshaler for ContainerGroup struct.
func (cg *ContainerGroup) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
for k, v := range m {
switch k {
case "identity":
if v != nil {
var identity ContainerGroupIdentity
err = json.Unmarshal(*v, &identity)
if err != nil {
return err
}
cg.Identity = &identity
}
case "properties":
if v != nil {
var containerGroupProperties ContainerGroupProperties
err = json.Unmarshal(*v, &containerGroupProperties)
if err != nil {
return err
}
cg.ContainerGroupProperties = &containerGroupProperties
}
case "id":
if v != nil {
var ID string
err = json.Unmarshal(*v, &ID)
if err != nil {
return err
}
cg.ID = &ID
}
case "name":
if v != nil {
var name string
err = json.Unmarshal(*v, &name)
if err != nil {
return err
}
cg.Name = &name
}
case "type":
if v != nil {
var typeVar string
err = json.Unmarshal(*v, &typeVar)
if err != nil {
return err
}
cg.Type = &typeVar
}
case "location":
if v != nil {
var location string
err = json.Unmarshal(*v, &location)
if err != nil {
return err
}
cg.Location = &location
}
case "tags":
if v != nil {
var tags map[string]*string
err = json.Unmarshal(*v, &tags)
if err != nil {
return err
}
cg.Tags = tags
}
case "zones":
if v != nil {
var zones []string
err = json.Unmarshal(*v, &zones)
if err != nil {
return err
}
cg.Zones = &zones
}
}
}
return nil
}
// ContainerGroupDiagnostics container group diagnostic information.
type ContainerGroupDiagnostics struct {
// LogAnalytics - Container group log analytics information.
LogAnalytics *LogAnalytics `json:"logAnalytics,omitempty"`
}
// ContainerGroupIdentity identity for the container group.
type ContainerGroupIdentity struct {
// PrincipalID - READ-ONLY; The principal id of the container group identity. This property will only be provided for a system assigned identity.
PrincipalID *string `json:"principalId,omitempty"`
// TenantID - READ-ONLY; The tenant id associated with the container group. This property will only be provided for a system assigned identity.
TenantID *string `json:"tenantId,omitempty"`
// Type - The type of identity used for the container group. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the container group. Possible values include: 'ResourceIdentityTypeSystemAssigned', 'ResourceIdentityTypeUserAssigned', 'ResourceIdentityTypeSystemAssignedUserAssigned', 'ResourceIdentityTypeNone'
Type ResourceIdentityType `json:"type,omitempty"`
// UserAssignedIdentities - The list of user identities associated with the container group. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
UserAssignedIdentities map[string]*ContainerGroupIdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"`
}
// MarshalJSON is the custom marshaler for ContainerGroupIdentity.
func (cgiVar ContainerGroupIdentity) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if cgiVar.Type != "" {
objectMap["type"] = cgiVar.Type
}
if cgiVar.UserAssignedIdentities != nil {
objectMap["userAssignedIdentities"] = cgiVar.UserAssignedIdentities
}
return json.Marshal(objectMap)
}
// ContainerGroupIdentityUserAssignedIdentitiesValue ...
type ContainerGroupIdentityUserAssignedIdentitiesValue struct {
// PrincipalID - READ-ONLY; The principal id of user assigned identity.
PrincipalID *string `json:"principalId,omitempty"`
// ClientID - READ-ONLY; The client id of user assigned identity.
ClientID *string `json:"clientId,omitempty"`
}
// MarshalJSON is the custom marshaler for ContainerGroupIdentityUserAssignedIdentitiesValue.
func (cgiAiv ContainerGroupIdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// ContainerGroupListResult the container group list response that contains the container group properties.
type ContainerGroupListResult struct {
autorest.Response `json:"-"`
// Value - The list of container groups.
Value *[]ContainerGroup `json:"value,omitempty"`
// NextLink - The URI to fetch the next page of container groups.
NextLink *string `json:"nextLink,omitempty"`
}
// ContainerGroupListResultIterator provides access to a complete listing of ContainerGroup values.
type ContainerGroupListResultIterator struct {
i int
page ContainerGroupListResultPage
}
// NextWithContext advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *ContainerGroupListResultIterator) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupListResultIterator.NextWithContext")
defer func() {
sc := -1
if iter.Response().Response.Response != nil {
sc = iter.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err = iter.page.NextWithContext(ctx)
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *ContainerGroupListResultIterator) Next() error {
return iter.NextWithContext(context.Background())
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter ContainerGroupListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter ContainerGroupListResultIterator) Response() ContainerGroupListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter ContainerGroupListResultIterator) Value() ContainerGroup {
if !iter.page.NotDone() {
return ContainerGroup{}
}
return iter.page.Values()[iter.i]
}
// Creates a new instance of the ContainerGroupListResultIterator type.
func NewContainerGroupListResultIterator(page ContainerGroupListResultPage) ContainerGroupListResultIterator {
return ContainerGroupListResultIterator{page: page}
}
// IsEmpty returns true if the ListResult contains no values.
func (cglr ContainerGroupListResult) IsEmpty() bool {
return cglr.Value == nil || len(*cglr.Value) == 0
}
// hasNextLink returns true if the NextLink is not empty.
func (cglr ContainerGroupListResult) hasNextLink() bool {
return cglr.NextLink != nil && len(*cglr.NextLink) != 0
}
// containerGroupListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (cglr ContainerGroupListResult) containerGroupListResultPreparer(ctx context.Context) (*http.Request, error) {
if !cglr.hasNextLink() {
return nil, nil
}
return autorest.Prepare((&http.Request{}).WithContext(ctx),
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(cglr.NextLink)))
}
// ContainerGroupListResultPage contains a page of ContainerGroup values.
type ContainerGroupListResultPage struct {
fn func(context.Context, ContainerGroupListResult) (ContainerGroupListResult, error)
cglr ContainerGroupListResult
}
// NextWithContext advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *ContainerGroupListResultPage) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupListResultPage.NextWithContext")
defer func() {
sc := -1
if page.Response().Response.Response != nil {
sc = page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
for {
next, err := page.fn(ctx, page.cglr)
if err != nil {
return err
}
page.cglr = next
if !next.hasNextLink() || !next.IsEmpty() {
break
}
}
return nil
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *ContainerGroupListResultPage) Next() error {
return page.NextWithContext(context.Background())
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page ContainerGroupListResultPage) NotDone() bool {
return !page.cglr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page ContainerGroupListResultPage) Response() ContainerGroupListResult {
return page.cglr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page ContainerGroupListResultPage) Values() []ContainerGroup {
if page.cglr.IsEmpty() {
return nil
}
return *page.cglr.Value
}
// Creates a new instance of the ContainerGroupListResultPage type.
func NewContainerGroupListResultPage(cur ContainerGroupListResult, getNextPage func(context.Context, ContainerGroupListResult) (ContainerGroupListResult, error)) ContainerGroupListResultPage {
return ContainerGroupListResultPage{
fn: getNextPage,
cglr: cur,
}
}
// ContainerGroupProperties the container group properties
type ContainerGroupProperties struct {
// ProvisioningState - READ-ONLY; The provisioning state of the container group. This only appears in the response.
ProvisioningState *string `json:"provisioningState,omitempty"`
// Containers - The containers within the container group.
Containers *[]Container `json:"containers,omitempty"`
// ImageRegistryCredentials - The image registry credentials by which the container group is created from.
ImageRegistryCredentials *[]ImageRegistryCredential `json:"imageRegistryCredentials,omitempty"`
// RestartPolicy - Restart policy for all containers within the container group.
// - `Always` Always restart
// - `OnFailure` Restart on failure
// - `Never` Never restart
// . Possible values include: 'ContainerGroupRestartPolicyAlways', 'ContainerGroupRestartPolicyOnFailure', 'ContainerGroupRestartPolicyNever'
RestartPolicy ContainerGroupRestartPolicy `json:"restartPolicy,omitempty"`
// IPAddress - The IP address type of the container group.
IPAddress *IPAddress `json:"ipAddress,omitempty"`
// OsType - The operating system type required by the containers in the container group. Possible values include: 'OperatingSystemTypesWindows', 'OperatingSystemTypesLinux'
OsType OperatingSystemTypes `json:"osType,omitempty"`
// Volumes - The list of volumes that can be mounted by containers in this container group.
Volumes *[]Volume `json:"volumes,omitempty"`
// InstanceView - READ-ONLY; The instance view of the container group. Only valid in response.
InstanceView *ContainerGroupPropertiesInstanceView `json:"instanceView,omitempty"`
// Diagnostics - The diagnostic information for a container group.
Diagnostics *ContainerGroupDiagnostics `json:"diagnostics,omitempty"`
// SubnetIds - The subnet resource IDs for a container group.
SubnetIds *[]ContainerGroupSubnetID `json:"subnetIds,omitempty"`
// DNSConfig - The DNS config information for a container group.
DNSConfig *DNSConfiguration `json:"dnsConfig,omitempty"`
// Sku - The SKU for a container group. Possible values include: 'ContainerGroupSkuStandard', 'ContainerGroupSkuDedicated'
Sku ContainerGroupSku `json:"sku,omitempty"`
// EncryptionProperties - The encryption properties for a container group.
EncryptionProperties *EncryptionProperties `json:"encryptionProperties,omitempty"`
// InitContainers - The init containers for a container group.
InitContainers *[]InitContainerDefinition `json:"initContainers,omitempty"`
}
// MarshalJSON is the custom marshaler for ContainerGroupProperties.
func (cg ContainerGroupProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if cg.Containers != nil {
objectMap["containers"] = cg.Containers
}
if cg.ImageRegistryCredentials != nil {
objectMap["imageRegistryCredentials"] = cg.ImageRegistryCredentials
}
if cg.RestartPolicy != "" {
objectMap["restartPolicy"] = cg.RestartPolicy
}
if cg.IPAddress != nil {
objectMap["ipAddress"] = cg.IPAddress
}
if cg.OsType != "" {
objectMap["osType"] = cg.OsType
}
if cg.Volumes != nil {
objectMap["volumes"] = cg.Volumes
}
if cg.Diagnostics != nil {
objectMap["diagnostics"] = cg.Diagnostics
}
if cg.SubnetIds != nil {
objectMap["subnetIds"] = cg.SubnetIds
}
if cg.DNSConfig != nil {
objectMap["dnsConfig"] = cg.DNSConfig
}
if cg.Sku != "" {
objectMap["sku"] = cg.Sku
}
if cg.EncryptionProperties != nil {
objectMap["encryptionProperties"] = cg.EncryptionProperties
}
if cg.InitContainers != nil {
objectMap["initContainers"] = cg.InitContainers
}
return json.Marshal(objectMap)
}
// ContainerGroupPropertiesInstanceView the instance view of the container group. Only valid in response.
type ContainerGroupPropertiesInstanceView struct {
// Events - READ-ONLY; The events of this container group.
Events *[]Event `json:"events,omitempty"`
// State - READ-ONLY; The state of the container group. Only valid in response.
State *string `json:"state,omitempty"`
}
// MarshalJSON is the custom marshaler for ContainerGroupPropertiesInstanceView.
func (cgV ContainerGroupPropertiesInstanceView) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// ContainerGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a
// long-running operation.
type ContainerGroupsCreateOrUpdateFuture struct {
azure.FutureAPI
// Result returns the result of the asynchronous operation.
// If the operation has not completed it will return an error.
Result func(ContainerGroupsClient) (ContainerGroup, error)
}
// UnmarshalJSON is the custom unmarshaller for CreateFuture.
func (future *ContainerGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error {
var azFuture azure.Future
if err := json.Unmarshal(body, &azFuture); err != nil {
return err
}
future.FutureAPI = &azFuture
future.Result = future.result
return nil
}
// result is the default implementation for ContainerGroupsCreateOrUpdateFuture.Result.
func (future *ContainerGroupsCreateOrUpdateFuture) result(client ContainerGroupsClient) (cg ContainerGroup, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
cg.Response.Response = future.Response()
err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsCreateOrUpdateFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if cg.Response.Response, err = future.GetResult(sender); err == nil && cg.Response.Response.StatusCode != http.StatusNoContent {
cg, err = client.CreateOrUpdateResponder(cg.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsCreateOrUpdateFuture", "Result", cg.Response.Response, "Failure responding to request")
}
}
return
}
// ContainerGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running
// operation.
type ContainerGroupsDeleteFuture struct {
azure.FutureAPI
// Result returns the result of the asynchronous operation.
// If the operation has not completed it will return an error.
Result func(ContainerGroupsClient) (ContainerGroup, error)
}
// UnmarshalJSON is the custom unmarshaller for CreateFuture.
func (future *ContainerGroupsDeleteFuture) UnmarshalJSON(body []byte) error {
var azFuture azure.Future
if err := json.Unmarshal(body, &azFuture); err != nil {
return err
}
future.FutureAPI = &azFuture
future.Result = future.result
return nil
}
// result is the default implementation for ContainerGroupsDeleteFuture.Result.
func (future *ContainerGroupsDeleteFuture) result(client ContainerGroupsClient) (cg ContainerGroup, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsDeleteFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
cg.Response.Response = future.Response()
err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsDeleteFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if cg.Response.Response, err = future.GetResult(sender); err == nil && cg.Response.Response.StatusCode != http.StatusNoContent {
cg, err = client.DeleteResponder(cg.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsDeleteFuture", "Result", cg.Response.Response, "Failure responding to request")
}
}
return
}
// ContainerGroupsRestartFuture an abstraction for monitoring and retrieving the results of a long-running
// operation.
type ContainerGroupsRestartFuture struct {
azure.FutureAPI
// Result returns the result of the asynchronous operation.
// If the operation has not completed it will return an error.
Result func(ContainerGroupsClient) (autorest.Response, error)
}
// UnmarshalJSON is the custom unmarshaller for CreateFuture.
func (future *ContainerGroupsRestartFuture) UnmarshalJSON(body []byte) error {
var azFuture azure.Future
if err := json.Unmarshal(body, &azFuture); err != nil {
return err
}
future.FutureAPI = &azFuture
future.Result = future.result
return nil
}
// result is the default implementation for ContainerGroupsRestartFuture.Result.
func (future *ContainerGroupsRestartFuture) result(client ContainerGroupsClient) (ar autorest.Response, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsRestartFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
ar.Response = future.Response()
err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsRestartFuture")
return
}
ar.Response = future.Response()
return
}
// ContainerGroupsStartFuture an abstraction for monitoring and retrieving the results of a long-running
// operation.
type ContainerGroupsStartFuture struct {
azure.FutureAPI
// Result returns the result of the asynchronous operation.
// If the operation has not completed it will return an error.
Result func(ContainerGroupsClient) (autorest.Response, error)
}
// UnmarshalJSON is the custom unmarshaller for CreateFuture.
func (future *ContainerGroupsStartFuture) UnmarshalJSON(body []byte) error {
var azFuture azure.Future
if err := json.Unmarshal(body, &azFuture); err != nil {
return err
}
future.FutureAPI = &azFuture
future.Result = future.result
return nil
}
// result is the default implementation for ContainerGroupsStartFuture.Result.
func (future *ContainerGroupsStartFuture) result(client ContainerGroupsClient) (ar autorest.Response, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsStartFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
ar.Response = future.Response()
err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsStartFuture")
return
}
ar.Response = future.Response()
return
}
// ContainerGroupSubnetID container group subnet information.
type ContainerGroupSubnetID struct {
// ID - Resource ID of virtual network and subnet.
ID *string `json:"id,omitempty"`
// Name - Friendly name for the subnet.
Name *string `json:"name,omitempty"`
}
// ContainerHTTPGet the container Http Get settings, for liveness or readiness probe
type ContainerHTTPGet struct {
// Path - The path to probe.
Path *string `json:"path,omitempty"`
// Port - The port number to probe.
Port *int32 `json:"port,omitempty"`
// Scheme - The scheme. Possible values include: 'SchemeHTTP', 'SchemeHTTPS'
Scheme Scheme `json:"scheme,omitempty"`
// HTTPHeaders - The HTTP headers.
HTTPHeaders *[]HTTPHeader `json:"httpHeaders,omitempty"`
}
// ContainerPort the port exposed on the container instance.
type ContainerPort struct {
// Protocol - The protocol associated with the port. Possible values include: 'ContainerNetworkProtocolTCP', 'ContainerNetworkProtocolUDP'
Protocol ContainerNetworkProtocol `json:"protocol,omitempty"`
// Port - The port number exposed within the container group.
Port *int32 `json:"port,omitempty"`
}
// ContainerProbe the container probe, for liveness or readiness
type ContainerProbe struct {
// Exec - The execution command to probe
Exec *ContainerExec `json:"exec,omitempty"`
// HTTPGet - The Http Get settings to probe
HTTPGet *ContainerHTTPGet `json:"httpGet,omitempty"`
// InitialDelaySeconds - The initial delay seconds.
InitialDelaySeconds *int32 `json:"initialDelaySeconds,omitempty"`
// PeriodSeconds - The period seconds.
PeriodSeconds *int32 `json:"periodSeconds,omitempty"`
// FailureThreshold - The failure threshold.
FailureThreshold *int32 `json:"failureThreshold,omitempty"`
// SuccessThreshold - The success threshold.
SuccessThreshold *int32 `json:"successThreshold,omitempty"`
// TimeoutSeconds - The timeout seconds.
TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty"`
}
// ContainerProperties the container instance properties.
type ContainerProperties struct {
// Image - The name of the image used to create the container instance.
Image *string `json:"image,omitempty"`
// Command - The commands to execute within the container instance in exec form.
Command *[]string `json:"command,omitempty"`
// Ports - The exposed ports on the container instance.
Ports *[]ContainerPort `json:"ports,omitempty"`
// EnvironmentVariables - The environment variables to set in the container instance.
EnvironmentVariables *[]EnvironmentVariable `json:"environmentVariables,omitempty"`
// InstanceView - READ-ONLY; The instance view of the container instance. Only valid in response.
InstanceView *ContainerPropertiesInstanceView `json:"instanceView,omitempty"`
// Resources - The resource requirements of the container instance.
Resources *ResourceRequirements `json:"resources,omitempty"`
// VolumeMounts - The volume mounts available to the container instance.
VolumeMounts *[]VolumeMount `json:"volumeMounts,omitempty"`
// LivenessProbe - The liveness probe.
LivenessProbe *ContainerProbe `json:"livenessProbe,omitempty"`
// ReadinessProbe - The readiness probe.
ReadinessProbe *ContainerProbe `json:"readinessProbe,omitempty"`
}
// MarshalJSON is the custom marshaler for ContainerProperties.
func (cp ContainerProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if cp.Image != nil {
objectMap["image"] = cp.Image
}
if cp.Command != nil {
objectMap["command"] = cp.Command
}
if cp.Ports != nil {
objectMap["ports"] = cp.Ports
}
if cp.EnvironmentVariables != nil {
objectMap["environmentVariables"] = cp.EnvironmentVariables
}
if cp.Resources != nil {
objectMap["resources"] = cp.Resources
}
if cp.VolumeMounts != nil {
objectMap["volumeMounts"] = cp.VolumeMounts
}
if cp.LivenessProbe != nil {
objectMap["livenessProbe"] = cp.LivenessProbe
}
if cp.ReadinessProbe != nil {
objectMap["readinessProbe"] = cp.ReadinessProbe
}
return json.Marshal(objectMap)
}
// ContainerPropertiesInstanceView the instance view of the container instance. Only valid in response.
type ContainerPropertiesInstanceView struct {
// RestartCount - READ-ONLY; The number of times that the container instance has been restarted.
RestartCount *int32 `json:"restartCount,omitempty"`
// CurrentState - READ-ONLY; Current container instance state.
CurrentState *ContainerState `json:"currentState,omitempty"`
// PreviousState - READ-ONLY; Previous container instance state.
PreviousState *ContainerState `json:"previousState,omitempty"`
// Events - READ-ONLY; The events of the container instance.
Events *[]Event `json:"events,omitempty"`
}
// MarshalJSON is the custom marshaler for ContainerPropertiesInstanceView.
func (cpV ContainerPropertiesInstanceView) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// ContainerState the container instance state.
type ContainerState struct {
// State - READ-ONLY; The state of the container instance.
State *string `json:"state,omitempty"`
// StartTime - READ-ONLY; The date-time when the container instance state started.
StartTime *date.Time `json:"startTime,omitempty"`
// ExitCode - READ-ONLY; The container instance exit codes correspond to those from the `docker run` command.
ExitCode *int32 `json:"exitCode,omitempty"`
// FinishTime - READ-ONLY; The date-time when the container instance state finished.
FinishTime *date.Time `json:"finishTime,omitempty"`
// DetailStatus - READ-ONLY; The human-readable status of the container instance state.
DetailStatus *string `json:"detailStatus,omitempty"`
}
// MarshalJSON is the custom marshaler for ContainerState.
func (cs ContainerState) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// DNSConfiguration DNS configuration for the container group.
type DNSConfiguration struct {
// NameServers - The DNS servers for the container group.
NameServers *[]string `json:"nameServers,omitempty"`
// SearchDomains - The DNS search domains for hostname lookup in the container group.
SearchDomains *string `json:"searchDomains,omitempty"`
// Options - The DNS options for the container group.
Options *string `json:"options,omitempty"`
}
// EncryptionProperties the container group encryption properties.
type EncryptionProperties struct {
// VaultBaseURL - The keyvault base url.
VaultBaseURL *string `json:"vaultBaseUrl,omitempty"`
// KeyName - The encryption key name.
KeyName *string `json:"keyName,omitempty"`
// KeyVersion - The encryption key version.
KeyVersion *string `json:"keyVersion,omitempty"`
}
// EnvironmentVariable the environment variable to set within the container instance.
type EnvironmentVariable struct {
// Name - The name of the environment variable.
Name *string `json:"name,omitempty"`
// Value - The value of the environment variable.
Value *string `json:"value,omitempty"`
// SecureValue - The value of the secure environment variable.
SecureValue *string `json:"secureValue,omitempty"`
}
// Event a container group or container instance event.
type Event struct {
// Count - READ-ONLY; The count of the event.
Count *int32 `json:"count,omitempty"`
// FirstTimestamp - READ-ONLY; The date-time of the earliest logged event.
FirstTimestamp *date.Time `json:"firstTimestamp,omitempty"`
// LastTimestamp - READ-ONLY; The date-time of the latest logged event.
LastTimestamp *date.Time `json:"lastTimestamp,omitempty"`
// Name - READ-ONLY; The event name.
Name *string `json:"name,omitempty"`
// Message - READ-ONLY; The event message.
Message *string `json:"message,omitempty"`
// Type - READ-ONLY; The event type.
Type *string `json:"type,omitempty"`
}
// MarshalJSON is the custom marshaler for Event.
func (e Event) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// GitRepoVolume represents a volume that is populated with the contents of a git repository
type GitRepoVolume struct {
// Directory - Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.
Directory *string `json:"directory,omitempty"`
// Repository - Repository URL
Repository *string `json:"repository,omitempty"`
// Revision - Commit hash for the specified revision.
Revision *string `json:"revision,omitempty"`
}
// GpuResource the GPU resource.
type GpuResource struct {
// Count - The count of the GPU resource.
Count *int32 `json:"count,omitempty"`
// Sku - The SKU of the GPU resource. Possible values include: 'GpuSkuK80', 'GpuSkuP100', 'GpuSkuV100'
Sku GpuSku `json:"sku,omitempty"`
}
// HTTPHeader the HTTP header.
type HTTPHeader struct {
// Name - The header name.
Name *string `json:"name,omitempty"`
// Value - The header value.
Value *string `json:"value,omitempty"`
}
// ImageRegistryCredential image registry credential.
type ImageRegistryCredential struct {
// Server - The Docker image registry server without a protocol such as "http" and "https".
Server *string `json:"server,omitempty"`
// Username - The username for the private registry.
Username *string `json:"username,omitempty"`
// Password - The password for the private registry.
Password *string `json:"password,omitempty"`
// Identity - The identity for the private registry.
Identity *string `json:"identity,omitempty"`
// IdentityURL - The identity URL for the private registry.
IdentityURL *string `json:"identityUrl,omitempty"`
}
// InitContainerDefinition the init container definition.
type InitContainerDefinition struct {
// Name - The name for the init container.
Name *string `json:"name,omitempty"`
// InitContainerPropertiesDefinition - The properties for the init container.
*InitContainerPropertiesDefinition `json:"properties,omitempty"`
}
// MarshalJSON is the custom marshaler for InitContainerDefinition.
func (icd InitContainerDefinition) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if icd.Name != nil {
objectMap["name"] = icd.Name
}
if icd.InitContainerPropertiesDefinition != nil {
objectMap["properties"] = icd.InitContainerPropertiesDefinition
}
return json.Marshal(objectMap)
}
// UnmarshalJSON is the custom unmarshaler for InitContainerDefinition struct.
func (icd *InitContainerDefinition) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
for k, v := range m {
switch k {
case "name":
if v != nil {
var name string
err = json.Unmarshal(*v, &name)
if err != nil {
return err
}
icd.Name = &name
}
case "properties":
if v != nil {
var initContainerPropertiesDefinition InitContainerPropertiesDefinition
err = json.Unmarshal(*v, &initContainerPropertiesDefinition)
if err != nil {
return err
}
icd.InitContainerPropertiesDefinition = &initContainerPropertiesDefinition
}
}
}
return nil
}
// InitContainerPropertiesDefinition the init container definition properties.
type InitContainerPropertiesDefinition struct {
// Image - The image of the init container.
Image *string `json:"image,omitempty"`
// Command - The command to execute within the init container in exec form.
Command *[]string `json:"command,omitempty"`
// EnvironmentVariables - The environment variables to set in the init container.
EnvironmentVariables *[]EnvironmentVariable `json:"environmentVariables,omitempty"`
// InstanceView - READ-ONLY; The instance view of the init container. Only valid in response.
InstanceView *InitContainerPropertiesDefinitionInstanceView `json:"instanceView,omitempty"`
// VolumeMounts - The volume mounts available to the init container.
VolumeMounts *[]VolumeMount `json:"volumeMounts,omitempty"`
}
// MarshalJSON is the custom marshaler for InitContainerPropertiesDefinition.
func (icpd InitContainerPropertiesDefinition) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if icpd.Image != nil {
objectMap["image"] = icpd.Image
}
if icpd.Command != nil {
objectMap["command"] = icpd.Command
}
if icpd.EnvironmentVariables != nil {
objectMap["environmentVariables"] = icpd.EnvironmentVariables
}
if icpd.VolumeMounts != nil {
objectMap["volumeMounts"] = icpd.VolumeMounts
}
return json.Marshal(objectMap)
}
// InitContainerPropertiesDefinitionInstanceView the instance view of the init container. Only valid in
// response.
type InitContainerPropertiesDefinitionInstanceView struct {
// RestartCount - READ-ONLY; The number of times that the init container has been restarted.
RestartCount *int32 `json:"restartCount,omitempty"`
// CurrentState - READ-ONLY; The current state of the init container.
CurrentState *ContainerState `json:"currentState,omitempty"`
// PreviousState - READ-ONLY; The previous state of the init container.
PreviousState *ContainerState `json:"previousState,omitempty"`
// Events - READ-ONLY; The events of the init container.
Events *[]Event `json:"events,omitempty"`
}
// MarshalJSON is the custom marshaler for InitContainerPropertiesDefinitionInstanceView.
func (icpdV InitContainerPropertiesDefinitionInstanceView) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// IPAddress IP address for the container group.
type IPAddress struct {
// Ports - The list of ports exposed on the container group.
Ports *[]Port `json:"ports,omitempty"`
// Type - Specifies if the IP is exposed to the public internet or private VNET. Possible values include: 'ContainerGroupIPAddressTypePublic', 'ContainerGroupIPAddressTypePrivate'
Type ContainerGroupIPAddressType `json:"type,omitempty"`
// IP - The IP exposed to the public internet.
IP *string `json:"ip,omitempty"`
// DNSNameLabel - The Dns name label for the IP.
DNSNameLabel *string `json:"dnsNameLabel,omitempty"`
// Fqdn - READ-ONLY; The FQDN for the IP.
Fqdn *string `json:"fqdn,omitempty"`
}
// MarshalJSON is the custom marshaler for IPAddress.
func (ia IPAddress) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if ia.Ports != nil {
objectMap["ports"] = ia.Ports
}
if ia.Type != "" {
objectMap["type"] = ia.Type
}
if ia.IP != nil {
objectMap["ip"] = ia.IP
}
if ia.DNSNameLabel != nil {
objectMap["dnsNameLabel"] = ia.DNSNameLabel
}
return json.Marshal(objectMap)
}
// ListString ...
type ListString struct {
autorest.Response `json:"-"`
Value *[]string `json:"value,omitempty"`
}
// LogAnalytics container group log analytics information.
type LogAnalytics struct {
// WorkspaceID - The workspace id for log analytics
WorkspaceID *string `json:"workspaceId,omitempty"`
// WorkspaceKey - The workspace key for log analytics
WorkspaceKey *string `json:"workspaceKey,omitempty"`
// LogType - The log type to be used. Possible values include: 'LogAnalyticsLogTypeContainerInsights', 'LogAnalyticsLogTypeContainerInstanceLogs'
LogType LogAnalyticsLogType `json:"logType,omitempty"`
// Metadata - Metadata for log analytics.
Metadata map[string]*string `json:"metadata"`
// WorkspaceResourceID - The workspace resource id for log analytics
WorkspaceResourceID *string `json:"workspaceResourceId,omitempty"`
}
// MarshalJSON is the custom marshaler for LogAnalytics.
func (la LogAnalytics) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if la.WorkspaceID != nil {
objectMap["workspaceId"] = la.WorkspaceID
}
if la.WorkspaceKey != nil {
objectMap["workspaceKey"] = la.WorkspaceKey
}
if la.LogType != "" {
objectMap["logType"] = la.LogType
}
if la.Metadata != nil {
objectMap["metadata"] = la.Metadata
}
if la.WorkspaceResourceID != nil {
objectMap["workspaceResourceId"] = la.WorkspaceResourceID
}
return json.Marshal(objectMap)
}
// Logs the logs.
type Logs struct {
autorest.Response `json:"-"`
// Content - The content of the log.
Content *string `json:"content,omitempty"`
}
// Operation an operation for Azure Container Instance service.
type Operation struct {
// Name - The name of the operation.
Name *string `json:"name,omitempty"`
// Display - The display information of the operation.
Display *OperationDisplay `json:"display,omitempty"`
// Properties - The additional properties.
Properties interface{} `json:"properties,omitempty"`
// Origin - The intended executor of the operation. Possible values include: 'OperationsOriginUser', 'OperationsOriginSystem'
Origin OperationsOrigin `json:"origin,omitempty"`
}
// OperationDisplay the display information of the operation.
type OperationDisplay struct {
// Provider - The name of the provider of the operation.
Provider *string `json:"provider,omitempty"`
// Resource - The name of the resource type of the operation.
Resource *string `json:"resource,omitempty"`
// Operation - The friendly name of the operation.
Operation *string `json:"operation,omitempty"`
// Description - The description of the operation.
Description *string `json:"description,omitempty"`
}
// OperationListResult the operation list response that contains all operations for Azure Container
// Instance service.
type OperationListResult struct {
autorest.Response `json:"-"`
// Value - The list of operations.
Value *[]Operation `json:"value,omitempty"`
// NextLink - The URI to fetch the next page of operations.
NextLink *string `json:"nextLink,omitempty"`
}
// OperationListResultIterator provides access to a complete listing of Operation values.
type OperationListResultIterator struct {
i int
page OperationListResultPage
}
// NextWithContext advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext")
defer func() {
sc := -1
if iter.Response().Response.Response != nil {
sc = iter.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err = iter.page.NextWithContext(ctx)
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *OperationListResultIterator) Next() error {
return iter.NextWithContext(context.Background())
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter OperationListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter OperationListResultIterator) Response() OperationListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter OperationListResultIterator) Value() Operation {
if !iter.page.NotDone() {
return Operation{}
}
return iter.page.Values()[iter.i]
}
// Creates a new instance of the OperationListResultIterator type.
func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator {
return OperationListResultIterator{page: page}
}
// IsEmpty returns true if the ListResult contains no values.
func (olr OperationListResult) IsEmpty() bool {
return olr.Value == nil || len(*olr.Value) == 0
}
// hasNextLink returns true if the NextLink is not empty.
func (olr OperationListResult) hasNextLink() bool {
return olr.NextLink != nil && len(*olr.NextLink) != 0
}
// operationListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) {
if !olr.hasNextLink() {
return nil, nil
}
return autorest.Prepare((&http.Request{}).WithContext(ctx),
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(olr.NextLink)))
}
// OperationListResultPage contains a page of Operation values.
type OperationListResultPage struct {
fn func(context.Context, OperationListResult) (OperationListResult, error)
olr OperationListResult
}
// NextWithContext advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext")
defer func() {
sc := -1
if page.Response().Response.Response != nil {
sc = page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
for {
next, err := page.fn(ctx, page.olr)
if err != nil {
return err
}
page.olr = next
if !next.hasNextLink() || !next.IsEmpty() {
break
}
}
return nil
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *OperationListResultPage) Next() error {
return page.NextWithContext(context.Background())
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page OperationListResultPage) NotDone() bool {
return !page.olr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page OperationListResultPage) Response() OperationListResult {
return page.olr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page OperationListResultPage) Values() []Operation {
if page.olr.IsEmpty() {
return nil
}
return *page.olr.Value
}
// Creates a new instance of the OperationListResultPage type.
func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage {
return OperationListResultPage{
fn: getNextPage,
olr: cur,
}
}
// Port the port exposed on the container group.
type Port struct {
// Protocol - The protocol associated with the port. Possible values include: 'ContainerGroupNetworkProtocolTCP', 'ContainerGroupNetworkProtocolUDP'
Protocol ContainerGroupNetworkProtocol `json:"protocol,omitempty"`
// Port - The port number.
Port *int32 `json:"port,omitempty"`
}
// Resource the Resource model definition.
type Resource struct {
// ID - READ-ONLY; The resource id.
ID *string `json:"id,omitempty"`
// Name - READ-ONLY; The resource name.
Name *string `json:"name,omitempty"`
// Type - READ-ONLY; The resource type.
Type *string `json:"type,omitempty"`
// Location - The resource location.
Location *string `json:"location,omitempty"`
// Tags - The resource tags.
Tags map[string]*string `json:"tags"`
// Zones - The zones for the container group.
Zones *[]string `json:"zones,omitempty"`
}
// MarshalJSON is the custom marshaler for Resource.
func (r Resource) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if r.Location != nil {
objectMap["location"] = r.Location
}
if r.Tags != nil {
objectMap["tags"] = r.Tags
}
if r.Zones != nil {
objectMap["zones"] = r.Zones
}
return json.Marshal(objectMap)
}
// ResourceLimits the resource limits.
type ResourceLimits struct {
// MemoryInGB - The memory limit in GB of this container instance.
MemoryInGB *float64 `json:"memoryInGB,omitempty"`
// CPU - The CPU limit of this container instance.
CPU *float64 `json:"cpu,omitempty"`
// Gpu - The GPU limit of this container instance.
Gpu *GpuResource `json:"gpu,omitempty"`
}
// ResourceRequests the resource requests.
type ResourceRequests struct {
// MemoryInGB - The memory request in GB of this container instance.
MemoryInGB *float64 `json:"memoryInGB,omitempty"`
// CPU - The CPU request of this container instance.
CPU *float64 `json:"cpu,omitempty"`
// Gpu - The GPU request of this container instance.
Gpu *GpuResource `json:"gpu,omitempty"`
}
// ResourceRequirements the resource requirements.
type ResourceRequirements struct {
// Requests - The resource requests of this container instance.
Requests *ResourceRequests `json:"requests,omitempty"`
// Limits - The resource limits of this container instance.
Limits *ResourceLimits `json:"limits,omitempty"`
}
// Usage a single usage result
type Usage struct {
// Unit - READ-ONLY; Unit of the usage result
Unit *string `json:"unit,omitempty"`
// CurrentValue - READ-ONLY; The current usage of the resource
CurrentValue *int32 `json:"currentValue,omitempty"`
// Limit - READ-ONLY; The maximum permitted usage of the resource.
Limit *int32 `json:"limit,omitempty"`
// Name - READ-ONLY; The name object of the resource
Name *UsageName `json:"name,omitempty"`
}
// MarshalJSON is the custom marshaler for Usage.
func (u Usage) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// UsageListResult the response containing the usage data
type UsageListResult struct {
autorest.Response `json:"-"`
// Value - READ-ONLY; The usage data.
Value *[]Usage `json:"value,omitempty"`
}
// MarshalJSON is the custom marshaler for UsageListResult.
func (ulr UsageListResult) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// UsageName the name object of the resource
type UsageName struct {
// Value - READ-ONLY; The name of the resource
Value *string `json:"value,omitempty"`
// LocalizedValue - READ-ONLY; The localized name of the resource
LocalizedValue *string `json:"localizedValue,omitempty"`
}
// MarshalJSON is the custom marshaler for UsageName.
func (u UsageName) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// Volume the properties of the volume.
type Volume struct {
// Name - The name of the volume.
Name *string `json:"name,omitempty"`
// AzureFile - The Azure File volume.
AzureFile *AzureFileVolume `json:"azureFile,omitempty"`
// EmptyDir - The empty directory volume.
EmptyDir interface{} `json:"emptyDir,omitempty"`
// Secret - The secret volume.
Secret map[string]*string `json:"secret"`
// GitRepo - The git repo volume.
GitRepo *GitRepoVolume `json:"gitRepo,omitempty"`
}
// MarshalJSON is the custom marshaler for Volume.
func (vVar Volume) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if vVar.Name != nil {
objectMap["name"] = vVar.Name
}
if vVar.AzureFile != nil {
objectMap["azureFile"] = vVar.AzureFile
}
if vVar.EmptyDir != nil {
objectMap["emptyDir"] = vVar.EmptyDir
}
if vVar.Secret != nil {
objectMap["secret"] = vVar.Secret
}
if vVar.GitRepo != nil {
objectMap["gitRepo"] = vVar.GitRepo
}
return json.Marshal(objectMap)
}
// VolumeMount the properties of the volume mount.
type VolumeMount struct {
// Name - The name of the volume mount.
Name *string `json:"name,omitempty"`
// MountPath - The path within the container where the volume should be mounted. Must not contain colon (:).
MountPath *string `json:"mountPath,omitempty"`
// ReadOnly - The flag indicating whether the volume mount is read-only.
ReadOnly *bool `json:"readOnly,omitempty"`
}
| mit |
jirutka/gitlabhq | app/models/clusters/applications/ingress.rb | 1435 | # frozen_string_literal: true
module Clusters
module Applications
class Ingress < ActiveRecord::Base
VERSION = '0.23.0'.freeze
self.table_name = 'clusters_applications_ingress'
include ::Clusters::Concerns::ApplicationCore
include ::Clusters::Concerns::ApplicationStatus
include ::Clusters::Concerns::ApplicationVersion
include ::Clusters::Concerns::ApplicationData
include AfterCommitQueue
default_value_for :ingress_type, :nginx
default_value_for :version, VERSION
enum ingress_type: {
nginx: 1
}
FETCH_IP_ADDRESS_DELAY = 30.seconds
state_machine :status do
before_transition any => [:installed] do |application|
application.run_after_commit do
ClusterWaitForIngressIpAddressWorker.perform_in(
FETCH_IP_ADDRESS_DELAY, application.name, application.id)
end
end
end
def chart
'stable/nginx-ingress'
end
def install_command
Gitlab::Kubernetes::Helm::InstallCommand.new(
name: name,
version: VERSION,
rbac: cluster.platform_kubernetes_rbac?,
chart: chart,
files: files
)
end
def schedule_status_update
return unless installed?
return if external_ip
ClusterWaitForIngressIpAddressWorker.perform_async(name, id)
end
end
end
end
| mit |
CoralineAda/alice | spec/models/command_string_spec.rb | 566 | require 'spec_helper'
describe Message::CommandString do
let(:command) {
Message::CommandString.new("!drop the object.")
}
describe "#components" do
it "breaks its text ino an array of words" do
expect(command.components).to eq(["drop", "the", "object"])
end
end
describe "#fragment" do
it "returns its content minus its verb" do
expect(command.fragment).to eq("the object")
end
end
describe "#verb" do
it "selects the first component as its verb" do
expect(command.verb).to eq("drop")
end
end
end
| mit |
joshbayley/spacetrader-unity | Assets/GUI/Screens/Missions/MissionsMenu.cs | 2159 | #pragma warning disable 0649
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class MissionsMenu : MonoBehaviour
{
[SerializeField]
private Transform missionsLayout;
[SerializeField]
private MissionMenuItem missionElementPrefab;
[SerializeField]
private Text selectedMissionTitle;
[SerializeField]
private Text selectedMissionDescription;
[SerializeField]
private Button[] missionActionButtons;
private MissionDefinition selectedMission;
public void SelectMission(MissionDefinition mission)
{
selectedMission = mission;
if (!selectedMission)
{
selectedMissionTitle.text = "No mission selected";
selectedMissionDescription.text = "";
}
else
{
selectedMissionTitle.text = selectedMission.MissionName;
selectedMissionDescription.text = selectedMission.Description;
}
foreach (var button in missionActionButtons)
{
button.interactable = !!selectedMission;
}
}
void OnEnable()
{
foreach (var button in GetComponentsInChildren<MissionMenuItem>())
{
Destroy(button.gameObject);
}
foreach (var mission in SpaceTraderConfig.MissionsConfiguration.Missions)
{
var missionItem = MissionMenuItem.Create(missionElementPrefab, mission);
missionItem.transform.SetParent(missionsLayout, false);
}
SelectMission(null);
}
void OnDisable()
{
SelectMission(null);
}
private IEnumerator PlayOfflineRoutine(MissionDefinition missionDef)
{
var gui = GetComponentInParent<GUIController>();
yield return gui.ShowLoadingOverlay();
yield return MissionManager.Instance.PrepMission(missionDef);
gui.DismissLoadingOverlay();
yield return gui.SwitchTo(ScreenID.MissionPrep);
}
public void PlayOffline()
{
if (selectedMission)
{
StartCoroutine(PlayOfflineRoutine(selectedMission));
}
}
}
| mit |
Ivoz/flask-uwsgi-websocket | examples/chat-gevent/chat.py | 609 | #!/usr/bin/env python
from flask import Flask, render_template
from flask.ext.uwsgi_websocket import GeventWSApp
app = Flask(__name__)
ws = GeventWebSocket(app)
users = {}
@app.route('/')
def index():
return render_template('index.html')
@ws.route('/websocket')
def chat(ws):
users[ws.id] = ws
while True:
msg = ws.receive()
if msg is not None:
print users
for id in users:
if id != ws.id:
users[id].send(msg)
else: break
del users[ws.id]
if __name__ == '__main__':
app.run(debug=True, gevent=100)
| mit |
avanov/solo | solo/server/sessions/__init__.py | 85 | from .session import Session, update_session
__all__ = ('Session', 'update_session') | mit |
danbickford007/ruby_chat | lib/commands.rb | 3952 | class Commands
attr_accessor :used, :clients
def initialize msg=nil, client=nil, categories=nil, category=nil, username=nil, clients=nil
@msg = msg
@client = client
@categories = categories
@category = category
@username = username
@clients = clients
@used = false
end
def check
exit_now
category
categories
help
history
password
{categories: @categories, category: @category}
end
def password
if @msg.match(/password:/)
@used = true
Password.set(@username, @msg.split(/password:/)[1])
@client.puts "yellow:password has been set."
end
end
def history
if @msg.match(/history:/)
@used = true
@client.puts "Topic History:"
p hist = @msg.split(/history:/)[1]
url = `pwd`
url.gsub!(/\n/, '')
p url = "#{url}/logs/#{hist}.txt"
f = File.open(url, "r")
f.each_line do |line|
@client.puts "yellow:#{line}"
end
f.close
elsif @msg.match(/history/)
@used = true
history = History.new(@client, @msg)
history.list
end
end
def exit_now
if @msg.match(/exit/)
@used = true
@client.puts "exit:"
@clients.reject! { |key| key.to_s == @username.to_s}
end
end
def category
if @msg.match(/category:/)
@used = true
cat = @msg.split('category:')[1]
cat.strip!
if @categories.include? cat
hash = Hash[@categories.map.with_index.to_a]
@category = hash[cat]
quick_print_history cat
elsif cat.match(/\d/) and @categories[cat.to_i]
p "HERE...."
@category = cat.to_i
quick_print_history @categories[cat.to_i]
else
@categories << cat
hash = Hash[@categories.map.with_index.to_a]
@category = hash[cat]
end
end
end
def quick_print_history cat
p url = `pwd`.gsub(/\n/, '')
url = "#{url}/logs/"
p file = "#{url}#{cat}.txt"
@client.puts `tail -n 15 #{file}`
end
def categories
if @msg.match(/categories/)
@used = true
@categories.each_with_index do |cat, i|
count = 0
@clients.each{|k,v| count += 1 if v[1] == i}
@client.puts "#{i}. #{i == @category ? '*' : ''}#{cat} (#{count} active users)"
end
end
end
def help
if @msg.match(/help/)
@used = true
@client.puts "Current open categories to chat in:"
@client.puts "-----------------------------------"
@categories.each_with_index do |cat, i|
@client.puts "#{i}. #{cat}"
end
@client.puts "yellow:-----------------------------------------------------------------------------------------------"
@client.puts "To select a category, issue command 'category:test' with 'test being the name of your category'"
@client.puts "yellow:-----------------------------------------------------------------------------------------------"
@client.puts "To view all the categories and your current category defined by '*', issue command 'categories'"
@client.puts "yellow:-----------------------------------------------------------------------------------------------"
@client.puts "To exit, issue command 'exit'"
@client.puts "yellow:-----------------------------------------------------------------------------------------------"
@client.puts "To keep your username, set a password by issuing 'password:1234'"
@client.puts "yellow:-----------------------------------------------------------------------------------------------"
@client.puts "To view all available history for different topics, issue command 'history'"
@client.puts "yellow:-----------------------------------------------------------------------------------------------"
@client.puts "To view history for a specific subject, issue command 'history:myCategory' with myCategory being the history to view"
end
category
end
end
| mit |
Microsoft/WPF-Samples | Windows/Wizard/WizardReturnEventArgs.cs | 455 | // // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Wizard
{
public class WizardReturnEventArgs
{
public WizardReturnEventArgs(WizardResult result, object data)
{
Result = result;
Data = data;
}
public WizardResult Result { get; }
public object Data { get; }
}
} | mit |
StephenClearyApps/DotNetApis | service/DotNetApis.Logic/GenerationScope.cs | 791 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetApis.Common;
using DotNetApis.Logic.Assemblies;
using DotNetApis.Nuget;
namespace DotNetApis.Logic
{
public sealed class GenerationScope : ScopeBase<GenerationScope>
{
private GenerationScope(PlatformTarget platformTarget, AssemblyCollection asssemblies)
{
PlatformTarget = platformTarget;
Asssemblies = asssemblies;
}
public PlatformTarget PlatformTarget { get; }
public AssemblyCollection Asssemblies { get; }
public static IDisposable Create(PlatformTarget platformTarget, AssemblyCollection asssemblies) => Create(new GenerationScope(platformTarget, asssemblies));
}
}
| mit |
stivalet/PHP-Vulnerability-test-suite | XSS/CWE_79/unsafe/CWE_79__system__func_FILTER-CLEANING-special_chars_filter__Use_untrusted_data_script-window_SetInterval.php | 1445 | <!--
Unsafe sample
input : execute a ls command using the function system, and put the last result in $tainted
Uses a special_chars_filter via filter_var function
File : unsafe, use of untrusted data in the function setInterval
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head>
<script>
<?php
$tainted = system('ls', $retval);
$sanitized = filter_var($tainted, FILTER_SANITIZE_SPECIAL_CHARS);
$tainted = $sanitized ;
//flaw
echo "window.setInterval('". $tainted ."');" ;
?>
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html> | mit |
vistarsoft/git-log-viewer | src/modules/detail/reducers/repository.js | 336 | import ActionType from 'constants/actiontype.js';
export default (state = {}, action) => {
switch (action.type) {
case ActionType.UPDATE_REPOSITORY:
return state.merge(action.data);
case ActionType.CHANGE_BRANCH:
return state.set('currentBranch', action.data);
default:
return state;
}
}
| mit |
hereforu/tizen-multimedia-apps | transcoder/src/popupprogress.cpp | 2406 | /*
* popupprogress.cpp
*
* Created on: Jun 30, 2016
* Author: Jason
*/
#include "popupprogress.h"
#include <stdexcept>
PopupProgress::PopupProgress()
:m_cancelbtn(NULL), m_pb(NULL), m_popup(NULL), m_parent(NULL)
{
}
PopupProgress::~PopupProgress()
{
}
void PopupProgress::Create(Evas_Object* parent, Porgress_Cancel_Cb cancel_cb, void* data)
{
m_cancelcb = cancel_cb;
m_data = data;
m_popup = createpopup(parent);
m_pb = createpb(m_popup);
m_cancelbtn = createcancelbtn(m_popup);
elm_object_part_content_set(m_popup, "default", m_pb);
elm_object_part_content_set(m_popup, "button2", m_cancelbtn);
m_parent = parent;
}
void PopupProgress::Destroy()
{
SAFE_EVAS_DELETE(m_pb);
SAFE_EVAS_DELETE(m_cancelbtn);
SAFE_EVAS_DELETE(m_popup);
}
void PopupProgress::Popup()
{
evas_object_show(m_popup);
}
void PopupProgress::Hide()
{
evas_object_hide(m_popup);
}
void PopupProgress::SetValue(double value)
{
elm_progressbar_value_set(m_pb, value);
}
Evas_Object* PopupProgress::createpopup(Evas_Object* parent)
{
Evas_Object* popup = elm_popup_add(parent);
if(popup==NULL)
{
throw std::runtime_error("fail to create popup");
}
elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
return popup;
}
Evas_Object* PopupProgress::createpb(Evas_Object* parent)
{
Evas_Object* pb = elm_progressbar_add(parent);
if(pb==NULL)
{
throw std::runtime_error("fail to create Progress");
}
elm_object_style_set(pb, "default");
elm_object_text_set(pb, "Transcoding...");
elm_progressbar_value_set(pb, 0.0);
return pb;
}
Evas_Object* PopupProgress::createcancelbtn(Evas_Object* parent)
{
Evas_Object* btn = elm_button_add(parent);
if(btn==NULL)
{
throw std::runtime_error("fail to create Progress");
}
std::string resource_path = app_get_resource_path();
resource_path += "images/cancel.png";
Evas_Object *ic;
ic = elm_icon_add(btn);
elm_image_file_set(ic, resource_path.c_str(), NULL);
elm_object_part_content_set(btn, "icon", ic);
elm_object_style_set(btn,"circle");
evas_object_smart_callback_add(btn, "clicked", PopupProgress::clicked_cancel_cb, (void*)this);
return btn;
}
void PopupProgress::cancel()
{
m_cancelcb(m_data);
}
void PopupProgress::clicked_cancel_cb(void *data, Evas_Object *obj, void *event_info)
{
PopupProgress* popup = (PopupProgress*)data;
popup->cancel();
}
| mit |
ryan-laurence/stic | js/validator.js | 164973 |
<!DOCTYPE html>
<html lang="en" class=" is-copy-enabled is-u2f-enabled">
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#">
<meta charset='utf-8'>
<link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/frameworks-99bbe9ec608366f7ca64d4ce812d55f19c0fc647f99b2edc95f06fc8f4fb3752.css" integrity="sha256-mbvp7GCDZvfKZNTOgS1V8ZwPxkf5my7clfBvyPT7N1I=" media="all" rel="stylesheet" />
<link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/github-b76daf817af087a37a303a52e34b04204617814cc893b427a077b35168b59554.css" integrity="sha256-t22vgXrwh6N6MDpS40sEIEYXgUzIk7QnoHezUWi1lVQ=" media="all" rel="stylesheet" />
<link as="script" href="https://assets-cdn.github.com/assets/frameworks-5c2c698a5a7dbecfbfed7180198b5cc5bc21d0588392269449bed16d124f0ea3.js" rel="preload" />
<link as="script" href="https://assets-cdn.github.com/assets/github-bf0bf1cd49adbab6c52f3af0eab40c89621e0b56532eff5e7c943008c79e21ec.js" rel="preload" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Language" content="en">
<meta name="viewport" content="width=1020">
<title>bootstrap-validator/validator.js at master · 1000hz/bootstrap-validator</title>
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub">
<link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
<meta property="fb:app_id" content="1401488693436528">
<meta content="https://avatars2.githubusercontent.com/u/1395018?v=3&s=400" name="twitter:image:src" /><meta content="@github" name="twitter:site" /><meta content="summary" name="twitter:card" /><meta content="1000hz/bootstrap-validator" name="twitter:title" /><meta content="bootstrap-validator - A user-friendly HTML5 form validation jQuery plugin for Bootstrap 3" name="twitter:description" />
<meta content="https://avatars2.githubusercontent.com/u/1395018?v=3&s=400" property="og:image" /><meta content="GitHub" property="og:site_name" /><meta content="object" property="og:type" /><meta content="1000hz/bootstrap-validator" property="og:title" /><meta content="https://github.com/1000hz/bootstrap-validator" property="og:url" /><meta content="bootstrap-validator - A user-friendly HTML5 form validation jQuery plugin for Bootstrap 3" property="og:description" />
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<link rel="assets" href="https://assets-cdn.github.com/">
<link rel="web-socket" href="wss://live.github.com/_sockets/MTY0MDc4NTY6MDFiN2ZjNzMwYzM1ZWVkMDI1YmExODY1OTg5M2VlZTQ6YmM3NmNiODBjZWU3YzBhNzUyOTE5NWY4M2YyODU0ZDk3MDFlM2IzMjBlYWJhN2I4Nzk0NmM4ZmIyYjEwMTg5YQ==--a0be8e8788c6e7cd4dc9b69b8fa980063e5f7df0">
<meta name="pjax-timeout" content="1000">
<link rel="sudo-modal" href="/sessions/sudo_modal">
<meta name="msapplication-TileImage" content="/windows-tile.png">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="selected-link" value="repo_source" data-pjax-transient>
<meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU">
<meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA">
<meta name="google-analytics" content="UA-3769691-2">
<meta content="collector.githubapp.com" name="octolytics-host" /><meta content="github" name="octolytics-app-id" /><meta content="70CE43C1:0E36:321B73D:570268D0" name="octolytics-dimension-request_id" /><meta content="16407856" name="octolytics-actor-id" /><meta content="ryan-laurence" name="octolytics-actor-login" /><meta content="9d9645e47b6b7b4a2d6156558aae245c8108974bdb12893c0f144eca35eb78cf" name="octolytics-actor-hash" />
<meta content="/<user-name>/<repo-name>/blob/show" data-pjax-transient="true" name="analytics-location" />
<meta class="js-ga-set" name="dimension1" content="Logged In">
<meta name="hostname" content="github.com">
<meta name="user-login" content="ryan-laurence">
<meta name="expected-hostname" content="github.com">
<meta name="js-proxy-site-detection-payload" content="NWZkMzA5OTJmNDlhMGNkMTIzMmVjNDc5ZjczYmU4MWI1N2NhNzJhYTM1Y2RiMDM4M2FlMTgyNmU4Y2QwOGFjNHx7InJlbW90ZV9hZGRyZXNzIjoiMTEyLjIwNi42Ny4xOTMiLCJyZXF1ZXN0X2lkIjoiNzBDRTQzQzE6MEUzNjozMjFCNzNEOjU3MDI2OEQwIiwidGltZXN0YW1wIjoxNDU5Nzc1Njk2fQ==">
<link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#4078c0">
<link rel="icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico">
<meta content="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" name="form-nonce" />
<meta http-equiv="x-pjax-version" content="18529cf0d2f7f84784eaad979171203e">
<meta name="description" content="bootstrap-validator - A user-friendly HTML5 form validation jQuery plugin for Bootstrap 3">
<meta name="go-import" content="github.com/1000hz/bootstrap-validator git https://github.com/1000hz/bootstrap-validator.git">
<meta content="1395018" name="octolytics-dimension-user_id" /><meta content="1000hz" name="octolytics-dimension-user_login" /><meta content="14457098" name="octolytics-dimension-repository_id" /><meta content="1000hz/bootstrap-validator" name="octolytics-dimension-repository_nwo" /><meta content="true" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="14457098" name="octolytics-dimension-repository_network_root_id" /><meta content="1000hz/bootstrap-validator" name="octolytics-dimension-repository_network_root_nwo" />
<link href="https://github.com/1000hz/bootstrap-validator/commits/master.atom" rel="alternate" title="Recent Commits to bootstrap-validator:master" type="application/atom+xml">
<link rel="canonical" href="https://github.com/1000hz/bootstrap-validator/blob/master/dist/validator.js" data-pjax-transient>
</head>
<body class="logged-in env-production windows vis-public page-blob">
<div id="js-pjax-loader-bar" class="pjax-loader-bar"></div>
<a href="#start-of-content" tabindex="1" class="accessibility-aid js-skip-to-content">Skip to content</a>
<div class="header header-logged-in true" role="banner">
<div class="container clearfix">
<a class="header-logo-invertocat" href="https://github.com/" data-hotkey="g d" aria-label="Homepage" data-ga-click="Header, go to dashboard, icon:logo">
<svg aria-hidden="true" class="octicon octicon-mark-github" height="28" version="1.1" viewBox="0 0 16 16" width="28"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59 0.4 0.07 0.55-0.17 0.55-0.38 0-0.19-0.01-0.82-0.01-1.49-2.01 0.37-2.53-0.49-2.69-0.94-0.09-0.23-0.48-0.94-0.82-1.13-0.28-0.15-0.68-0.52-0.01-0.53 0.63-0.01 1.08 0.58 1.23 0.82 0.72 1.21 1.87 0.87 2.33 0.66 0.07-0.52 0.28-0.87 0.51-1.07-1.78-0.2-3.64-0.89-3.64-3.95 0-0.87 0.31-1.59 0.82-2.15-0.08-0.2-0.36-1.02 0.08-2.12 0 0 0.67-0.21 2.2 0.82 0.64-0.18 1.32-0.27 2-0.27 0.68 0 1.36 0.09 2 0.27 1.53-1.04 2.2-0.82 2.2-0.82 0.44 1.1 0.16 1.92 0.08 2.12 0.51 0.56 0.82 1.27 0.82 2.15 0 3.07-1.87 3.75-3.65 3.95 0.29 0.25 0.54 0.73 0.54 1.48 0 1.07-0.01 1.93-0.01 2.2 0 0.21 0.15 0.46 0.55 0.38C13.71 14.53 16 11.53 16 8 16 3.58 12.42 0 8 0z"></path></svg>
</a>
<div class="header-search scoped-search site-scoped-search js-site-search" role="search">
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/1000hz/bootstrap-validator/search" class="js-site-search-form" data-scoped-search-url="/1000hz/bootstrap-validator/search" data-unscoped-search-url="/search" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<label class="form-control header-search-wrapper js-chromeless-input-container">
<div class="header-search-scope">This repository</div>
<input type="text"
class="form-control header-search-input js-site-search-focus js-site-search-field is-clearable"
data-hotkey="s"
name="q"
placeholder="Search"
aria-label="Search this repository"
data-unscoped-placeholder="Search GitHub"
data-scoped-placeholder="Search"
tabindex="1"
autocapitalize="off">
</label>
</form></div>
<ul class="header-nav left" role="navigation">
<li class="header-nav-item">
<a href="/pulls" class="js-selected-navigation-item header-nav-link" data-ga-click="Header, click, Nav menu - item:pulls context:user" data-hotkey="g p" data-selected-links="/pulls /pulls/assigned /pulls/mentioned /pulls">
Pull requests
</a> </li>
<li class="header-nav-item">
<a href="/issues" class="js-selected-navigation-item header-nav-link" data-ga-click="Header, click, Nav menu - item:issues context:user" data-hotkey="g i" data-selected-links="/issues /issues/assigned /issues/mentioned /issues">
Issues
</a> </li>
<li class="header-nav-item">
<a class="header-nav-link" href="https://gist.github.com/" data-ga-click="Header, go to gist, text:gist">Gist</a>
</li>
</ul>
<ul class="header-nav user-nav right" id="user-links">
<li class="header-nav-item">
<a href="/notifications" aria-label="You have no unread notifications" class="header-nav-link notification-indicator tooltipped tooltipped-s js-socket-channel js-notification-indicator" data-channel="notification-changed-v2:16407856" data-ga-click="Header, go to notifications, icon:read" data-hotkey="g n">
<span class="mail-status "></span>
<svg aria-hidden="true" class="octicon octicon-bell" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M14 12v1H0v-1l0.73-0.58c0.77-0.77 0.81-2.55 1.19-4.42 0.77-3.77 4.08-5 4.08-5 0-0.55 0.45-1 1-1s1 0.45 1 1c0 0 3.39 1.23 4.16 5 0.38 1.88 0.42 3.66 1.19 4.42l0.66 0.58z m-7 4c1.11 0 2-0.89 2-2H5c0 1.11 0.89 2 2 2z"></path></svg>
</a>
</li>
<li class="header-nav-item dropdown js-menu-container">
<a class="header-nav-link tooltipped tooltipped-s js-menu-target" href="/new"
aria-label="Create new…"
data-ga-click="Header, create new, icon:add">
<svg aria-hidden="true" class="octicon octicon-plus left" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 9H7v5H5V9H0V7h5V2h2v5h5v2z"></path></svg>
<span class="dropdown-caret"></span>
</a>
<div class="dropdown-menu-content js-menu-content">
<ul class="dropdown-menu dropdown-menu-sw">
<a class="dropdown-item" href="/new" data-ga-click="Header, create new repository">
New repository
</a>
<a class="dropdown-item" href="/organizations/new" data-ga-click="Header, create new organization">
New organization
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-header">
<span title="1000hz/bootstrap-validator">This repository</span>
</div>
<a class="dropdown-item" href="/1000hz/bootstrap-validator/issues/new" data-ga-click="Header, create new issue">
New issue
</a>
</ul>
</div>
</li>
<li class="header-nav-item dropdown js-menu-container">
<a class="header-nav-link name tooltipped tooltipped-sw js-menu-target" href="/ryan-laurence"
aria-label="View profile and more"
data-ga-click="Header, show menu, icon:avatar">
<img alt="@ryan-laurence" class="avatar" height="20" src="https://avatars1.githubusercontent.com/u/16407856?v=3&s=40" width="20" />
<span class="dropdown-caret"></span>
</a>
<div class="dropdown-menu-content js-menu-content">
<div class="dropdown-menu dropdown-menu-sw">
<div class=" dropdown-header header-nav-current-user css-truncate">
Signed in as <strong class="css-truncate-target">ryan-laurence</strong>
</div>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/ryan-laurence" data-ga-click="Header, go to profile, text:your profile">
Your profile
</a>
<a class="dropdown-item" href="/stars" data-ga-click="Header, go to starred repos, text:your stars">
Your stars
</a>
<a class="dropdown-item" href="/explore" data-ga-click="Header, go to explore, text:explore">
Explore
</a>
<a class="dropdown-item" href="/integrations" data-ga-click="Header, go to integrations, text:integrations">
Integrations
</a>
<a class="dropdown-item" href="https://help.github.com" data-ga-click="Header, go to help, text:help">
Help
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/settings/profile" data-ga-click="Header, go to settings, icon:settings">
Settings
</a>
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/logout" class="logout-form" data-form-nonce="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="vKaN89JKzRnh56qVYKV1NYxZylMbTcylUMHYxVaXJbkYA1GwUhoLX+7sW2jhcnv1cAtbeL9qkDLNG9uAAw5HbQ==" /></div>
<button class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout">
Sign out
</button>
</form>
</div>
</div>
</li>
</ul>
</div>
</div>
<div id="start-of-content" class="accessibility-aid"></div>
<div id="js-flash-container">
</div>
<div role="main" class="main-content">
<div itemscope itemtype="http://schema.org/SoftwareSourceCode">
<div id="js-repo-pjax-container" data-pjax-container>
<div class="pagehead repohead instapaper_ignore readability-menu experiment-repo-nav">
<div class="container repohead-details-container">
<ul class="pagehead-actions">
<li>
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/notifications/subscribe" class="js-social-container" data-autosubmit="true" data-form-nonce="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="m7jXoGG6AmtmnNnnVPlJJqpWdFg3nIYxELbyyG0HULwWR6cUYq1NnWhx8CH1uHG0/rOQZZPwk8a0Q0nzUlZgEA==" /></div> <input class="form-control" id="repository_id" name="repository_id" type="hidden" value="14457098" />
<div class="select-menu js-menu-container js-select-menu">
<a href="/1000hz/bootstrap-validator/subscription"
class="btn btn-sm btn-with-count select-menu-button js-menu-target" role="button" tabindex="0" aria-haspopup="true"
data-ga-click="Repository, click Watch settings, action:blob#show">
<span class="js-select-button">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6c4.94 0 7.94-6 7.94-6S13 2 8.06 2z m-0.06 10c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4z m2-4c0 1.11-0.89 2-2 2s-2-0.89-2-2 0.89-2 2-2 2 0.89 2 2z"></path></svg>
Watch
</span>
</a>
<a class="social-count js-social-count" href="/1000hz/bootstrap-validator/watchers">
74
</a>
<div class="select-menu-modal-holder">
<div class="select-menu-modal subscription-menu-modal js-menu-content" aria-hidden="true">
<div class="select-menu-header js-navigation-enable" tabindex="-1">
<svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path d="M7.48 8l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75-1.48-1.48 3.75-3.75L0.77 4.25l1.48-1.48 3.75 3.75 3.75-3.75 1.48 1.48-3.75 3.75z"></path></svg>
<span class="select-menu-title">Notifications</span>
</div>
<div class="select-menu-list js-navigation-container" role="menu">
<div class="select-menu-item js-navigation-item selected" role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<div class="select-menu-item-text">
<input checked="checked" id="do_included" name="do" type="radio" value="included" />
<span class="select-menu-item-heading">Not watching</span>
<span class="description">Be notified when participating or @mentioned.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6c4.94 0 7.94-6 7.94-6S13 2 8.06 2z m-0.06 10c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4z m2-4c0 1.11-0.89 2-2 2s-2-0.89-2-2 0.89-2 2-2 2 0.89 2 2z"></path></svg>
Watch
</span>
</div>
</div>
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<div class="select-menu-item-text">
<input id="do_subscribed" name="do" type="radio" value="subscribed" />
<span class="select-menu-item-heading">Watching</span>
<span class="description">Be notified of all conversations.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6c4.94 0 7.94-6 7.94-6S13 2 8.06 2z m-0.06 10c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4z m2-4c0 1.11-0.89 2-2 2s-2-0.89-2-2 0.89-2 2-2 2 0.89 2 2z"></path></svg>
Unwatch
</span>
</div>
</div>
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<div class="select-menu-item-text">
<input id="do_ignore" name="do" type="radio" value="ignore" />
<span class="select-menu-item-heading">Ignoring</span>
<span class="description">Never be notified.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-mute" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8 2.81v10.38c0 0.67-0.81 1-1.28 0.53L3 10H1c-0.55 0-1-0.45-1-1V7c0-0.55 0.45-1 1-1h2l3.72-3.72c0.47-0.47 1.28-0.14 1.28 0.53z m7.53 3.22l-1.06-1.06-1.97 1.97-1.97-1.97-1.06 1.06 1.97 1.97-1.97 1.97 1.06 1.06 1.97-1.97 1.97 1.97 1.06-1.06-1.97-1.97 1.97-1.97z"></path></svg>
Stop ignoring
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</li>
<li>
<div class="js-toggler-container js-social-container starring-container ">
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/1000hz/bootstrap-validator/unstar" class="js-toggler-form starred" data-form-nonce="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="6CF7z9IJFCFkzRobkrRBYnqpVTl+Y0dESHrrtb303PmAWqV3SGAl+hh0eiMjB1l0sXm3oIcQWUpnR5WYO1WhZQ==" /></div>
<button
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Unstar this repository" title="Unstar 1000hz/bootstrap-validator"
data-ga-click="Repository, click unstar button, action:blob#show; text:Unstar">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M14 6l-4.9-0.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14l4.33-2.33 4.33 2.33L10.4 9.26 14 6z"></path></svg>
Unstar
</button>
<a class="social-count js-social-count" href="/1000hz/bootstrap-validator/stargazers">
1,021
</a>
</form>
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/1000hz/bootstrap-validator/star" class="js-toggler-form unstarred" data-form-nonce="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="zAvSf4IEhQBI8IH48/+M+Rz/45aSHUX6fHD3r0t2FAiq5jfzYw+GQCq1CiPnx/Zd4vToGz7pNEc4Euj3DhpXIQ==" /></div>
<button
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Star this repository" title="Star 1000hz/bootstrap-validator"
data-ga-click="Repository, click star button, action:blob#show; text:Star">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M14 6l-4.9-0.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14l4.33-2.33 4.33 2.33L10.4 9.26 14 6z"></path></svg>
Star
</button>
<a class="social-count js-social-count" href="/1000hz/bootstrap-validator/stargazers">
1,021
</a>
</form> </div>
</li>
<li>
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/1000hz/bootstrap-validator/fork" class="btn-with-count" data-form-nonce="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="Tik/PbiVZ/FblqyTniAgwkUd0mV6PXZgZFOcgGiyA0udDOaUyRHJ6vD78IlV60kBdjlPuHLjRaFaI5aHdNcnyg==" /></div>
<button
type="submit"
class="btn btn-sm btn-with-count"
data-ga-click="Repository, show fork modal, action:blob#show; text:Fork"
title="Fork your own copy of 1000hz/bootstrap-validator to your account"
aria-label="Fork your own copy of 1000hz/bootstrap-validator to your account">
<svg aria-hidden="true" class="octicon octicon-repo-forked" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path d="M8 1c-1.11 0-2 0.89-2 2 0 0.73 0.41 1.38 1 1.72v1.28L5 8 3 6v-1.28c0.59-0.34 1-0.98 1-1.72 0-1.11-0.89-2-2-2S0 1.89 0 3c0 0.73 0.41 1.38 1 1.72v1.78l3 3v1.78c-0.59 0.34-1 0.98-1 1.72 0 1.11 0.89 2 2 2s2-0.89 2-2c0-0.73-0.41-1.38-1-1.72V9.5l3-3V4.72c0.59-0.34 1-0.98 1-1.72 0-1.11-0.89-2-2-2zM2 4.2c-0.66 0-1.2-0.55-1.2-1.2s0.55-1.2 1.2-1.2 1.2 0.55 1.2 1.2-0.55 1.2-1.2 1.2z m3 10c-0.66 0-1.2-0.55-1.2-1.2s0.55-1.2 1.2-1.2 1.2 0.55 1.2 1.2-0.55 1.2-1.2 1.2z m3-10c-0.66 0-1.2-0.55-1.2-1.2s0.55-1.2 1.2-1.2 1.2 0.55 1.2 1.2-0.55 1.2-1.2 1.2z"></path></svg>
Fork
</button>
</form>
<a href="/1000hz/bootstrap-validator/network" class="social-count">
479
</a>
</li>
</ul>
<h1 class="entry-title public ">
<svg aria-hidden="true" class="octicon octicon-repo" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M4 9h-1v-1h1v1z m0-3h-1v1h1v-1z m0-2h-1v1h1v-1z m0-2h-1v1h1v-1z m8-1v12c0 0.55-0.45 1-1 1H6v2l-1.5-1.5-1.5 1.5V14H1c-0.55 0-1-0.45-1-1V1C0 0.45 0.45 0 1 0h10c0.55 0 1 0.45 1 1z m-1 10H1v2h2v-1h3v1h5V11z m0-10H2v9h9V1z"></path></svg>
<span class="author" itemprop="author"><a href="/1000hz" class="url fn" rel="author">1000hz</a></span><!--
--><span class="path-divider">/</span><!--
--><strong itemprop="name"><a href="/1000hz/bootstrap-validator" data-pjax="#js-repo-pjax-container">bootstrap-validator</a></strong>
</h1>
</div>
<div class="container">
<nav class="reponav js-repo-nav js-sidenav-container-pjax"
itemscope
itemtype="http://schema.org/BreadcrumbList"
role="navigation"
data-pjax="#js-repo-pjax-container">
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/1000hz/bootstrap-validator" aria-selected="true" class="js-selected-navigation-item selected reponav-item" data-hotkey="g c" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches /1000hz/bootstrap-validator" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-code" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M9.5 3l-1.5 1.5 3.5 3.5L8 11.5l1.5 1.5 4.5-5L9.5 3zM4.5 3L0 8l4.5 5 1.5-1.5L2.5 8l3.5-3.5L4.5 3z"></path></svg>
<span itemprop="name">Code</span>
<meta itemprop="position" content="1">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/1000hz/bootstrap-validator/issues" class="js-selected-navigation-item reponav-item" data-hotkey="g i" data-selected-links="repo_issues repo_labels repo_milestones /1000hz/bootstrap-validator/issues" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-issue-opened" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z"></path></svg>
<span itemprop="name">Issues</span>
<span class="counter">42</span>
<meta itemprop="position" content="2">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/1000hz/bootstrap-validator/pulls" class="js-selected-navigation-item reponav-item" data-hotkey="g p" data-selected-links="repo_pulls /1000hz/bootstrap-validator/pulls" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-git-pull-request" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M11 11.28c0-1.73 0-6.28 0-6.28-0.03-0.78-0.34-1.47-0.94-2.06s-1.28-0.91-2.06-0.94c0 0-1.02 0-1 0V0L4 3l3 3V4h1c0.27 0.02 0.48 0.11 0.69 0.31s0.3 0.42 0.31 0.69v6.28c-0.59 0.34-1 0.98-1 1.72 0 1.11 0.89 2 2 2s2-0.89 2-2c0-0.73-0.41-1.38-1-1.72z m-1 2.92c-0.66 0-1.2-0.55-1.2-1.2s0.55-1.2 1.2-1.2 1.2 0.55 1.2 1.2-0.55 1.2-1.2 1.2zM4 3c0-1.11-0.89-2-2-2S0 1.89 0 3c0 0.73 0.41 1.38 1 1.72 0 1.55 0 5.56 0 6.56-0.59 0.34-1 0.98-1 1.72 0 1.11 0.89 2 2 2s2-0.89 2-2c0-0.73-0.41-1.38-1-1.72V4.72c0.59-0.34 1-0.98 1-1.72z m-0.8 10c0 0.66-0.55 1.2-1.2 1.2s-1.2-0.55-1.2-1.2 0.55-1.2 1.2-1.2 1.2 0.55 1.2 1.2z m-1.2-8.8c-0.66 0-1.2-0.55-1.2-1.2s0.55-1.2 1.2-1.2 1.2 0.55 1.2 1.2-0.55 1.2-1.2 1.2z"></path></svg>
<span itemprop="name">Pull requests</span>
<span class="counter">14</span>
<meta itemprop="position" content="3">
</a> </span>
<a href="/1000hz/bootstrap-validator/wiki" class="js-selected-navigation-item reponav-item" data-hotkey="g w" data-selected-links="repo_wiki /1000hz/bootstrap-validator/wiki">
<svg aria-hidden="true" class="octicon octicon-book" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M2 5h4v1H2v-1z m0 3h4v-1H2v1z m0 2h4v-1H2v1z m11-5H9v1h4v-1z m0 2H9v1h4v-1z m0 2H9v1h4v-1z m2-6v9c0 0.55-0.45 1-1 1H8.5l-1 1-1-1H1c-0.55 0-1-0.45-1-1V3c0-0.55 0.45-1 1-1h5.5l1 1 1-1h5.5c0.55 0 1 0.45 1 1z m-8 0.5l-0.5-0.5H1v9h6V3.5z m7-0.5H8.5l-0.5 0.5v8.5h6V3z"></path></svg>
Wiki
</a>
<a href="/1000hz/bootstrap-validator/pulse" class="js-selected-navigation-item reponav-item" data-selected-links="pulse /1000hz/bootstrap-validator/pulse">
<svg aria-hidden="true" class="octicon octicon-pulse" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M11.5 8L8.8 5.4 6.6 8.5 5.5 1.6 2.38 8H0V10h3.6L4.5 8.2l0.9 5.4L9 8.5l1.6 1.5H14V8H11.5z"></path></svg>
Pulse
</a>
<a href="/1000hz/bootstrap-validator/graphs" class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors /1000hz/bootstrap-validator/graphs">
<svg aria-hidden="true" class="octicon octicon-graph" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M16 14v1H0V0h1v14h15z m-11-1H3V8h2v5z m4 0H7V3h2v10z m4 0H11V6h2v7z"></path></svg>
Graphs
</a>
</nav>
</div>
</div>
<div class="container new-discussion-timeline experiment-repo-nav">
<div class="repository-content">
<a href="/1000hz/bootstrap-validator/blob/54f6f32b7e0e54038e80a9db172fd5a61e2800f5/dist/validator.js" class="hidden js-permalink-shortcut" data-hotkey="y">Permalink</a>
<!-- blob contrib key: blob_contributors:v21:cea66d4a6b4fef35dd39995550627768 -->
<div class="file-navigation js-zeroclipboard-container">
<div class="select-menu js-menu-container js-select-menu left">
<button class="btn btn-sm select-menu-button js-menu-target css-truncate" data-hotkey="w"
title="master"
type="button" aria-label="Switch branches or tags" tabindex="0" aria-haspopup="true">
<i>Branch:</i>
<span class="js-select-button css-truncate-target">master</span>
</button>
<div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax aria-hidden="true">
<div class="select-menu-modal">
<div class="select-menu-header">
<svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path d="M7.48 8l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75-1.48-1.48 3.75-3.75L0.77 4.25l1.48-1.48 3.75 3.75 3.75-3.75 1.48 1.48-3.75 3.75z"></path></svg>
<span class="select-menu-title">Switch branches/tags</span>
</div>
<div class="select-menu-filters">
<div class="select-menu-text-filter">
<input type="text" aria-label="Filter branches/tags" id="context-commitish-filter-field" class="form-control js-filterable-field js-navigation-enable" placeholder="Filter branches/tags">
</div>
<div class="select-menu-tabs">
<ul>
<li class="select-menu-tab">
<a href="#" data-tab-filter="branches" data-filter-placeholder="Filter branches/tags" class="js-select-menu-tab" role="tab">Branches</a>
</li>
<li class="select-menu-tab">
<a href="#" data-tab-filter="tags" data-filter-placeholder="Find a tag…" class="js-select-menu-tab" role="tab">Tags</a>
</li>
</ul>
</div>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches" role="menu">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/blob/gh-pages/dist/validator.js"
data-name="gh-pages"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text" title="gh-pages">
gh-pages
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open selected"
href="/1000hz/bootstrap-validator/blob/master/dist/validator.js"
data-name="master"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text" title="master">
master
</span>
</a>
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.10.1/dist/validator.js"
data-name="v0.10.1"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.10.1">
v0.10.1
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.10.0/dist/validator.js"
data-name="v0.10.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.10.0">
v0.10.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.9.0/dist/validator.js"
data-name="v0.9.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.9.0">
v0.9.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.8.1/dist/validator.js"
data-name="v0.8.1"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.8.1">
v0.8.1
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.8.0/dist/validator.js"
data-name="v0.8.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.8.0">
v0.8.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.7.3/dist/validator.js"
data-name="v0.7.3"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.7.3">
v0.7.3
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.7.2/dist/validator.js"
data-name="v0.7.2"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.7.2">
v0.7.2
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.7.1/dist/validator.js"
data-name="v0.7.1"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.7.1">
v0.7.1
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.7.0/dist/validator.js"
data-name="v0.7.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.7.0">
v0.7.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.6.0/dist/validator.js"
data-name="v0.6.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.6.0">
v0.6.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.5.0/dist/validator.js"
data-name="v0.5.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.5.0">
v0.5.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.4.0/dist/validator.js"
data-name="v0.4.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.4.0">
v0.4.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.3.0/dist/validator.js"
data-name="v0.3.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.3.0">
v0.3.0
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.2.1/dist/validator.js"
data-name="v0.2.1"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.2.1">
v0.2.1
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/1000hz/bootstrap-validator/tree/v0.2.0/dist/validator.js"
data-name="v0.2.0"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>
<span class="select-menu-item-text css-truncate-target" title="v0.2.0">
v0.2.0
</span>
</a>
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div>
</div>
</div>
</div>
<div class="btn-group right">
<a href="/1000hz/bootstrap-validator/find/master"
class="js-pjax-capture-input btn btn-sm"
data-pjax
data-hotkey="t">
Find file
</a>
<button aria-label="Copy file path to clipboard" class="js-zeroclipboard btn btn-sm zeroclipboard-button tooltipped tooltipped-s" data-copied-hint="Copied!" type="button">Copy path</button>
</div>
<div class="breadcrumb js-zeroclipboard-target">
<span class="repo-root js-repo-root"><span class="js-path-segment"><a href="/1000hz/bootstrap-validator"><span>bootstrap-validator</span></a></span></span><span class="separator">/</span><span class="js-path-segment"><a href="/1000hz/bootstrap-validator/tree/master/dist"><span>dist</span></a></span><span class="separator">/</span><strong class="final-path">validator.js</strong>
</div>
</div>
<div class="commit-tease">
<span class="right">
<a class="commit-tease-sha" href="/1000hz/bootstrap-validator/commit/511b4036c8c733d2da0facb2e2218f3de56a3e96" data-pjax>
511b403
</a>
<time datetime="2016-03-03T21:20:10Z" is="relative-time">Mar 3, 2016</time>
</span>
<div>
<img alt="@1000hz" class="avatar" height="20" src="https://avatars0.githubusercontent.com/u/1395018?v=3&s=40" width="20" />
<a href="/1000hz" class="user-mention" rel="author">1000hz</a>
<a href="/1000hz/bootstrap-validator/commit/511b4036c8c733d2da0facb2e2218f3de56a3e96" class="message" data-pjax="true" title="v0.10.1 :rotating_light: BOY HE BOUT TO DO IT (AGAIN)!!!!!!!!">v0.10.1 <img class="emoji" title=":rotating_light:" alt=":rotating_light:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f6a8.png" height="20" width="20" align="absmiddle"> BOY HE BOUT TO DO IT (AGAIN)!!!!!!!!</a>
</div>
<div class="commit-tease-contributors">
<button type="button" class="btn-link muted-link contributors-toggle" data-facebox="#blob_contributors_box">
<strong>5</strong>
contributors
</button>
<a class="avatar-link tooltipped tooltipped-s" aria-label="1000hz" href="/1000hz/bootstrap-validator/commits/master/dist/validator.js?author=1000hz"><img alt="@1000hz" class="avatar" height="20" src="https://avatars0.githubusercontent.com/u/1395018?v=3&s=40" width="20" /> </a>
<a class="avatar-link tooltipped tooltipped-s" aria-label="mrDinckleman" href="/1000hz/bootstrap-validator/commits/master/dist/validator.js?author=mrDinckleman"><img alt="@mrDinckleman" class="avatar" height="20" src="https://avatars3.githubusercontent.com/u/2909337?v=3&s=40" width="20" /> </a>
<a class="avatar-link tooltipped tooltipped-s" aria-label="marten-seemann" href="/1000hz/bootstrap-validator/commits/master/dist/validator.js?author=marten-seemann"><img alt="@marten-seemann" class="avatar" height="20" src="https://avatars3.githubusercontent.com/u/1478487?v=3&s=40" width="20" /> </a>
<a class="avatar-link tooltipped tooltipped-s" aria-label="balcsida" href="/1000hz/bootstrap-validator/commits/master/dist/validator.js?author=balcsida"><img alt="@balcsida" class="avatar" height="20" src="https://avatars1.githubusercontent.com/u/1768446?v=3&s=40" width="20" /> </a>
<a class="avatar-link tooltipped tooltipped-s" aria-label="jugglebird" href="/1000hz/bootstrap-validator/commits/master/dist/validator.js?author=jugglebird"><img alt="@jugglebird" class="avatar" height="20" src="https://avatars0.githubusercontent.com/u/2484?v=3&s=40" width="20" /> </a>
</div>
<div id="blob_contributors_box" style="display:none">
<h2 class="facebox-header" data-facebox-id="facebox-header">Users who have contributed to this file</h2>
<ul class="facebox-user-list" data-facebox-id="facebox-description">
<li class="facebox-user-list-item">
<img alt="@1000hz" height="24" src="https://avatars2.githubusercontent.com/u/1395018?v=3&s=48" width="24" />
<a href="/1000hz">1000hz</a>
</li>
<li class="facebox-user-list-item">
<img alt="@mrDinckleman" height="24" src="https://avatars1.githubusercontent.com/u/2909337?v=3&s=48" width="24" />
<a href="/mrDinckleman">mrDinckleman</a>
</li>
<li class="facebox-user-list-item">
<img alt="@marten-seemann" height="24" src="https://avatars1.githubusercontent.com/u/1478487?v=3&s=48" width="24" />
<a href="/marten-seemann">marten-seemann</a>
</li>
<li class="facebox-user-list-item">
<img alt="@balcsida" height="24" src="https://avatars3.githubusercontent.com/u/1768446?v=3&s=48" width="24" />
<a href="/balcsida">balcsida</a>
</li>
<li class="facebox-user-list-item">
<img alt="@jugglebird" height="24" src="https://avatars2.githubusercontent.com/u/2484?v=3&s=48" width="24" />
<a href="/jugglebird">jugglebird</a>
</li>
</ul>
</div>
</div>
<div class="file">
<div class="file-header">
<div class="file-actions">
<div class="btn-group">
<a href="/1000hz/bootstrap-validator/raw/master/dist/validator.js" class="btn btn-sm " id="raw-url">Raw</a>
<a href="/1000hz/bootstrap-validator/blame/master/dist/validator.js" class="btn btn-sm js-update-url-with-hash">Blame</a>
<a href="/1000hz/bootstrap-validator/commits/master/dist/validator.js" class="btn btn-sm " rel="nofollow">History</a>
</div>
<a class="btn-octicon tooltipped tooltipped-nw"
href="https://windows.github.com"
aria-label="Open this file in GitHub Desktop"
data-ga-click="Repository, open with desktop, type:windows">
<svg aria-hidden="true" class="octicon octicon-device-desktop" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M15 2H1c-0.55 0-1 0.45-1 1v9c0 0.55 0.45 1 1 1h5.34c-0.25 0.61-0.86 1.39-2.34 2h8c-1.48-0.61-2.09-1.39-2.34-2h5.34c0.55 0 1-0.45 1-1V3c0-0.55-0.45-1-1-1z m0 9H1V3h14v8z"></path></svg>
</a>
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/1000hz/bootstrap-validator/edit/master/dist/validator.js" class="inline-form js-update-url-with-hash" data-form-nonce="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="zz4fr/GEMvB6zt3asP/VtK99KjIB3v3AvkjtlVQ6BfxyFiA0H/3oGytnGpdKyUx4Xl+oTHf/KfIfMRCKtYHBPg==" /></div>
<button class="btn-octicon tooltipped tooltipped-nw" type="submit"
aria-label="Fork this project and edit the file" data-hotkey="e" data-disable-with>
<svg aria-hidden="true" class="octicon octicon-pencil" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M0 12v3h3l8-8-3-3L0 12z m3 2H1V12h1v1h1v1z m10.3-9.3l-1.3 1.3-3-3 1.3-1.3c0.39-0.39 1.02-0.39 1.41 0l1.59 1.59c0.39 0.39 0.39 1.02 0 1.41z"></path></svg>
</button>
</form> <!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/1000hz/bootstrap-validator/delete/master/dist/validator.js" class="inline-form" data-form-nonce="4796631dcd9748d3ca4eed2b4fac1debc1c503a4" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="VzO0eY06YjyG8rCl6SuhvZySZImhLKIfhU18u7XrxhA/4R6IYfBztVOlH3SaKU2g2lnYlhPaOAXJZJw2S2Tfng==" /></div>
<button class="btn-octicon btn-octicon-danger tooltipped tooltipped-nw" type="submit"
aria-label="Fork this project and delete the file" data-disable-with>
<svg aria-hidden="true" class="octicon octicon-trashcan" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M10 2H8c0-0.55-0.45-1-1-1H4c-0.55 0-1 0.45-1 1H1c-0.55 0-1 0.45-1 1v1c0 0.55 0.45 1 1 1v9c0 0.55 0.45 1 1 1h7c0.55 0 1-0.45 1-1V5c0.55 0 1-0.45 1-1v-1c0-0.55-0.45-1-1-1z m-1 12H2V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9z m1-10H1v-1h9v1z"></path></svg>
</button>
</form> </div>
<div class="file-info">
341 lines (265 sloc)
<span class="file-info-divider"></span>
10.3 KB
</div>
</div>
<div itemprop="text" class="blob-wrapper data type-javascript">
<table class="highlight tab-size js-file-line-container" data-tab-size="8">
<tr>
<td id="L1" class="blob-num js-line-number" data-line-number="1"></td>
<td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-c">/*!</span></td>
</tr>
<tr>
<td id="L2" class="blob-num js-line-number" data-line-number="2"></td>
<td id="LC2" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * Validator v0.10.1 for Bootstrap 3, by @1000hz</span></td>
</tr>
<tr>
<td id="L3" class="blob-num js-line-number" data-line-number="3"></td>
<td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * Copyright 2016 Cina Saffary</span></td>
</tr>
<tr>
<td id="L4" class="blob-num js-line-number" data-line-number="4"></td>
<td id="LC4" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * Licensed under http://opensource.org/licenses/MIT</span></td>
</tr>
<tr>
<td id="L5" class="blob-num js-line-number" data-line-number="5"></td>
<td id="LC5" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> *</span></td>
</tr>
<tr>
<td id="L6" class="blob-num js-line-number" data-line-number="6"></td>
<td id="LC6" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * https://github.com/1000hz/bootstrap-validator</span></td>
</tr>
<tr>
<td id="L7" class="blob-num js-line-number" data-line-number="7"></td>
<td id="LC7" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> */</span></td>
</tr>
<tr>
<td id="L8" class="blob-num js-line-number" data-line-number="8"></td>
<td id="LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L9" class="blob-num js-line-number" data-line-number="9"></td>
<td id="LC9" class="blob-code blob-code-inner js-file-line"><span class="pl-k">+</span><span class="pl-k">function</span> (<span class="pl-smi">$</span>) {</td>
</tr>
<tr>
<td id="L10" class="blob-num js-line-number" data-line-number="10"></td>
<td id="LC10" class="blob-code blob-code-inner js-file-line"> <span class="pl-s"><span class="pl-pds">'</span>use strict<span class="pl-pds">'</span></span>;</td>
</tr>
<tr>
<td id="L11" class="blob-num js-line-number" data-line-number="11"></td>
<td id="LC11" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L12" class="blob-num js-line-number" data-line-number="12"></td>
<td id="LC12" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// VALIDATOR CLASS DEFINITION</span></td>
</tr>
<tr>
<td id="L13" class="blob-num js-line-number" data-line-number="13"></td>
<td id="LC13" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// ==========================</span></td>
</tr>
<tr>
<td id="L14" class="blob-num js-line-number" data-line-number="14"></td>
<td id="LC14" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L15" class="blob-num js-line-number" data-line-number="15"></td>
<td id="LC15" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">function</span> <span class="pl-en">getValue</span>(<span class="pl-smi">$el</span>) {</td>
</tr>
<tr>
<td id="L16" class="blob-num js-line-number" data-line-number="16"></td>
<td id="LC16" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-smi">$el</span>.<span class="pl-en">is</span>(<span class="pl-s"><span class="pl-pds">'</span>[type="checkbox"]<span class="pl-pds">'</span></span>) <span class="pl-k">?</span> <span class="pl-smi">$el</span>.<span class="pl-en">prop</span>(<span class="pl-s"><span class="pl-pds">'</span>checked<span class="pl-pds">'</span></span>) <span class="pl-k">:</span></td>
</tr>
<tr>
<td id="L17" class="blob-num js-line-number" data-line-number="17"></td>
<td id="LC17" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$el</span>.<span class="pl-en">is</span>(<span class="pl-s"><span class="pl-pds">'</span>[type="radio"]<span class="pl-pds">'</span></span>) <span class="pl-k">?</span> <span class="pl-k">!!</span><span class="pl-en">$</span>(<span class="pl-s"><span class="pl-pds">'</span>[name="<span class="pl-pds">'</span></span> <span class="pl-k">+</span> <span class="pl-smi">$el</span>.<span class="pl-en">attr</span>(<span class="pl-s"><span class="pl-pds">'</span>name<span class="pl-pds">'</span></span>) <span class="pl-k">+</span> <span class="pl-s"><span class="pl-pds">'</span>"]:checked<span class="pl-pds">'</span></span>).<span class="pl-c1">length</span> <span class="pl-k">:</span></td>
</tr>
<tr>
<td id="L18" class="blob-num js-line-number" data-line-number="18"></td>
<td id="LC18" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-en">trim</span>(<span class="pl-smi">$el</span>.<span class="pl-en">val</span>())</td>
</tr>
<tr>
<td id="L19" class="blob-num js-line-number" data-line-number="19"></td>
<td id="LC19" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L20" class="blob-num js-line-number" data-line-number="20"></td>
<td id="LC20" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L21" class="blob-num js-line-number" data-line-number="21"></td>
<td id="LC21" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> <span class="pl-en">Validator</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">element</span>, <span class="pl-smi">options</span>) {</td>
</tr>
<tr>
<td id="L22" class="blob-num js-line-number" data-line-number="22"></td>
<td id="LC22" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-c1">options</span> <span class="pl-k">=</span> options</td>
</tr>
<tr>
<td id="L23" class="blob-num js-line-number" data-line-number="23"></td>
<td id="LC23" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span> <span class="pl-k">=</span> <span class="pl-en">$</span>(element)</td>
</tr>
<tr>
<td id="L24" class="blob-num js-line-number" data-line-number="24"></td>
<td id="LC24" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$inputs</span> <span class="pl-k">=</span> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-c1">find</span>(<span class="pl-smi">Validator</span>.<span class="pl-c1">INPUT_SELECTOR</span>)</td>
</tr>
<tr>
<td id="L25" class="blob-num js-line-number" data-line-number="25"></td>
<td id="LC25" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$btn</span> <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-s"><span class="pl-pds">'</span>button[type="submit"], input[type="submit"]<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L26" class="blob-num js-line-number" data-line-number="26"></td>
<td id="LC26" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">filter</span>(<span class="pl-s"><span class="pl-pds">'</span>[form="<span class="pl-pds">'</span></span> <span class="pl-k">+</span> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-en">attr</span>(<span class="pl-s"><span class="pl-pds">'</span>id<span class="pl-pds">'</span></span>) <span class="pl-k">+</span> <span class="pl-s"><span class="pl-pds">'</span>"]<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L27" class="blob-num js-line-number" data-line-number="27"></td>
<td id="LC27" class="blob-code blob-code-inner js-file-line"> .<span class="pl-c1">add</span>(<span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>input[type="submit"], button[type="submit"]<span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L28" class="blob-num js-line-number" data-line-number="28"></td>
<td id="LC28" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L29" class="blob-num js-line-number" data-line-number="29"></td>
<td id="LC29" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">options</span>.<span class="pl-smi">errors</span> <span class="pl-k">=</span> <span class="pl-smi">$</span>.<span class="pl-en">extend</span>({}, <span class="pl-smi">Validator</span>.<span class="pl-c1">DEFAULTS</span>.<span class="pl-smi">errors</span>, <span class="pl-smi">options</span>.<span class="pl-smi">errors</span>)</td>
</tr>
<tr>
<td id="L30" class="blob-num js-line-number" data-line-number="30"></td>
<td id="LC30" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L31" class="blob-num js-line-number" data-line-number="31"></td>
<td id="LC31" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">for</span> (<span class="pl-k">var</span> custom <span class="pl-k">in</span> <span class="pl-smi">options</span>.<span class="pl-smi">custom</span>) {</td>
</tr>
<tr>
<td id="L32" class="blob-num js-line-number" data-line-number="32"></td>
<td id="LC32" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span><span class="pl-smi">options</span>.<span class="pl-smi">errors</span>[custom]) <span class="pl-k">throw</span> <span class="pl-k">new</span> <span class="pl-en">Error</span>(<span class="pl-s"><span class="pl-pds">'</span>Missing default error message for custom validator: <span class="pl-pds">'</span></span> <span class="pl-k">+</span> custom)</td>
</tr>
<tr>
<td id="L33" class="blob-num js-line-number" data-line-number="33"></td>
<td id="LC33" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L34" class="blob-num js-line-number" data-line-number="34"></td>
<td id="LC34" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L35" class="blob-num js-line-number" data-line-number="35"></td>
<td id="LC35" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-en">extend</span>(<span class="pl-smi">Validator</span>.<span class="pl-c1">VALIDATORS</span>, <span class="pl-smi">options</span>.<span class="pl-smi">custom</span>)</td>
</tr>
<tr>
<td id="L36" class="blob-num js-line-number" data-line-number="36"></td>
<td id="LC36" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L37" class="blob-num js-line-number" data-line-number="37"></td>
<td id="LC37" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-en">attr</span>(<span class="pl-s"><span class="pl-pds">'</span>novalidate<span class="pl-pds">'</span></span>, <span class="pl-c1">true</span>) <span class="pl-c">// disable automatic native validation</span></td>
</tr>
<tr>
<td id="L38" class="blob-num js-line-number" data-line-number="38"></td>
<td id="LC38" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-en">toggleSubmit</span>()</td>
</tr>
<tr>
<td id="L39" class="blob-num js-line-number" data-line-number="39"></td>
<td id="LC39" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L40" class="blob-num js-line-number" data-line-number="40"></td>
<td id="LC40" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-en">on</span>(<span class="pl-s"><span class="pl-pds">'</span>input.bs.validator change.bs.validator focusout.bs.validator<span class="pl-pds">'</span></span>, <span class="pl-smi">Validator</span>.<span class="pl-c1">INPUT_SELECTOR</span>, <span class="pl-smi">$</span>.<span class="pl-en">proxy</span>(<span class="pl-v">this</span>.<span class="pl-smi">onInput</span>, <span class="pl-v">this</span>))</td>
</tr>
<tr>
<td id="L41" class="blob-num js-line-number" data-line-number="41"></td>
<td id="LC41" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-en">on</span>(<span class="pl-s"><span class="pl-pds">'</span>submit.bs.validator<span class="pl-pds">'</span></span>, <span class="pl-smi">$</span>.<span class="pl-en">proxy</span>(<span class="pl-v">this</span>.<span class="pl-smi">onSubmit</span>, <span class="pl-v">this</span>))</td>
</tr>
<tr>
<td id="L42" class="blob-num js-line-number" data-line-number="42"></td>
<td id="LC42" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L43" class="blob-num js-line-number" data-line-number="43"></td>
<td id="LC43" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>[data-match]<span class="pl-pds">'</span></span>).<span class="pl-en">each</span>(<span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L44" class="blob-num js-line-number" data-line-number="44"></td>
<td id="LC44" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $<span class="pl-v">this</span> <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-v">this</span>)</td>
</tr>
<tr>
<td id="L45" class="blob-num js-line-number" data-line-number="45"></td>
<td id="LC45" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> target <span class="pl-k">=</span> <span class="pl-smi">$this</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>match<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L46" class="blob-num js-line-number" data-line-number="46"></td>
<td id="LC46" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L47" class="blob-num js-line-number" data-line-number="47"></td>
<td id="LC47" class="blob-code blob-code-inner js-file-line"> <span class="pl-en">$</span>(target).<span class="pl-en">on</span>(<span class="pl-s"><span class="pl-pds">'</span>input.bs.validator<span class="pl-pds">'</span></span>, <span class="pl-k">function</span> (<span class="pl-smi">e</span>) {</td>
</tr>
<tr>
<td id="L48" class="blob-num js-line-number" data-line-number="48"></td>
<td id="LC48" class="blob-code blob-code-inner js-file-line"> <span class="pl-en">getValue</span>($<span class="pl-v">this</span>) <span class="pl-k">&&</span> <span class="pl-smi">$this</span>.<span class="pl-en">trigger</span>(<span class="pl-s"><span class="pl-pds">'</span>input.bs.validator<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L49" class="blob-num js-line-number" data-line-number="49"></td>
<td id="LC49" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L50" class="blob-num js-line-number" data-line-number="50"></td>
<td id="LC50" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L51" class="blob-num js-line-number" data-line-number="51"></td>
<td id="LC51" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L52" class="blob-num js-line-number" data-line-number="52"></td>
<td id="LC52" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L53" class="blob-num js-line-number" data-line-number="53"></td>
<td id="LC53" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">INPUT_SELECTOR</span> <span class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">'</span>:input:not([type="submit"], button):enabled:visible<span class="pl-pds">'</span></span></td>
</tr>
<tr>
<td id="L54" class="blob-num js-line-number" data-line-number="54"></td>
<td id="LC54" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L55" class="blob-num js-line-number" data-line-number="55"></td>
<td id="LC55" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">FOCUS_OFFSET</span> <span class="pl-k">=</span> <span class="pl-c1">20</span></td>
</tr>
<tr>
<td id="L56" class="blob-num js-line-number" data-line-number="56"></td>
<td id="LC56" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L57" class="blob-num js-line-number" data-line-number="57"></td>
<td id="LC57" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">DEFAULTS</span> <span class="pl-k">=</span> {</td>
</tr>
<tr>
<td id="L58" class="blob-num js-line-number" data-line-number="58"></td>
<td id="LC58" class="blob-code blob-code-inner js-file-line"> delay<span class="pl-k">:</span> <span class="pl-c1">500</span>,</td>
</tr>
<tr>
<td id="L59" class="blob-num js-line-number" data-line-number="59"></td>
<td id="LC59" class="blob-code blob-code-inner js-file-line"> html<span class="pl-k">:</span> <span class="pl-c1">false</span>,</td>
</tr>
<tr>
<td id="L60" class="blob-num js-line-number" data-line-number="60"></td>
<td id="LC60" class="blob-code blob-code-inner js-file-line"> disable<span class="pl-k">:</span> <span class="pl-c1">true</span>,</td>
</tr>
<tr>
<td id="L61" class="blob-num js-line-number" data-line-number="61"></td>
<td id="LC61" class="blob-code blob-code-inner js-file-line"> focus<span class="pl-k">:</span> <span class="pl-c1">true</span>,</td>
</tr>
<tr>
<td id="L62" class="blob-num js-line-number" data-line-number="62"></td>
<td id="LC62" class="blob-code blob-code-inner js-file-line"> custom<span class="pl-k">:</span> {},</td>
</tr>
<tr>
<td id="L63" class="blob-num js-line-number" data-line-number="63"></td>
<td id="LC63" class="blob-code blob-code-inner js-file-line"> errors<span class="pl-k">:</span> {</td>
</tr>
<tr>
<td id="L64" class="blob-num js-line-number" data-line-number="64"></td>
<td id="LC64" class="blob-code blob-code-inner js-file-line"> match<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>Does not match<span class="pl-pds">'</span></span>,</td>
</tr>
<tr>
<td id="L65" class="blob-num js-line-number" data-line-number="65"></td>
<td id="LC65" class="blob-code blob-code-inner js-file-line"> minlength<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>Not long enough<span class="pl-pds">'</span></span></td>
</tr>
<tr>
<td id="L66" class="blob-num js-line-number" data-line-number="66"></td>
<td id="LC66" class="blob-code blob-code-inner js-file-line"> },</td>
</tr>
<tr>
<td id="L67" class="blob-num js-line-number" data-line-number="67"></td>
<td id="LC67" class="blob-code blob-code-inner js-file-line"> feedback<span class="pl-k">:</span> {</td>
</tr>
<tr>
<td id="L68" class="blob-num js-line-number" data-line-number="68"></td>
<td id="LC68" class="blob-code blob-code-inner js-file-line"> success<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>glyphicon-ok<span class="pl-pds">'</span></span>,</td>
</tr>
<tr>
<td id="L69" class="blob-num js-line-number" data-line-number="69"></td>
<td id="LC69" class="blob-code blob-code-inner js-file-line"> error<span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>glyphicon-remove<span class="pl-pds">'</span></span></td>
</tr>
<tr>
<td id="L70" class="blob-num js-line-number" data-line-number="70"></td>
<td id="LC70" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L71" class="blob-num js-line-number" data-line-number="71"></td>
<td id="LC71" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L72" class="blob-num js-line-number" data-line-number="72"></td>
<td id="LC72" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L73" class="blob-num js-line-number" data-line-number="73"></td>
<td id="LC73" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">VALIDATORS</span> <span class="pl-k">=</span> {</td>
</tr>
<tr>
<td id="L74" class="blob-num js-line-number" data-line-number="74"></td>
<td id="LC74" class="blob-code blob-code-inner js-file-line"> <span class="pl-s"><span class="pl-pds">'</span><span class="pl-en">native</span><span class="pl-pds">'</span></span><span class="pl-k">:</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>) {</td>
</tr>
<tr>
<td id="L75" class="blob-num js-line-number" data-line-number="75"></td>
<td id="LC75" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> el <span class="pl-k">=</span> $el[<span class="pl-c1">0</span>]</td>
</tr>
<tr>
<td id="L76" class="blob-num js-line-number" data-line-number="76"></td>
<td id="LC76" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-smi">el</span>.<span class="pl-smi">checkValidity</span> <span class="pl-k">?</span> <span class="pl-smi">el</span>.<span class="pl-en">checkValidity</span>() <span class="pl-k">:</span> <span class="pl-c1">true</span></td>
</tr>
<tr>
<td id="L77" class="blob-num js-line-number" data-line-number="77"></td>
<td id="LC77" class="blob-code blob-code-inner js-file-line"> },</td>
</tr>
<tr>
<td id="L78" class="blob-num js-line-number" data-line-number="78"></td>
<td id="LC78" class="blob-code blob-code-inner js-file-line"> <span class="pl-s"><span class="pl-pds">'</span><span class="pl-en">match</span><span class="pl-pds">'</span></span><span class="pl-k">:</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>) {</td>
</tr>
<tr>
<td id="L79" class="blob-num js-line-number" data-line-number="79"></td>
<td id="LC79" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> target <span class="pl-k">=</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>match<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L80" class="blob-num js-line-number" data-line-number="80"></td>
<td id="LC80" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-k">!</span><span class="pl-smi">$el</span>.<span class="pl-en">val</span>() <span class="pl-k">||</span> <span class="pl-smi">$el</span>.<span class="pl-en">val</span>() <span class="pl-k">===</span> <span class="pl-en">$</span>(target).<span class="pl-en">val</span>()</td>
</tr>
<tr>
<td id="L81" class="blob-num js-line-number" data-line-number="81"></td>
<td id="LC81" class="blob-code blob-code-inner js-file-line"> },</td>
</tr>
<tr>
<td id="L82" class="blob-num js-line-number" data-line-number="82"></td>
<td id="LC82" class="blob-code blob-code-inner js-file-line"> <span class="pl-s"><span class="pl-pds">'</span><span class="pl-en">minlength</span><span class="pl-pds">'</span></span><span class="pl-k">:</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>) {</td>
</tr>
<tr>
<td id="L83" class="blob-num js-line-number" data-line-number="83"></td>
<td id="LC83" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> minlength <span class="pl-k">=</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>minlength<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L84" class="blob-num js-line-number" data-line-number="84"></td>
<td id="LC84" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-k">!</span><span class="pl-smi">$el</span>.<span class="pl-en">val</span>() <span class="pl-k">||</span> <span class="pl-smi">$el</span>.<span class="pl-en">val</span>().<span class="pl-c1">length</span> <span class="pl-k">>=</span> minlength</td>
</tr>
<tr>
<td id="L85" class="blob-num js-line-number" data-line-number="85"></td>
<td id="LC85" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L86" class="blob-num js-line-number" data-line-number="86"></td>
<td id="LC86" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L87" class="blob-num js-line-number" data-line-number="87"></td>
<td id="LC87" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L88" class="blob-num js-line-number" data-line-number="88"></td>
<td id="LC88" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">onInput</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">e</span>) {</td>
</tr>
<tr>
<td id="L89" class="blob-num js-line-number" data-line-number="89"></td>
<td id="LC89" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> self <span class="pl-k">=</span> <span class="pl-v">this</span></td>
</tr>
<tr>
<td id="L90" class="blob-num js-line-number" data-line-number="90"></td>
<td id="LC90" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $el <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-smi">e</span>.<span class="pl-c1">target</span>)</td>
</tr>
<tr>
<td id="L91" class="blob-num js-line-number" data-line-number="91"></td>
<td id="LC91" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> deferErrors <span class="pl-k">=</span> <span class="pl-smi">e</span>.<span class="pl-c1">type</span> <span class="pl-k">!==</span> <span class="pl-s"><span class="pl-pds">'</span>focusout<span class="pl-pds">'</span></span></td>
</tr>
<tr>
<td id="L92" class="blob-num js-line-number" data-line-number="92"></td>
<td id="LC92" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-en">validateInput</span>($el, deferErrors).<span class="pl-en">done</span>(<span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L93" class="blob-num js-line-number" data-line-number="93"></td>
<td id="LC93" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">self</span>.<span class="pl-en">toggleSubmit</span>()</td>
</tr>
<tr>
<td id="L94" class="blob-num js-line-number" data-line-number="94"></td>
<td id="LC94" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L95" class="blob-num js-line-number" data-line-number="95"></td>
<td id="LC95" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L96" class="blob-num js-line-number" data-line-number="96"></td>
<td id="LC96" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L97" class="blob-num js-line-number" data-line-number="97"></td>
<td id="LC97" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">validateInput</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>, <span class="pl-smi">deferErrors</span>) {</td>
</tr>
<tr>
<td id="L98" class="blob-num js-line-number" data-line-number="98"></td>
<td id="LC98" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> value <span class="pl-k">=</span> <span class="pl-en">getValue</span>($el)</td>
</tr>
<tr>
<td id="L99" class="blob-num js-line-number" data-line-number="99"></td>
<td id="LC99" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> prevValue <span class="pl-k">=</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.previous<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L100" class="blob-num js-line-number" data-line-number="100"></td>
<td id="LC100" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> prevErrors <span class="pl-k">=</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.errors<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L101" class="blob-num js-line-number" data-line-number="101"></td>
<td id="LC101" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> errors</td>
</tr>
<tr>
<td id="L102" class="blob-num js-line-number" data-line-number="102"></td>
<td id="LC102" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L103" class="blob-num js-line-number" data-line-number="103"></td>
<td id="LC103" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (prevValue <span class="pl-k">===</span> value) <span class="pl-k">return</span> <span class="pl-smi">$</span>.<span class="pl-en">Deferred</span>().<span class="pl-en">resolve</span>()</td>
</tr>
<tr>
<td id="L104" class="blob-num js-line-number" data-line-number="104"></td>
<td id="LC104" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">else</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.previous<span class="pl-pds">'</span></span>, value)</td>
</tr>
<tr>
<td id="L105" class="blob-num js-line-number" data-line-number="105"></td>
<td id="LC105" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L106" class="blob-num js-line-number" data-line-number="106"></td>
<td id="LC106" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-smi">$el</span>.<span class="pl-en">is</span>(<span class="pl-s"><span class="pl-pds">'</span>[type="radio"]<span class="pl-pds">'</span></span>)) $el <span class="pl-k">=</span> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>input[name="<span class="pl-pds">'</span></span> <span class="pl-k">+</span> <span class="pl-smi">$el</span>.<span class="pl-en">attr</span>(<span class="pl-s"><span class="pl-pds">'</span>name<span class="pl-pds">'</span></span>) <span class="pl-k">+</span> <span class="pl-s"><span class="pl-pds">'</span>"]<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L107" class="blob-num js-line-number" data-line-number="107"></td>
<td id="LC107" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L108" class="blob-num js-line-number" data-line-number="108"></td>
<td id="LC108" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> e <span class="pl-k">=</span> <span class="pl-smi">$</span>.<span class="pl-en">Event</span>(<span class="pl-s"><span class="pl-pds">'</span>validate.bs.validator<span class="pl-pds">'</span></span>, {relatedTarget<span class="pl-k">:</span> $el[<span class="pl-c1">0</span>]})</td>
</tr>
<tr>
<td id="L109" class="blob-num js-line-number" data-line-number="109"></td>
<td id="LC109" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-en">trigger</span>(e)</td>
</tr>
<tr>
<td id="L110" class="blob-num js-line-number" data-line-number="110"></td>
<td id="LC110" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-smi">e</span>.<span class="pl-en">isDefaultPrevented</span>()) <span class="pl-k">return</span></td>
</tr>
<tr>
<td id="L111" class="blob-num js-line-number" data-line-number="111"></td>
<td id="LC111" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L112" class="blob-num js-line-number" data-line-number="112"></td>
<td id="LC112" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> self <span class="pl-k">=</span> <span class="pl-v">this</span></td>
</tr>
<tr>
<td id="L113" class="blob-num js-line-number" data-line-number="113"></td>
<td id="LC113" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L114" class="blob-num js-line-number" data-line-number="114"></td>
<td id="LC114" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-v">this</span>.<span class="pl-en">runValidators</span>($el).<span class="pl-en">done</span>(<span class="pl-k">function</span> (<span class="pl-smi">errors</span>) {</td>
</tr>
<tr>
<td id="L115" class="blob-num js-line-number" data-line-number="115"></td>
<td id="LC115" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.errors<span class="pl-pds">'</span></span>, errors)</td>
</tr>
<tr>
<td id="L116" class="blob-num js-line-number" data-line-number="116"></td>
<td id="LC116" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L117" class="blob-num js-line-number" data-line-number="117"></td>
<td id="LC117" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">errors</span>.<span class="pl-c1">length</span></td>
</tr>
<tr>
<td id="L118" class="blob-num js-line-number" data-line-number="118"></td>
<td id="LC118" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">?</span> deferErrors <span class="pl-k">?</span> <span class="pl-smi">self</span>.<span class="pl-c1">defer</span>($el, <span class="pl-smi">self</span>.<span class="pl-smi">showErrors</span>) <span class="pl-k">:</span> <span class="pl-smi">self</span>.<span class="pl-en">showErrors</span>($el)</td>
</tr>
<tr>
<td id="L119" class="blob-num js-line-number" data-line-number="119"></td>
<td id="LC119" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">:</span> <span class="pl-smi">self</span>.<span class="pl-en">clearErrors</span>($el)</td>
</tr>
<tr>
<td id="L120" class="blob-num js-line-number" data-line-number="120"></td>
<td id="LC120" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L121" class="blob-num js-line-number" data-line-number="121"></td>
<td id="LC121" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span>prevErrors <span class="pl-k">||</span> <span class="pl-smi">errors</span>.<span class="pl-c1">toString</span>() <span class="pl-k">!==</span> <span class="pl-smi">prevErrors</span>.<span class="pl-c1">toString</span>()) {</td>
</tr>
<tr>
<td id="L122" class="blob-num js-line-number" data-line-number="122"></td>
<td id="LC122" class="blob-code blob-code-inner js-file-line"> e <span class="pl-k">=</span> <span class="pl-smi">errors</span>.<span class="pl-c1">length</span></td>
</tr>
<tr>
<td id="L123" class="blob-num js-line-number" data-line-number="123"></td>
<td id="LC123" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">?</span> <span class="pl-smi">$</span>.<span class="pl-en">Event</span>(<span class="pl-s"><span class="pl-pds">'</span>invalid.bs.validator<span class="pl-pds">'</span></span>, {relatedTarget<span class="pl-k">:</span> $el[<span class="pl-c1">0</span>], detail<span class="pl-k">:</span> errors})</td>
</tr>
<tr>
<td id="L124" class="blob-num js-line-number" data-line-number="124"></td>
<td id="LC124" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">:</span> <span class="pl-smi">$</span>.<span class="pl-en">Event</span>(<span class="pl-s"><span class="pl-pds">'</span>valid.bs.validator<span class="pl-pds">'</span></span>, {relatedTarget<span class="pl-k">:</span> $el[<span class="pl-c1">0</span>], detail<span class="pl-k">:</span> prevErrors})</td>
</tr>
<tr>
<td id="L125" class="blob-num js-line-number" data-line-number="125"></td>
<td id="LC125" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L126" class="blob-num js-line-number" data-line-number="126"></td>
<td id="LC126" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">self</span>.<span class="pl-smi">$element</span>.<span class="pl-en">trigger</span>(e)</td>
</tr>
<tr>
<td id="L127" class="blob-num js-line-number" data-line-number="127"></td>
<td id="LC127" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L128" class="blob-num js-line-number" data-line-number="128"></td>
<td id="LC128" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L129" class="blob-num js-line-number" data-line-number="129"></td>
<td id="LC129" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">self</span>.<span class="pl-en">toggleSubmit</span>()</td>
</tr>
<tr>
<td id="L130" class="blob-num js-line-number" data-line-number="130"></td>
<td id="LC130" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L131" class="blob-num js-line-number" data-line-number="131"></td>
<td id="LC131" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">self</span>.<span class="pl-smi">$element</span>.<span class="pl-en">trigger</span>(<span class="pl-smi">$</span>.<span class="pl-en">Event</span>(<span class="pl-s"><span class="pl-pds">'</span>validated.bs.validator<span class="pl-pds">'</span></span>, {relatedTarget<span class="pl-k">:</span> $el[<span class="pl-c1">0</span>]}))</td>
</tr>
<tr>
<td id="L132" class="blob-num js-line-number" data-line-number="132"></td>
<td id="LC132" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L133" class="blob-num js-line-number" data-line-number="133"></td>
<td id="LC133" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L134" class="blob-num js-line-number" data-line-number="134"></td>
<td id="LC134" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L135" class="blob-num js-line-number" data-line-number="135"></td>
<td id="LC135" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L136" class="blob-num js-line-number" data-line-number="136"></td>
<td id="LC136" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">runValidators</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>) {</td>
</tr>
<tr>
<td id="L137" class="blob-num js-line-number" data-line-number="137"></td>
<td id="LC137" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> errors <span class="pl-k">=</span> []</td>
</tr>
<tr>
<td id="L138" class="blob-num js-line-number" data-line-number="138"></td>
<td id="LC138" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> deferred <span class="pl-k">=</span> <span class="pl-smi">$</span>.<span class="pl-en">Deferred</span>()</td>
</tr>
<tr>
<td id="L139" class="blob-num js-line-number" data-line-number="139"></td>
<td id="LC139" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> options <span class="pl-k">=</span> <span class="pl-v">this</span>.<span class="pl-c1">options</span></td>
</tr>
<tr>
<td id="L140" class="blob-num js-line-number" data-line-number="140"></td>
<td id="LC140" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L141" class="blob-num js-line-number" data-line-number="141"></td>
<td id="LC141" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.deferred<span class="pl-pds">'</span></span>) <span class="pl-k">&&</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.deferred<span class="pl-pds">'</span></span>).<span class="pl-en">reject</span>()</td>
</tr>
<tr>
<td id="L142" class="blob-num js-line-number" data-line-number="142"></td>
<td id="LC142" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.deferred<span class="pl-pds">'</span></span>, deferred)</td>
</tr>
<tr>
<td id="L143" class="blob-num js-line-number" data-line-number="143"></td>
<td id="LC143" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L144" class="blob-num js-line-number" data-line-number="144"></td>
<td id="LC144" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">function</span> <span class="pl-en">getErrorMessage</span>(<span class="pl-smi">key</span>) {</td>
</tr>
<tr>
<td id="L145" class="blob-num js-line-number" data-line-number="145"></td>
<td id="LC145" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(key <span class="pl-k">+</span> <span class="pl-s"><span class="pl-pds">'</span>-error<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L146" class="blob-num js-line-number" data-line-number="146"></td>
<td id="LC146" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">||</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>error<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L147" class="blob-num js-line-number" data-line-number="147"></td>
<td id="LC147" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">||</span> key <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">'</span>native<span class="pl-pds">'</span></span> <span class="pl-k">&&</span> $el[<span class="pl-c1">0</span>].<span class="pl-smi">validationMessage</span></td>
</tr>
<tr>
<td id="L148" class="blob-num js-line-number" data-line-number="148"></td>
<td id="LC148" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">||</span> <span class="pl-smi">options</span>.<span class="pl-smi">errors</span>[key]</td>
</tr>
<tr>
<td id="L149" class="blob-num js-line-number" data-line-number="149"></td>
<td id="LC149" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L150" class="blob-num js-line-number" data-line-number="150"></td>
<td id="LC150" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L151" class="blob-num js-line-number" data-line-number="151"></td>
<td id="LC151" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-en">each</span>(<span class="pl-smi">Validator</span>.<span class="pl-c1">VALIDATORS</span>, <span class="pl-smi">$</span>.<span class="pl-en">proxy</span>(<span class="pl-k">function</span> (<span class="pl-smi">key</span>, <span class="pl-smi">validator</span>) {</td>
</tr>
<tr>
<td id="L152" class="blob-num js-line-number" data-line-number="152"></td>
<td id="LC152" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> ((<span class="pl-en">getValue</span>($el) <span class="pl-k">||</span> <span class="pl-smi">$el</span>.<span class="pl-en">attr</span>(<span class="pl-s"><span class="pl-pds">'</span>required<span class="pl-pds">'</span></span>)) <span class="pl-k">&&</span></td>
</tr>
<tr>
<td id="L153" class="blob-num js-line-number" data-line-number="153"></td>
<td id="LC153" class="blob-code blob-code-inner js-file-line"> (<span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(key) <span class="pl-k">||</span> key <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">'</span>native<span class="pl-pds">'</span></span>) <span class="pl-k">&&</span></td>
</tr>
<tr>
<td id="L154" class="blob-num js-line-number" data-line-number="154"></td>
<td id="LC154" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">!</span><span class="pl-smi">validator</span>.<span class="pl-c1">call</span>(<span class="pl-v">this</span>, $el)) {</td>
</tr>
<tr>
<td id="L155" class="blob-num js-line-number" data-line-number="155"></td>
<td id="LC155" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> error <span class="pl-k">=</span> <span class="pl-en">getErrorMessage</span>(key)</td>
</tr>
<tr>
<td id="L156" class="blob-num js-line-number" data-line-number="156"></td>
<td id="LC156" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">!</span><span class="pl-k">~</span><span class="pl-smi">errors</span>.<span class="pl-c1">indexOf</span>(error) <span class="pl-k">&&</span> <span class="pl-smi">errors</span>.<span class="pl-c1">push</span>(error)</td>
</tr>
<tr>
<td id="L157" class="blob-num js-line-number" data-line-number="157"></td>
<td id="LC157" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L158" class="blob-num js-line-number" data-line-number="158"></td>
<td id="LC158" class="blob-code blob-code-inner js-file-line"> }, <span class="pl-v">this</span>))</td>
</tr>
<tr>
<td id="L159" class="blob-num js-line-number" data-line-number="159"></td>
<td id="LC159" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L160" class="blob-num js-line-number" data-line-number="160"></td>
<td id="LC160" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span><span class="pl-smi">errors</span>.<span class="pl-c1">length</span> <span class="pl-k">&&</span> <span class="pl-en">getValue</span>($el) <span class="pl-k">&&</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>remote<span class="pl-pds">'</span></span>)) {</td>
</tr>
<tr>
<td id="L161" class="blob-num js-line-number" data-line-number="161"></td>
<td id="LC161" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-c1">defer</span>($el, <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L162" class="blob-num js-line-number" data-line-number="162"></td>
<td id="LC162" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> data <span class="pl-k">=</span> {}</td>
</tr>
<tr>
<td id="L163" class="blob-num js-line-number" data-line-number="163"></td>
<td id="LC163" class="blob-code blob-code-inner js-file-line"> data[<span class="pl-smi">$el</span>.<span class="pl-en">attr</span>(<span class="pl-s"><span class="pl-pds">'</span>name<span class="pl-pds">'</span></span>)] <span class="pl-k">=</span> <span class="pl-en">getValue</span>($el)</td>
</tr>
<tr>
<td id="L164" class="blob-num js-line-number" data-line-number="164"></td>
<td id="LC164" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-en">get</span>(<span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>remote<span class="pl-pds">'</span></span>), data)</td>
</tr>
<tr>
<td id="L165" class="blob-num js-line-number" data-line-number="165"></td>
<td id="LC165" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">fail</span>(<span class="pl-k">function</span> (<span class="pl-smi">jqXHR</span>, <span class="pl-smi">textStatus</span>, <span class="pl-smi">error</span>) { <span class="pl-smi">errors</span>.<span class="pl-c1">push</span>(<span class="pl-en">getErrorMessage</span>(<span class="pl-s"><span class="pl-pds">'</span>remote<span class="pl-pds">'</span></span>) <span class="pl-k">||</span> error) })</td>
</tr>
<tr>
<td id="L166" class="blob-num js-line-number" data-line-number="166"></td>
<td id="LC166" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">always</span>(<span class="pl-k">function</span> () { <span class="pl-smi">deferred</span>.<span class="pl-en">resolve</span>(errors)})</td>
</tr>
<tr>
<td id="L167" class="blob-num js-line-number" data-line-number="167"></td>
<td id="LC167" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L168" class="blob-num js-line-number" data-line-number="168"></td>
<td id="LC168" class="blob-code blob-code-inner js-file-line"> } <span class="pl-k">else</span> <span class="pl-smi">deferred</span>.<span class="pl-en">resolve</span>(errors)</td>
</tr>
<tr>
<td id="L169" class="blob-num js-line-number" data-line-number="169"></td>
<td id="LC169" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L170" class="blob-num js-line-number" data-line-number="170"></td>
<td id="LC170" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-smi">deferred</span>.<span class="pl-en">promise</span>()</td>
</tr>
<tr>
<td id="L171" class="blob-num js-line-number" data-line-number="171"></td>
<td id="LC171" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L172" class="blob-num js-line-number" data-line-number="172"></td>
<td id="LC172" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L173" class="blob-num js-line-number" data-line-number="173"></td>
<td id="LC173" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">validate</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L174" class="blob-num js-line-number" data-line-number="174"></td>
<td id="LC174" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> self <span class="pl-k">=</span> <span class="pl-v">this</span></td>
</tr>
<tr>
<td id="L175" class="blob-num js-line-number" data-line-number="175"></td>
<td id="LC175" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L176" class="blob-num js-line-number" data-line-number="176"></td>
<td id="LC176" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-en">when</span>(<span class="pl-v">this</span>.<span class="pl-smi">$inputs</span>.<span class="pl-en">map</span>(<span class="pl-k">function</span> (<span class="pl-smi">el</span>) {</td>
</tr>
<tr>
<td id="L177" class="blob-num js-line-number" data-line-number="177"></td>
<td id="LC177" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-smi">self</span>.<span class="pl-en">validateInput</span>(<span class="pl-en">$</span>(<span class="pl-v">this</span>), <span class="pl-c1">false</span>)</td>
</tr>
<tr>
<td id="L178" class="blob-num js-line-number" data-line-number="178"></td>
<td id="LC178" class="blob-code blob-code-inner js-file-line"> })).<span class="pl-en">then</span>(<span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L179" class="blob-num js-line-number" data-line-number="179"></td>
<td id="LC179" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">self</span>.<span class="pl-en">toggleSubmit</span>()</td>
</tr>
<tr>
<td id="L180" class="blob-num js-line-number" data-line-number="180"></td>
<td id="LC180" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-smi">self</span>.<span class="pl-smi">$btn</span>.<span class="pl-en">hasClass</span>(<span class="pl-s"><span class="pl-pds">'</span>disabled<span class="pl-pds">'</span></span>)) <span class="pl-smi">self</span>.<span class="pl-en">focusError</span>()</td>
</tr>
<tr>
<td id="L181" class="blob-num js-line-number" data-line-number="181"></td>
<td id="LC181" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L182" class="blob-num js-line-number" data-line-number="182"></td>
<td id="LC182" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L183" class="blob-num js-line-number" data-line-number="183"></td>
<td id="LC183" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-v">this</span></td>
</tr>
<tr>
<td id="L184" class="blob-num js-line-number" data-line-number="184"></td>
<td id="LC184" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L185" class="blob-num js-line-number" data-line-number="185"></td>
<td id="LC185" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L186" class="blob-num js-line-number" data-line-number="186"></td>
<td id="LC186" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">focusError</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L187" class="blob-num js-line-number" data-line-number="187"></td>
<td id="LC187" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span><span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">focus</span>) <span class="pl-k">return</span></td>
</tr>
<tr>
<td id="L188" class="blob-num js-line-number" data-line-number="188"></td>
<td id="LC188" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L189" class="blob-num js-line-number" data-line-number="189"></td>
<td id="LC189" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $input <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-s"><span class="pl-pds">"</span>.has-error:first :input<span class="pl-pds">"</span></span>)</td>
</tr>
<tr>
<td id="L190" class="blob-num js-line-number" data-line-number="190"></td>
<td id="LC190" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L191" class="blob-num js-line-number" data-line-number="191"></td>
<td id="LC191" class="blob-code blob-code-inner js-file-line"> <span class="pl-en">$</span>(<span class="pl-c1">document</span>.<span class="pl-c1">body</span>).<span class="pl-en">animate</span>({scrollTop<span class="pl-k">:</span> <span class="pl-smi">$input</span>.<span class="pl-en">offset</span>().<span class="pl-c1">top</span> <span class="pl-k">-</span> <span class="pl-smi">Validator</span>.<span class="pl-c1">FOCUS_OFFSET</span>}, <span class="pl-c1">250</span>)</td>
</tr>
<tr>
<td id="L192" class="blob-num js-line-number" data-line-number="192"></td>
<td id="LC192" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$input</span>.<span class="pl-c1">focus</span>()</td>
</tr>
<tr>
<td id="L193" class="blob-num js-line-number" data-line-number="193"></td>
<td id="LC193" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L194" class="blob-num js-line-number" data-line-number="194"></td>
<td id="LC194" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L195" class="blob-num js-line-number" data-line-number="195"></td>
<td id="LC195" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">showErrors</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>) {</td>
</tr>
<tr>
<td id="L196" class="blob-num js-line-number" data-line-number="196"></td>
<td id="LC196" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> method <span class="pl-k">=</span> <span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">html</span> <span class="pl-k">?</span> <span class="pl-s"><span class="pl-pds">'</span>html<span class="pl-pds">'</span></span> <span class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>text<span class="pl-pds">'</span></span></td>
</tr>
<tr>
<td id="L197" class="blob-num js-line-number" data-line-number="197"></td>
<td id="LC197" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> errors <span class="pl-k">=</span> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.errors<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L198" class="blob-num js-line-number" data-line-number="198"></td>
<td id="LC198" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $group <span class="pl-k">=</span> <span class="pl-smi">$el</span>.<span class="pl-en">closest</span>(<span class="pl-s"><span class="pl-pds">'</span>.form-group<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L199" class="blob-num js-line-number" data-line-number="199"></td>
<td id="LC199" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $block <span class="pl-k">=</span> <span class="pl-smi">$group</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>.help-block.with-errors<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L200" class="blob-num js-line-number" data-line-number="200"></td>
<td id="LC200" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $feedback <span class="pl-k">=</span> <span class="pl-smi">$group</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>.form-control-feedback<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L201" class="blob-num js-line-number" data-line-number="201"></td>
<td id="LC201" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L202" class="blob-num js-line-number" data-line-number="202"></td>
<td id="LC202" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span><span class="pl-smi">errors</span>.<span class="pl-c1">length</span>) <span class="pl-k">return</span></td>
</tr>
<tr>
<td id="L203" class="blob-num js-line-number" data-line-number="203"></td>
<td id="LC203" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L204" class="blob-num js-line-number" data-line-number="204"></td>
<td id="LC204" class="blob-code blob-code-inner js-file-line"> errors <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-s"><span class="pl-pds">'</span><ul/><span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L205" class="blob-num js-line-number" data-line-number="205"></td>
<td id="LC205" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">addClass</span>(<span class="pl-s"><span class="pl-pds">'</span>list-unstyled<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L206" class="blob-num js-line-number" data-line-number="206"></td>
<td id="LC206" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">append</span>(<span class="pl-smi">$</span>.<span class="pl-en">map</span>(errors, <span class="pl-k">function</span> (<span class="pl-smi">error</span>) { <span class="pl-k">return</span> <span class="pl-en">$</span>(<span class="pl-s"><span class="pl-pds">'</span><li/><span class="pl-pds">'</span></span>)[method](error) }))</td>
</tr>
<tr>
<td id="L207" class="blob-num js-line-number" data-line-number="207"></td>
<td id="LC207" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L208" class="blob-num js-line-number" data-line-number="208"></td>
<td id="LC208" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$block</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.originalContent<span class="pl-pds">'</span></span>) <span class="pl-k">===</span> <span class="pl-c1">undefined</span> <span class="pl-k">&&</span> <span class="pl-smi">$block</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.originalContent<span class="pl-pds">'</span></span>, <span class="pl-smi">$block</span>.<span class="pl-en">html</span>())</td>
</tr>
<tr>
<td id="L209" class="blob-num js-line-number" data-line-number="209"></td>
<td id="LC209" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$block</span>.<span class="pl-en">empty</span>().<span class="pl-en">append</span>(errors)</td>
</tr>
<tr>
<td id="L210" class="blob-num js-line-number" data-line-number="210"></td>
<td id="LC210" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$group</span>.<span class="pl-en">addClass</span>(<span class="pl-s"><span class="pl-pds">'</span>has-error has-danger<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L211" class="blob-num js-line-number" data-line-number="211"></td>
<td id="LC211" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L212" class="blob-num js-line-number" data-line-number="212"></td>
<td id="LC212" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$group</span>.<span class="pl-en">hasClass</span>(<span class="pl-s"><span class="pl-pds">'</span>has-feedback<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L213" class="blob-num js-line-number" data-line-number="213"></td>
<td id="LC213" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">&&</span> <span class="pl-smi">$feedback</span>.<span class="pl-en">removeClass</span>(<span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">feedback</span>.<span class="pl-smi">success</span>)</td>
</tr>
<tr>
<td id="L214" class="blob-num js-line-number" data-line-number="214"></td>
<td id="LC214" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">&&</span> <span class="pl-smi">$feedback</span>.<span class="pl-en">addClass</span>(<span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">feedback</span>.<span class="pl-smi">error</span>)</td>
</tr>
<tr>
<td id="L215" class="blob-num js-line-number" data-line-number="215"></td>
<td id="LC215" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">&&</span> <span class="pl-smi">$group</span>.<span class="pl-en">removeClass</span>(<span class="pl-s"><span class="pl-pds">'</span>has-success<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L216" class="blob-num js-line-number" data-line-number="216"></td>
<td id="LC216" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L217" class="blob-num js-line-number" data-line-number="217"></td>
<td id="LC217" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L218" class="blob-num js-line-number" data-line-number="218"></td>
<td id="LC218" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">clearErrors</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>) {</td>
</tr>
<tr>
<td id="L219" class="blob-num js-line-number" data-line-number="219"></td>
<td id="LC219" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $group <span class="pl-k">=</span> <span class="pl-smi">$el</span>.<span class="pl-en">closest</span>(<span class="pl-s"><span class="pl-pds">'</span>.form-group<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L220" class="blob-num js-line-number" data-line-number="220"></td>
<td id="LC220" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $block <span class="pl-k">=</span> <span class="pl-smi">$group</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>.help-block.with-errors<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L221" class="blob-num js-line-number" data-line-number="221"></td>
<td id="LC221" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $feedback <span class="pl-k">=</span> <span class="pl-smi">$group</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>.form-control-feedback<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L222" class="blob-num js-line-number" data-line-number="222"></td>
<td id="LC222" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L223" class="blob-num js-line-number" data-line-number="223"></td>
<td id="LC223" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$block</span>.<span class="pl-en">html</span>(<span class="pl-smi">$block</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.originalContent<span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L224" class="blob-num js-line-number" data-line-number="224"></td>
<td id="LC224" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$group</span>.<span class="pl-en">removeClass</span>(<span class="pl-s"><span class="pl-pds">'</span>has-error has-danger<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L225" class="blob-num js-line-number" data-line-number="225"></td>
<td id="LC225" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L226" class="blob-num js-line-number" data-line-number="226"></td>
<td id="LC226" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$group</span>.<span class="pl-en">hasClass</span>(<span class="pl-s"><span class="pl-pds">'</span>has-feedback<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L227" class="blob-num js-line-number" data-line-number="227"></td>
<td id="LC227" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">&&</span> <span class="pl-smi">$feedback</span>.<span class="pl-en">removeClass</span>(<span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">feedback</span>.<span class="pl-smi">error</span>)</td>
</tr>
<tr>
<td id="L228" class="blob-num js-line-number" data-line-number="228"></td>
<td id="LC228" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">&&</span> <span class="pl-en">getValue</span>($el)</td>
</tr>
<tr>
<td id="L229" class="blob-num js-line-number" data-line-number="229"></td>
<td id="LC229" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">&&</span> <span class="pl-smi">$feedback</span>.<span class="pl-en">addClass</span>(<span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">feedback</span>.<span class="pl-smi">success</span>)</td>
</tr>
<tr>
<td id="L230" class="blob-num js-line-number" data-line-number="230"></td>
<td id="LC230" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">&&</span> <span class="pl-smi">$group</span>.<span class="pl-en">addClass</span>(<span class="pl-s"><span class="pl-pds">'</span>has-success<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L231" class="blob-num js-line-number" data-line-number="231"></td>
<td id="LC231" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L232" class="blob-num js-line-number" data-line-number="232"></td>
<td id="LC232" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L233" class="blob-num js-line-number" data-line-number="233"></td>
<td id="LC233" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">hasErrors</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L234" class="blob-num js-line-number" data-line-number="234"></td>
<td id="LC234" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">function</span> <span class="pl-en">fieldErrors</span>() {</td>
</tr>
<tr>
<td id="L235" class="blob-num js-line-number" data-line-number="235"></td>
<td id="LC235" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-k">!!</span>(<span class="pl-en">$</span>(<span class="pl-v">this</span>).<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.errors<span class="pl-pds">'</span></span>) <span class="pl-k">||</span> []).<span class="pl-c1">length</span></td>
</tr>
<tr>
<td id="L236" class="blob-num js-line-number" data-line-number="236"></td>
<td id="LC236" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L237" class="blob-num js-line-number" data-line-number="237"></td>
<td id="LC237" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L238" class="blob-num js-line-number" data-line-number="238"></td>
<td id="LC238" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-k">!!</span><span class="pl-v">this</span>.<span class="pl-smi">$inputs</span>.<span class="pl-en">filter</span>(fieldErrors).<span class="pl-c1">length</span></td>
</tr>
<tr>
<td id="L239" class="blob-num js-line-number" data-line-number="239"></td>
<td id="LC239" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L240" class="blob-num js-line-number" data-line-number="240"></td>
<td id="LC240" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L241" class="blob-num js-line-number" data-line-number="241"></td>
<td id="LC241" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">isIncomplete</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L242" class="blob-num js-line-number" data-line-number="242"></td>
<td id="LC242" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">function</span> <span class="pl-en">fieldIncomplete</span>() {</td>
</tr>
<tr>
<td id="L243" class="blob-num js-line-number" data-line-number="243"></td>
<td id="LC243" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-k">!</span><span class="pl-en">getValue</span>(<span class="pl-en">$</span>(<span class="pl-v">this</span>))</td>
</tr>
<tr>
<td id="L244" class="blob-num js-line-number" data-line-number="244"></td>
<td id="LC244" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L245" class="blob-num js-line-number" data-line-number="245"></td>
<td id="LC245" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L246" class="blob-num js-line-number" data-line-number="246"></td>
<td id="LC246" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-k">!!</span><span class="pl-v">this</span>.<span class="pl-smi">$inputs</span>.<span class="pl-en">filter</span>(<span class="pl-s"><span class="pl-pds">'</span>[required]<span class="pl-pds">'</span></span>).<span class="pl-en">filter</span>(fieldIncomplete).<span class="pl-c1">length</span></td>
</tr>
<tr>
<td id="L247" class="blob-num js-line-number" data-line-number="247"></td>
<td id="LC247" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L248" class="blob-num js-line-number" data-line-number="248"></td>
<td id="LC248" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L249" class="blob-num js-line-number" data-line-number="249"></td>
<td id="LC249" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">onSubmit</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">e</span>) {</td>
</tr>
<tr>
<td id="L250" class="blob-num js-line-number" data-line-number="250"></td>
<td id="LC250" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-en">validate</span>()</td>
</tr>
<tr>
<td id="L251" class="blob-num js-line-number" data-line-number="251"></td>
<td id="LC251" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-v">this</span>.<span class="pl-smi">$btn</span>.<span class="pl-en">hasClass</span>(<span class="pl-s"><span class="pl-pds">'</span>disabled<span class="pl-pds">'</span></span>)) <span class="pl-smi">e</span>.<span class="pl-en">preventDefault</span>()</td>
</tr>
<tr>
<td id="L252" class="blob-num js-line-number" data-line-number="252"></td>
<td id="LC252" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L253" class="blob-num js-line-number" data-line-number="253"></td>
<td id="LC253" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L254" class="blob-num js-line-number" data-line-number="254"></td>
<td id="LC254" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">toggleSubmit</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L255" class="blob-num js-line-number" data-line-number="255"></td>
<td id="LC255" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span>(<span class="pl-k">!</span><span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">disable</span>) <span class="pl-k">return</span></td>
</tr>
<tr>
<td id="L256" class="blob-num js-line-number" data-line-number="256"></td>
<td id="LC256" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$btn</span>.<span class="pl-en">toggleClass</span>(<span class="pl-s"><span class="pl-pds">'</span>disabled<span class="pl-pds">'</span></span>, <span class="pl-v">this</span>.<span class="pl-en">isIncomplete</span>() <span class="pl-k">||</span> <span class="pl-v">this</span>.<span class="pl-en">hasErrors</span>())</td>
</tr>
<tr>
<td id="L257" class="blob-num js-line-number" data-line-number="257"></td>
<td id="LC257" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L258" class="blob-num js-line-number" data-line-number="258"></td>
<td id="LC258" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L259" class="blob-num js-line-number" data-line-number="259"></td>
<td id="LC259" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">defer</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span class="pl-smi">$el</span>, <span class="pl-smi">callback</span>) {</td>
</tr>
<tr>
<td id="L260" class="blob-num js-line-number" data-line-number="260"></td>
<td id="LC260" class="blob-code blob-code-inner js-file-line"> callback <span class="pl-k">=</span> <span class="pl-smi">$</span>.<span class="pl-en">proxy</span>(callback, <span class="pl-v">this</span>, $el)</td>
</tr>
<tr>
<td id="L261" class="blob-num js-line-number" data-line-number="261"></td>
<td id="LC261" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span><span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">delay</span>) <span class="pl-k">return</span> <span class="pl-en">callback</span>()</td>
</tr>
<tr>
<td id="L262" class="blob-num js-line-number" data-line-number="262"></td>
<td id="LC262" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">window</span>.<span class="pl-en">clearTimeout</span>(<span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.timeout<span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L263" class="blob-num js-line-number" data-line-number="263"></td>
<td id="LC263" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$el</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.timeout<span class="pl-pds">'</span></span>, <span class="pl-c1">window</span>.<span class="pl-en">setTimeout</span>(callback, <span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">delay</span>))</td>
</tr>
<tr>
<td id="L264" class="blob-num js-line-number" data-line-number="264"></td>
<td id="LC264" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L265" class="blob-num js-line-number" data-line-number="265"></td>
<td id="LC265" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L266" class="blob-num js-line-number" data-line-number="266"></td>
<td id="LC266" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">Validator</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">destroy</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L267" class="blob-num js-line-number" data-line-number="267"></td>
<td id="LC267" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span></td>
</tr>
<tr>
<td id="L268" class="blob-num js-line-number" data-line-number="268"></td>
<td id="LC268" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">removeAttr</span>(<span class="pl-s"><span class="pl-pds">'</span>novalidate<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L269" class="blob-num js-line-number" data-line-number="269"></td>
<td id="LC269" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">removeData</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L270" class="blob-num js-line-number" data-line-number="270"></td>
<td id="LC270" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">off</span>(<span class="pl-s"><span class="pl-pds">'</span>.bs.validator<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L271" class="blob-num js-line-number" data-line-number="271"></td>
<td id="LC271" class="blob-code blob-code-inner js-file-line"> .<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>.form-control-feedback<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L272" class="blob-num js-line-number" data-line-number="272"></td>
<td id="LC272" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">removeClass</span>([<span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">feedback</span>.<span class="pl-smi">error</span>, <span class="pl-v">this</span>.<span class="pl-c1">options</span>.<span class="pl-smi">feedback</span>.<span class="pl-smi">success</span>].<span class="pl-c1">join</span>(<span class="pl-s"><span class="pl-pds">'</span> <span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L273" class="blob-num js-line-number" data-line-number="273"></td>
<td id="LC273" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L274" class="blob-num js-line-number" data-line-number="274"></td>
<td id="LC274" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$inputs</span></td>
</tr>
<tr>
<td id="L275" class="blob-num js-line-number" data-line-number="275"></td>
<td id="LC275" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">off</span>(<span class="pl-s"><span class="pl-pds">'</span>.bs.validator<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L276" class="blob-num js-line-number" data-line-number="276"></td>
<td id="LC276" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">removeData</span>([<span class="pl-s"><span class="pl-pds">'</span>bs.validator.errors<span class="pl-pds">'</span></span>, <span class="pl-s"><span class="pl-pds">'</span>bs.validator.deferred<span class="pl-pds">'</span></span>, <span class="pl-s"><span class="pl-pds">'</span>bs.validator.previous<span class="pl-pds">'</span></span>])</td>
</tr>
<tr>
<td id="L277" class="blob-num js-line-number" data-line-number="277"></td>
<td id="LC277" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">each</span>(<span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L278" class="blob-num js-line-number" data-line-number="278"></td>
<td id="LC278" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $<span class="pl-v">this</span> <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-v">this</span>)</td>
</tr>
<tr>
<td id="L279" class="blob-num js-line-number" data-line-number="279"></td>
<td id="LC279" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> timeout <span class="pl-k">=</span> <span class="pl-smi">$this</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.timeout<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L280" class="blob-num js-line-number" data-line-number="280"></td>
<td id="LC280" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">window</span>.<span class="pl-en">clearTimeout</span>(timeout) <span class="pl-k">&&</span> <span class="pl-smi">$this</span>.<span class="pl-en">removeData</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.timeout<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L281" class="blob-num js-line-number" data-line-number="281"></td>
<td id="LC281" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L282" class="blob-num js-line-number" data-line-number="282"></td>
<td id="LC282" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L283" class="blob-num js-line-number" data-line-number="283"></td>
<td id="LC283" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>.help-block.with-errors<span class="pl-pds">'</span></span>).<span class="pl-en">each</span>(<span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L284" class="blob-num js-line-number" data-line-number="284"></td>
<td id="LC284" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $<span class="pl-v">this</span> <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-v">this</span>)</td>
</tr>
<tr>
<td id="L285" class="blob-num js-line-number" data-line-number="285"></td>
<td id="LC285" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> originalContent <span class="pl-k">=</span> <span class="pl-smi">$this</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.originalContent<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L286" class="blob-num js-line-number" data-line-number="286"></td>
<td id="LC286" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L287" class="blob-num js-line-number" data-line-number="287"></td>
<td id="LC287" class="blob-code blob-code-inner js-file-line"> $<span class="pl-v">this</span></td>
</tr>
<tr>
<td id="L288" class="blob-num js-line-number" data-line-number="288"></td>
<td id="LC288" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">removeData</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator.originalContent<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L289" class="blob-num js-line-number" data-line-number="289"></td>
<td id="LC289" class="blob-code blob-code-inner js-file-line"> .<span class="pl-en">html</span>(originalContent)</td>
</tr>
<tr>
<td id="L290" class="blob-num js-line-number" data-line-number="290"></td>
<td id="LC290" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L291" class="blob-num js-line-number" data-line-number="291"></td>
<td id="LC291" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L292" class="blob-num js-line-number" data-line-number="292"></td>
<td id="LC292" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>input[type="submit"], button[type="submit"]<span class="pl-pds">'</span></span>).<span class="pl-en">removeClass</span>(<span class="pl-s"><span class="pl-pds">'</span>disabled<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L293" class="blob-num js-line-number" data-line-number="293"></td>
<td id="LC293" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L294" class="blob-num js-line-number" data-line-number="294"></td>
<td id="LC294" class="blob-code blob-code-inner js-file-line"> <span class="pl-v">this</span>.<span class="pl-smi">$element</span>.<span class="pl-c1">find</span>(<span class="pl-s"><span class="pl-pds">'</span>.has-error, .has-danger<span class="pl-pds">'</span></span>).<span class="pl-en">removeClass</span>(<span class="pl-s"><span class="pl-pds">'</span>has-error has-danger<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L295" class="blob-num js-line-number" data-line-number="295"></td>
<td id="LC295" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L296" class="blob-num js-line-number" data-line-number="296"></td>
<td id="LC296" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-v">this</span></td>
</tr>
<tr>
<td id="L297" class="blob-num js-line-number" data-line-number="297"></td>
<td id="LC297" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L298" class="blob-num js-line-number" data-line-number="298"></td>
<td id="LC298" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L299" class="blob-num js-line-number" data-line-number="299"></td>
<td id="LC299" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// VALIDATOR PLUGIN DEFINITION</span></td>
</tr>
<tr>
<td id="L300" class="blob-num js-line-number" data-line-number="300"></td>
<td id="LC300" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// ===========================</span></td>
</tr>
<tr>
<td id="L301" class="blob-num js-line-number" data-line-number="301"></td>
<td id="LC301" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L302" class="blob-num js-line-number" data-line-number="302"></td>
<td id="LC302" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L303" class="blob-num js-line-number" data-line-number="303"></td>
<td id="LC303" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">function</span> <span class="pl-en">Plugin</span>(<span class="pl-smi">option</span>) {</td>
</tr>
<tr>
<td id="L304" class="blob-num js-line-number" data-line-number="304"></td>
<td id="LC304" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-v">this</span>.<span class="pl-en">each</span>(<span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L305" class="blob-num js-line-number" data-line-number="305"></td>
<td id="LC305" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $<span class="pl-v">this</span> <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-v">this</span>)</td>
</tr>
<tr>
<td id="L306" class="blob-num js-line-number" data-line-number="306"></td>
<td id="LC306" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> options <span class="pl-k">=</span> <span class="pl-smi">$</span>.<span class="pl-en">extend</span>({}, <span class="pl-smi">Validator</span>.<span class="pl-c1">DEFAULTS</span>, <span class="pl-smi">$this</span>.<span class="pl-c1">data</span>(), <span class="pl-k">typeof</span> option <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">'</span>object<span class="pl-pds">'</span></span> <span class="pl-k">&&</span> option)</td>
</tr>
<tr>
<td id="L307" class="blob-num js-line-number" data-line-number="307"></td>
<td id="LC307" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> data <span class="pl-k">=</span> <span class="pl-smi">$this</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator<span class="pl-pds">'</span></span>)</td>
</tr>
<tr>
<td id="L308" class="blob-num js-line-number" data-line-number="308"></td>
<td id="LC308" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L309" class="blob-num js-line-number" data-line-number="309"></td>
<td id="LC309" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span>data <span class="pl-k">&&</span> option <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">'</span>destroy<span class="pl-pds">'</span></span>) <span class="pl-k">return</span></td>
</tr>
<tr>
<td id="L310" class="blob-num js-line-number" data-line-number="310"></td>
<td id="LC310" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">!</span>data) <span class="pl-smi">$this</span>.<span class="pl-c1">data</span>(<span class="pl-s"><span class="pl-pds">'</span>bs.validator<span class="pl-pds">'</span></span>, (data <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Validator</span>(<span class="pl-v">this</span>, options)))</td>
</tr>
<tr>
<td id="L311" class="blob-num js-line-number" data-line-number="311"></td>
<td id="LC311" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-k">typeof</span> option <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">'</span>string<span class="pl-pds">'</span></span>) data[option]()</td>
</tr>
<tr>
<td id="L312" class="blob-num js-line-number" data-line-number="312"></td>
<td id="LC312" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L313" class="blob-num js-line-number" data-line-number="313"></td>
<td id="LC313" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L314" class="blob-num js-line-number" data-line-number="314"></td>
<td id="LC314" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L315" class="blob-num js-line-number" data-line-number="315"></td>
<td id="LC315" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> old <span class="pl-k">=</span> <span class="pl-smi">$</span>.<span class="pl-smi">fn</span>.<span class="pl-smi">validator</span></td>
</tr>
<tr>
<td id="L316" class="blob-num js-line-number" data-line-number="316"></td>
<td id="LC316" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L317" class="blob-num js-line-number" data-line-number="317"></td>
<td id="LC317" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-smi">fn</span>.<span class="pl-smi">validator</span> <span class="pl-k">=</span> <span class="pl-c1">Plugin</span></td>
</tr>
<tr>
<td id="L318" class="blob-num js-line-number" data-line-number="318"></td>
<td id="LC318" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-smi">fn</span>.<span class="pl-smi">validator</span>.<span class="pl-smi">Constructor</span> <span class="pl-k">=</span> Validator</td>
</tr>
<tr>
<td id="L319" class="blob-num js-line-number" data-line-number="319"></td>
<td id="LC319" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L320" class="blob-num js-line-number" data-line-number="320"></td>
<td id="LC320" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L321" class="blob-num js-line-number" data-line-number="321"></td>
<td id="LC321" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// VALIDATOR NO CONFLICT</span></td>
</tr>
<tr>
<td id="L322" class="blob-num js-line-number" data-line-number="322"></td>
<td id="LC322" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// =====================</span></td>
</tr>
<tr>
<td id="L323" class="blob-num js-line-number" data-line-number="323"></td>
<td id="LC323" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L324" class="blob-num js-line-number" data-line-number="324"></td>
<td id="LC324" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-smi">fn</span>.<span class="pl-smi">validator</span>.<span class="pl-en">noConflict</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L325" class="blob-num js-line-number" data-line-number="325"></td>
<td id="LC325" class="blob-code blob-code-inner js-file-line"> <span class="pl-smi">$</span>.<span class="pl-smi">fn</span>.<span class="pl-smi">validator</span> <span class="pl-k">=</span> old</td>
</tr>
<tr>
<td id="L326" class="blob-num js-line-number" data-line-number="326"></td>
<td id="LC326" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-v">this</span></td>
</tr>
<tr>
<td id="L327" class="blob-num js-line-number" data-line-number="327"></td>
<td id="LC327" class="blob-code blob-code-inner js-file-line"> }</td>
</tr>
<tr>
<td id="L328" class="blob-num js-line-number" data-line-number="328"></td>
<td id="LC328" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L329" class="blob-num js-line-number" data-line-number="329"></td>
<td id="LC329" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L330" class="blob-num js-line-number" data-line-number="330"></td>
<td id="LC330" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// VALIDATOR DATA-API</span></td>
</tr>
<tr>
<td id="L331" class="blob-num js-line-number" data-line-number="331"></td>
<td id="LC331" class="blob-code blob-code-inner js-file-line"> <span class="pl-c">// ==================</span></td>
</tr>
<tr>
<td id="L332" class="blob-num js-line-number" data-line-number="332"></td>
<td id="LC332" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L333" class="blob-num js-line-number" data-line-number="333"></td>
<td id="LC333" class="blob-code blob-code-inner js-file-line"> <span class="pl-en">$</span>(<span class="pl-c1">window</span>).<span class="pl-en">on</span>(<span class="pl-s"><span class="pl-pds">'</span>load<span class="pl-pds">'</span></span>, <span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L334" class="blob-num js-line-number" data-line-number="334"></td>
<td id="LC334" class="blob-code blob-code-inner js-file-line"> <span class="pl-en">$</span>(<span class="pl-s"><span class="pl-pds">'</span>form[data-toggle="validator"]<span class="pl-pds">'</span></span>).<span class="pl-en">each</span>(<span class="pl-k">function</span> () {</td>
</tr>
<tr>
<td id="L335" class="blob-num js-line-number" data-line-number="335"></td>
<td id="LC335" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">var</span> $form <span class="pl-k">=</span> <span class="pl-en">$</span>(<span class="pl-v">this</span>)</td>
</tr>
<tr>
<td id="L336" class="blob-num js-line-number" data-line-number="336"></td>
<td id="LC336" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">Plugin</span>.<span class="pl-c1">call</span>($form, <span class="pl-smi">$form</span>.<span class="pl-c1">data</span>())</td>
</tr>
<tr>
<td id="L337" class="blob-num js-line-number" data-line-number="337"></td>
<td id="LC337" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L338" class="blob-num js-line-number" data-line-number="338"></td>
<td id="LC338" class="blob-code blob-code-inner js-file-line"> })</td>
</tr>
<tr>
<td id="L339" class="blob-num js-line-number" data-line-number="339"></td>
<td id="LC339" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L340" class="blob-num js-line-number" data-line-number="340"></td>
<td id="LC340" class="blob-code blob-code-inner js-file-line">}(jQuery);</td>
</tr>
</table>
</div>
</div>
<button type="button" data-facebox="#jump-to-line" data-facebox-class="linejump" data-hotkey="l" class="hidden">Jump to Line</button>
<div id="jump-to-line" style="display:none">
<!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="" class="js-jump-to-line-form" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<input class="form-control linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" aria-label="Jump to line" autofocus>
<button type="submit" class="btn">Go</button>
</form></div>
</div>
<div class="modal-backdrop"></div>
</div>
</div>
</div>
</div>
<div class="container site-footer-container">
<div class="site-footer" role="contentinfo">
<ul class="site-footer-links right">
<li><a href="https://status.github.com/" data-ga-click="Footer, go to status, text:status">Status</a></li>
<li><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li>
<li><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li>
<li><a href="https://shop.github.com" data-ga-click="Footer, go to shop, text:shop">Shop</a></li>
<li><a href="https://github.com/blog" data-ga-click="Footer, go to blog, text:blog">Blog</a></li>
<li><a href="https://github.com/about" data-ga-click="Footer, go to about, text:about">About</a></li>
</ul>
<a href="https://github.com" aria-label="Homepage" class="site-footer-mark">
<svg aria-hidden="true" class="octicon octicon-mark-github" height="24" title="GitHub " version="1.1" viewBox="0 0 16 16" width="24"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59 0.4 0.07 0.55-0.17 0.55-0.38 0-0.19-0.01-0.82-0.01-1.49-2.01 0.37-2.53-0.49-2.69-0.94-0.09-0.23-0.48-0.94-0.82-1.13-0.28-0.15-0.68-0.52-0.01-0.53 0.63-0.01 1.08 0.58 1.23 0.82 0.72 1.21 1.87 0.87 2.33 0.66 0.07-0.52 0.28-0.87 0.51-1.07-1.78-0.2-3.64-0.89-3.64-3.95 0-0.87 0.31-1.59 0.82-2.15-0.08-0.2-0.36-1.02 0.08-2.12 0 0 0.67-0.21 2.2 0.82 0.64-0.18 1.32-0.27 2-0.27 0.68 0 1.36 0.09 2 0.27 1.53-1.04 2.2-0.82 2.2-0.82 0.44 1.1 0.16 1.92 0.08 2.12 0.51 0.56 0.82 1.27 0.82 2.15 0 3.07-1.87 3.75-3.65 3.95 0.29 0.25 0.54 0.73 0.54 1.48 0 1.07-0.01 1.93-0.01 2.2 0 0.21 0.15 0.46 0.55 0.38C13.71 14.53 16 11.53 16 8 16 3.58 12.42 0 8 0z"></path></svg>
</a>
<ul class="site-footer-links">
<li>© 2016 <span title="0.16803s from github-fe134-cp1-prd.iad.github.net">GitHub</span>, Inc.</li>
<li><a href="https://github.com/site/terms" data-ga-click="Footer, go to terms, text:terms">Terms</a></li>
<li><a href="https://github.com/site/privacy" data-ga-click="Footer, go to privacy, text:privacy">Privacy</a></li>
<li><a href="https://github.com/security" data-ga-click="Footer, go to security, text:security">Security</a></li>
<li><a href="https://github.com/contact" data-ga-click="Footer, go to contact, text:contact">Contact</a></li>
<li><a href="https://help.github.com" data-ga-click="Footer, go to help, text:help">Help</a></li>
</ul>
</div>
</div>
<div id="ajax-error-message" class="ajax-error-message flash flash-error">
<svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M15.72 12.5l-6.85-11.98C8.69 0.21 8.36 0.02 8 0.02s-0.69 0.19-0.87 0.5l-6.85 11.98c-0.18 0.31-0.18 0.69 0 1C0.47 13.81 0.8 14 1.15 14h13.7c0.36 0 0.69-0.19 0.86-0.5S15.89 12.81 15.72 12.5zM9 12H7V10h2V12zM9 9H7V5h2V9z"></path></svg>
<button type="button" class="flash-close js-flash-close js-ajax-error-dismiss" aria-label="Dismiss error">
<svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M7.48 8l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75-1.48-1.48 3.75-3.75L0.77 4.25l1.48-1.48 3.75 3.75 3.75-3.75 1.48 1.48-3.75 3.75z"></path></svg>
</button>
Something went wrong with that request. Please try again.
</div>
<script crossorigin="anonymous" integrity="sha256-XCxpilp9vs+/7XGAGYtcxbwh0FiDkiaUSb7RbRJPDqM=" src="https://assets-cdn.github.com/assets/frameworks-5c2c698a5a7dbecfbfed7180198b5cc5bc21d0588392269449bed16d124f0ea3.js"></script>
<script async="async" crossorigin="anonymous" integrity="sha256-vwvxzUmturbFLzrw6rQMiWIeC1ZTLv9efJQwCMeeIew=" src="https://assets-cdn.github.com/assets/github-bf0bf1cd49adbab6c52f3af0eab40c89621e0b56532eff5e7c943008c79e21ec.js"></script>
<div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner hidden">
<svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M15.72 12.5l-6.85-11.98C8.69 0.21 8.36 0.02 8 0.02s-0.69 0.19-0.87 0.5l-6.85 11.98c-0.18 0.31-0.18 0.69 0 1C0.47 13.81 0.8 14 1.15 14h13.7c0.36 0 0.69-0.19 0.86-0.5S15.89 12.81 15.72 12.5zM9 12H7V10h2V12zM9 9H7V5h2V9z"></path></svg>
<span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span>
<span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span>
</div>
<div class="facebox" id="facebox" style="display:none;">
<div class="facebox-popup">
<div class="facebox-content" role="dialog" aria-labelledby="facebox-header" aria-describedby="facebox-description">
</div>
<button type="button" class="facebox-close js-facebox-close" aria-label="Close modal">
<svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M7.48 8l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75-1.48-1.48 3.75-3.75L0.77 4.25l1.48-1.48 3.75 3.75 3.75-3.75 1.48 1.48-3.75 3.75z"></path></svg>
</button>
</div>
</div>
</body>
</html>
| mit |
hzouba/BestTrip2 | app/cache/dev/twig/0/0/001c4b0e86622232bf82d2e007d2d8b9f8a32f898188508bf461c0ee975e4d9a.php | 5150 | <?php
/* @WebProfiler/Profiler/toolbar_js.html.twig */
class __TwigTemplate_001c4b0e86622232bf82d2e007d2d8b9f8a32f898188508bf461c0ee975e4d9a extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div id=\"sfwdt";
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "\" class=\"sf-toolbar\" style=\"display: none\"></div>
";
// line 2
$this->loadTemplate("@WebProfiler/Profiler/base_js.html.twig", "@WebProfiler/Profiler/toolbar_js.html.twig", 2)->display($context);
// line 3
echo "<script>/*<![CDATA[*/
(function () {
";
// line 5
if (("top" == (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")))) {
// line 6
echo " var sfwdt = document.getElementById('sfwdt";
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "');
document.body.insertBefore(
document.body.removeChild(sfwdt),
document.body.firstChild
);
";
}
// line 12
echo "
Sfjs.load(
'sfwdt";
// line 14
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "',
'";
// line 15
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_wdt", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")))), "html", null, true);
echo "',
function(xhr, el) {
el.style.display = -1 !== xhr.responseText.indexOf('sf-toolbarreset') ? 'block' : 'none';
if (el.style.display == 'none') {
return;
}
if (Sfjs.getPreference('toolbar/displayState') == 'none') {
document.getElementById('sfToolbarMainContent-";
// line 24
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'none';
document.getElementById('sfToolbarClearer-";
// line 25
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'none';
document.getElementById('sfMiniToolbar-";
// line 26
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'block';
} else {
document.getElementById('sfToolbarMainContent-";
// line 28
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'block';
document.getElementById('sfToolbarClearer-";
// line 29
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'block';
document.getElementById('sfMiniToolbar-";
// line 30
echo twig_escape_filter($this->env, (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")), "html", null, true);
echo "').style.display = 'none';
}
},
function(xhr) {
if (xhr.status !== 0) {
confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\\n\\nDo you want to open the profiler?') && (window.location = '";
// line 35
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_profiler", array("token" => (isset($context["token"]) ? $context["token"] : $this->getContext($context, "token")))), "html", null, true);
echo "');
}
},
{'maxTries': 5}
);
})();
/*]]>*/</script>
";
}
public function getTemplateName()
{
return "@WebProfiler/Profiler/toolbar_js.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 91 => 35, 83 => 30, 79 => 29, 75 => 28, 70 => 26, 66 => 25, 62 => 24, 50 => 15, 46 => 14, 42 => 12, 32 => 6, 30 => 5, 26 => 3, 24 => 2, 19 => 1,);
}
}
| mit |
sketch7/ssv-ng-dojo | src/app/app.const.ts | 701 | export class AppConst {
moduleName = "app-heroes";
templateModuleName = "app-heroes.tmpls";
basePath = "/dist/app";
controllerAs = "vm";
name = "Heroes";
version = "1.0.0-alpha";
routeStates = new RouteStateConfig();
events = {
myEvent: "example",
uiRouter: {
$stateChangeError: "$stateChangeError",
$stateChangeStart: "$stateChangeStart",
$stateChangeSuccess: "$stateChangeSuccess",
$stateNotFound: "$stateNotFound"
}
};
}
export class RouteStateConfig {
layout = "layout";
error = "error";
home = `${this.layout}.home`;
basicForm = `${this.layout}.basic-form`;
heroes = `${this.layout}.heroes`;
hero = `${this.layout}.hero`;
}
export default new AppConst(); | mit |
sorahavok/java-games | src/tetris/factories/ColorFactory.java | 881 | package tetris.factories;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
public class ColorFactory {
private final static int ALPHA = 160;
private final static List<Color> colors = new ArrayList<>();
private final static List<String> colorNames = new ArrayList<>();
public static Color getColor(int index){
return colors.get(index);
}
public static List<String> getColorNameArray() {
return colorNames;
}
public static void addColor(String s) {
try {
Color c = (Color) Color.class.getField(s).get(null);
Color alphaColor = new Color(c.getRed(), c.getGreen(), c.getBlue(), ALPHA);
colors.add(alphaColor);
colorNames.add(s);
}
catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) {
System.err.println("Color " + s +" Not Found!");
e.printStackTrace();
}
}
}
| mit |
Taerus/DTA-Services | src/main/java/com/dta/services/dao/ICategoryDao.java | 351 | package com.dta.services.dao;
import java.util.List;
import com.dta.services.model.Category;
/**
*
* Interface of dao layout of category
*
* @author Hugo Dumont
*
*/
public interface ICategoryDao {
void create(Category category);
Category getById(long id);
List<Category> list();
void update(Category category);
void delete(int id);
}
| mit |
alsatian-test/alsatian | packages/alsatian/test/unit-tests/running/test-runner/pre-test.spec.ts | 6081 | import {
Test,
Expect,
Setup,
SpyOn,
Teardown,
TestCase,
Timeout
} from "../../../../core/alsatian-core";
import { TestRunner } from "../../../../core/running/test-runner";
import { TestOutputStream } from "../../../../core/test-output-stream";
import { TestSet } from "../../../../core/test-set";
import { TestBuilder } from "../../../builders/test-builder";
import { TestCaseBuilder } from "../../../builders/test-case-builder";
import { TestFixtureBuilder } from "../../../builders/test-fixture-builder";
import { TestSetBuilder } from "../../../builders/test-set-builder";
import { TestPlan } from "../../../../core/running";
export class PreTestTests {
private originalTestPlan!: TestPlan;
@Setup
private recordOriginalTestPlan() {
this.originalTestPlan = Reflect.getMetadata(
"alsatian:test-plan",
Expect
);
}
@Teardown
private restoreOriginalTestPlan() {
Reflect.defineMetadata(
"alsatian:test-plan",
this.originalTestPlan,
Expect
);
}
@Test()
public async tapVersionHeaderOutput() {
const testFixtureBuilder = new TestFixtureBuilder();
const testBuilder = new TestBuilder();
testBuilder.addTestCase(new TestCaseBuilder().build());
testFixtureBuilder.addTest(testBuilder.build());
const fixture = testFixtureBuilder.build();
const testSet = new TestSetBuilder().addTestFixture(fixture).build();
const output = new TestOutputStream();
SpyOn(output, "push");
const testRunner = new TestRunner(output);
await testRunner.run(testSet);
Expect(output.push).toHaveBeenCalledWith("TAP version 13\n");
}
@TestCase(1)
@TestCase(2)
@TestCase(5)
@Test()
public async multipleTestFixtureWithSingleTestOutputsCorrectTestNumber(
testFixtureCount: number
) {
const fixtures = [];
for (let i = 0; i < testFixtureCount; i++) {
const testFixtureBuilder = new TestFixtureBuilder();
const testBuilder = new TestBuilder();
testBuilder.addTestCase(new TestCaseBuilder().build());
testFixtureBuilder.addTest(testBuilder.build());
fixtures.push(testFixtureBuilder.build());
}
const testSet = new TestSetBuilder().withTestFixtures(fixtures).build();
const output = new TestOutputStream();
SpyOn(output, "push");
const testRunner = new TestRunner(output);
await testRunner.run(testSet);
Expect(output.push).toHaveBeenCalledWith(
"1.." + testFixtureCount + "\n"
);
}
@TestCase(1, 1)
@TestCase(1, 2)
@TestCase(1, 5)
@TestCase(2, 1)
@TestCase(2, 2)
@TestCase(2, 5)
@TestCase(5, 1)
@TestCase(5, 2)
@TestCase(5, 5)
@Test()
public async multipleTestFixtureWithMultipleTestsOutputsCorrectTestCount(
testFixtureCount: number,
testCount: number
) {
const fixtures = [];
for (let i = 0; i < testFixtureCount; i++) {
const testFixtureBuilder = new TestFixtureBuilder();
for (let j = 0; j < testCount; j++) {
const testFunctionKey = "testFunction" + j;
const testBuilder = new TestBuilder().withKey(testFunctionKey);
testBuilder.addTestCase(new TestCaseBuilder().build());
testFixtureBuilder.addTest(testBuilder.build());
}
fixtures.push(testFixtureBuilder.build());
}
const testSet = new TestSetBuilder().withTestFixtures(fixtures).build();
const resultPromise: any = {
catch: (error: Error) => {},
resolve: () => {},
then: (callback: (testResults: Array<any>) => any) => {
resultPromise.resolve = callback;
return resultPromise;
}
};
const output = new TestOutputStream();
SpyOn(output, "push");
const testRunner = new TestRunner(output);
await testRunner.run(testSet);
Expect(output.push).toHaveBeenCalledWith(
"1.." + testFixtureCount * testCount + "\n"
);
}
@TestCase(1, 1, 1)
@TestCase(1, 2, 1)
@TestCase(1, 5, 1)
@TestCase(2, 1, 1)
@TestCase(2, 2, 1)
@TestCase(2, 5, 1)
@TestCase(5, 1, 1)
@TestCase(5, 2, 1)
@TestCase(5, 5, 1)
@TestCase(1, 1, 2)
@TestCase(1, 2, 2)
@TestCase(1, 5, 2)
@TestCase(2, 1, 2)
@TestCase(2, 2, 2)
@TestCase(2, 5, 2)
@TestCase(5, 1, 2)
@TestCase(5, 2, 2)
@TestCase(5, 5, 2)
@TestCase(1, 1, 5)
@TestCase(1, 2, 5)
@TestCase(1, 5, 5)
@TestCase(2, 1, 5)
@TestCase(2, 2, 5)
@TestCase(2, 5, 5)
@TestCase(5, 1, 5)
@TestCase(5, 2, 5)
@Timeout(1000)
@Test()
public async multipleTestFixtureWithMultipleTestsWithMultipleTestCasesOutputsCorrectTestCount(
testFixtureCount: number,
testCount: number,
testCaseCount: number
) {
const fixtures = [];
for (let i = 0; i < testFixtureCount; i++) {
const testFixtureBuilder = new TestFixtureBuilder();
for (let j = 0; j < testCount; j++) {
const testFunctionKey = "testFunction" + j;
const testBuilder = new TestBuilder().withKey(testFunctionKey);
testFixtureBuilder.addTest(testBuilder.build());
for (let k = 0; k < testCaseCount; k++) {
testBuilder.addTestCase(new TestCaseBuilder().build());
}
}
fixtures.push(testFixtureBuilder.build());
}
const testSet = new TestSetBuilder().withTestFixtures(fixtures).build();
const output = new TestOutputStream();
SpyOn(output, "push");
const testRunner = new TestRunner(output);
await testRunner.run(testSet);
Expect(output.push).toHaveBeenCalledWith(
"1.." + testFixtureCount * testCount * testCaseCount + "\n"
);
}
@TestCase(1)
@TestCase(2)
@TestCase(5)
@Test()
public async testFixtureWithMultipleTestsAndSecondWithNoneOutputsCorrectTestNumber(
testFixtureCount: number
) {
const fixtures = [];
for (let i = 0; i < testFixtureCount; i++) {
const testFixtureBuilder = new TestFixtureBuilder();
const testBuilder = new TestBuilder();
testBuilder.addTestCase(new TestCaseBuilder().build());
testFixtureBuilder.addTest(testBuilder.build());
fixtures.push(testFixtureBuilder.build());
}
fixtures.push(new TestFixtureBuilder().build());
const testSet = new TestSetBuilder().withTestFixtures(fixtures).build();
const output = new TestOutputStream();
SpyOn(output, "push");
const testRunner = new TestRunner(output);
await testRunner.run(testSet);
Expect(output.push).toHaveBeenCalledWith(
"1.." + testFixtureCount + "\n"
);
}
}
| mit |
matiasleidemer/live_soccer | spec/match_collection_spec.rb | 1250 | # encoding: UTF-8
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "MatchCollection" do
let(:params) {
[{ date: DateTime.parse("20May 18h30"), home: "Vasco", visitor: "Grêmio", score: "1 x 2", id: "40075" },
{ date: DateTime.parse("20May 18h30"), home: "Cruzeiro", visitor: "Atlético-GO", score: "0 x 0", id: "40085" }]
}
let(:match_collection) { LiveSoccer::MatchCollection.new params }
describe ".new" do
it "initializes a new MatchCollection class" do
LiveSoccer::MatchCollection.new(params).should be_a LiveSoccer::MatchCollection
end
it "initializes a Match object for each param" do
match_collection.matches.first.should be_a LiveSoccer::Match
end
end
describe "#to_s" do
context "with running matches" do
it "prints each Match" do
match_collection.to_s.should == "20May 18:30 - Vasco 1 x 2 Grêmio\n20May 18:30 - Cruzeiro 0 x 0 Atlético-GO"
end
end
context "without running matches" do
it "prints a message" do
match_collection = LiveSoccer::MatchCollection.new []
match_collection.to_s.should == "Sorry, but looks like no one is on the pitch right now..."
end
end
end
end
| mit |
akapps/rest-toolkit | src/main/java/org/akapps/rest/client/zip/DeflateWrapper.java | 1879 | package org.akapps.rest.client.zip;
import java.io.ByteArrayOutputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;
/**
* A wrapper to apply the "deflate" algorithm to a source.
*
* @author Antoine Kapps
*/
public class DeflateWrapper {
private final byte[] source;
public DeflateWrapper(byte[] source) {
this.source = source;
}
/**
* Decodes a deflate-compressed source.
* @return the decoded byte array
*
* @throws RuntimeException if the source is not deflate-encoded
*/
public byte[] decode() {
try(
ByteArrayOutputStream out = new ByteArrayOutputStream(source.length);
InflaterOutputStream inflater = new InflaterOutputStream(out);
) {
// Only 1 pass, as I get the entire source (this is no streaming !)
inflater.write(source);
inflater.flush();
inflater.finish();
return out.toByteArray();
}
catch (Exception e) {
throw new RuntimeException("Cannot decode deflate source - has it been compressed using deflate ?", e);
}
}
/**
* Compress the source using the "deflate" algorithm.
* @return the encoded byte array
*/
public byte[] encode() {
try(
ByteArrayOutputStream out = new ByteArrayOutputStream(source.length);
DeflaterOutputStream deflater = new DeflaterOutputStream(out);
) {
// Only 1 pass, as I get the entire source (this is no streaming !)
deflater.write(source);
deflater.flush();
deflater.finish();
return out.toByteArray();
}
catch (Exception e) {
throw new RuntimeException("Cannot encode source with deflate algorithm", e);
}
}
}
| mit |
smalot/github-webhook | src/Smalot/Github/Webhook/Model/PullRequestModel.php | 671 | <?php
namespace Smalot\Github\Webhook\Model;
/**
* Class PullRequestModel
* @package Smalot\Github\Webhook\Model
*
* Triggered when a pull request is assigned, unassigned, labeled, unlabeled,
* opened, closed, reopened, or synchronized.
*/
class PullRequestModel extends ModelBase
{
/**
* @return string
*/
public function getAction()
{
return $this->payload['action'];
}
/**
* @return int
*/
public function getNumber()
{
return $this->payload['number'];
}
/**
* @return array
*/
public function getPullRequest()
{
return $this->payload['pull_request'];
}
}
| mit |
ISO-tech/sw-d8 | web/2002-1/392/392_11_WEFProtests.php | 4381 | <html>
<head>
<title>
Protest the global fat cats
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<P><font face="Times New Roman, Times, serif" size="5"><b>Protest the global fat cats</b></font></P>
<P><font face="Times New Roman, Times, serif" size="2"><b>By Lee Wengraf</b></font><font face="Arial, Helvetica, sans-serif" size="2"> | February 1, 2002 | Page 11</font></P>
<font face="Times New Roman, Times, serif" size="3"><P>ACTIVISTS IN New York last weekend kicked off more than a week of events and actions to protest the arrival of the world's billionaires for the World Economic Forum (WEF).</P>
<P>Dozens of groups have endorsed the call to action to protest this corporate schmooze-fest, including Jubilee 2000, New York City Labor Against the War, Direct Action Network, School of the Americas Watch and the International Socialist Organization.</P>
<P>On Saturday night, poet and leading global justice activist Dennis Brutus led a panel of speakers at a forum at a West Village church. The following day, about 50 attended the New York City Social Forum, a grassroots meeting modeled after the World Social Forum at Porto Alegre, Brazil.</P>
<P>Many more events lie ahead:</P>
<B><P>January 30<BR>
</B>The week's events begin Wednesday night with the International Socialist Organization's panel discussion on "War, Layoffs and Budget Cuts: Fighting Corporate Globalization After 9/11." Speakers include union and community activists, Dedrick Muhammad of Rev. Al Sharpton's National Action Network, and BBC investigative reporter Gregory Palast.</P>
<B><P>January 31<BR>
</B>The next day, the AFL-CIO is sponsoring a "Working Families Economic Forum," followed by a Rally for Global Justice at a midtown Manhattan Gap store. The rally, cosponsored with Jobs with Justice, will target the Gap's notorious sweatshop conditions--with activists and unionists sending the message that the WEF's agenda is an attack on all workers.</P>
<B><P>January 31-February 1<BR>
</B>Thursday also kicks off a two-day student counter-summit at Columbia University. Scheduled speakers include Democracy Now! host Amy Goodman, Pam Africa of International Concerned Friends and Family of Mumia Abu-Jamal, members of United for a Fair Economy and City University of New York students.</P>
<P>One featured roundtable discussion on "Strategies for the Movement" will be led by Canadian global justice activist Jaggi Singh, Mike Dolan of Public Citizen and Katherine Dwyer of the International Socialist Organization.</P>
<B><P>February 2<BR>
</B>The week of activities will culminate with a march and actions on Saturday. The march will begin at the bottom of Central Park and go to several blocks from the Waldorf-Astoria Hotel, site of the WEF summit. There, the plan is for marchers to choose whether they want to cross into the "frozen zone" established by New York police--to participate in direct actions.</P>
<P>Some activists are planning to bring pots and pans to bang at the protests--in solidarity with the people of Argentina and their mass uprisings in December.</P>
<P>The media and the police have been working overtime to paint protesters as "violent rioters" bent on destroying the city. But we won't be intimidated! Come out to tell the WEF that you oppose their corporate agenda.</P>
<P><I>For more information, go to www.anotherworldispossible.com on the Web.</I></P>
<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| mit |
Peppa-Peddler/users | users/models/user.js | 1005 | var knex = require('../db/connection');
var bcrypt = require('bcryptjs');
var mongoose = require('mongoose');
var messageSchema = mongoose.Schema({
mensaje : String,
date: {type : Date, default: Date.now}
},{_id : false});
var taskSchema = mongoose.Schema({
title : {type: String, required: true},
content : {type: String, required: true},
status : {type: Boolean, default: false},
late : {type: Boolean, default: false},
start : {type : Date, default : Date.now},
limit : Date
});
var userSchema = mongoose.Schema({
local :{
username : String,
password : String,
tipo : Number,
messages : [ messageSchema ],
date : { type: Date, default: Date.now },
tasks : [ taskSchema ]
}
});
userSchema.methods.generateHash = function (password) {
return bcrypt.hashSync( password,bcrypt.genSaltSync() );
};
userSchema.methods.validPass = function (password) {
return bcrypt.compareSync( password, this.local.password )
};
module.exports = mongoose.model('User', userSchema);
| mit |
kazimanzurrashid/textuml-dotnet | source/TextUml/Scripts/application/uml/language/sequence/title.js | 692 |
define(function(require) {
var Title, trim;
trim = require('./helpers').trim;
return Title = (function() {
function Title() {}
Title.prototype.handles = function(context) {
var errorMessage, match;
match = context.line.match(/^title\s+(\w.*)/i);
if (!match) {
return false;
}
if (context.title || context.participants.length || context.commands.length) {
errorMessage = ("Error on line " + (context.getLineNumber()) + ", ") + 'title must be defined before any other instruction.';
throw new Error(errorMessage);
}
context.setTitle(trim(match[1]));
return true;
};
return Title;
})();
});
| mit |
Department-for-Work-and-Pensions/ClaimReceived | cr/test/ingress/submission/SubmissionServiceIntegrationSpec.scala | 5002 | package ingress.submission
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import com.rabbitmq.client.{QueueingConsumer, Channel, Connection}
import play.api.libs.ws.WS
import play.api.test.{FakeApplication, FakeRequest}
import play.api.test.Helpers._
import com.rabbitmq.client.AMQP.BasicProperties
import app.ConfigProperties
import utils.WithApplication
import scala.concurrent.{Await, TimeoutException, ExecutionContext, Future}
import ExecutionContext.Implicits.global
import submission.SubmissionService
import submission.messaging._
import scala.concurrent.duration._
import app.ConfigProperties._
import scala.xml.XML
class SubmissionServiceIntegrationSpec extends Specification with Mockito{
"Ingress Service" should {
"Successfully publish a message into a live broker" in new WithServerConfig("queue.name" -> "IngresServiceIntegration1","env.name"->"Test") {
val queueName = TestUtils.declareQueue
val timestamp = "2013-10-23"
val endpoint = s"http://localhost:$port/submission"
val xml = XML.load (getClass getResourceAsStream "/ValidXMLWithRSASignature.xml")
val response = Await.result(WS.url(endpoint).post(<request>{timestamp}{xml}</request>),DurationInt(4).seconds)
try{
response.status mustEqual OK
}finally{
TestUtils.consumeMessage(queueName) must contain(timestamp)
}
}
"Failure for exceeded message capacity" in new WithApplication {
val service:SubmissionService = new SubmissionService {
override def messagingService: MessageSendingService = {
new MessageSenderImpl {
override def getQueueName:String = "IngressServiceIntegrationSpec_2"
}
}
}
val queueName = service.messagingService.getQueueName
val conn: Connection = ConnectionManager.factory.newConnection()
var channel: Channel = conn.createChannel()
val declareOk = channel.queueDeclare(queueName,true,false,false,null)
channel.confirmSelect()
for(i <- 0 to getIntProperty("rabbit.messages.max")) {
channel.basicPublish("",queueName,new BasicProperties().builder().deliveryMode(2).build(),("Message number "+i).getBytes)
channel.waitForConfirms()
}
channel.close()
val timestamp = "2013-10-24"
val request = FakeRequest().withXmlBody(<request>{timestamp}</request>)
try{
val response = Future(service.xmlProcessing(request))
status(response) mustEqual SERVICE_UNAVAILABLE
}finally {
channel = conn.createChannel()
channel.queuePurge(queueName)
channel.queueDelete(queueName)
channel.close()
conn.close()
}
}
"Failure because connection fails" in new WithApplication{
ConnectionManager.factory.setUri("amqp://nonexistinghost")
val service:SubmissionService = new SubmissionService {
override def messagingService: MessageSendingService = {
new MessageSenderImpl {
override def getQueueName:String = "IngressServiceIntegrationSpec_3"
}
}
}
val request = FakeRequest().withXmlBody(<request></request>)
try {
val response = Future(service.xmlProcessing(request))
status(response) mustEqual SERVICE_UNAVAILABLE
ConnectionManager.factory.setUri(ConnectionManager.readUri)
} catch {
case e: TimeoutException => success
case _: Throwable => failure
}
}
"Failure by createChannel throwing exceptions" in new WithApplication {
val service:SubmissionService = new SubmissionService {
override def messagingService: MessageSendingService = new MessageSenderImpl {
override def getQueueName:String = "IngressServiceIntegrationSpec_4"
override protected def createChannel(connection: Connection): Channel = {
throw new Exception("This is a test thrown exception")
}
}
}
val request = FakeRequest().withXmlBody(<request>{"2013-10-24"}</request>)
try{
val response = Future(service.xmlProcessing(request))
status(response) mustEqual SERVICE_UNAVAILABLE
}finally {
}
}
"Failure by withChannel throwing exceptions" in new WithApplication {
val service:SubmissionService = new SubmissionService {
override def messagingService: MessageSendingService = new MessageSenderImpl {
override def getQueueName:String = "IngressServiceIntegrationSpec_5"
protected override def withChannel(f: (Channel) => Result): Result = {
throw new Exception("This is a test thrown exception")
}
}
}
val request = FakeRequest().withXmlBody(<request>{"2013-10-24"}</request>)
try{
val response = Future(service.xmlProcessing(request))
status(response) mustEqual SERVICE_UNAVAILABLE
}finally {
}
}
}
section("integration")
}
| mit |
Azure/azure-sdk-for-go | sdk/resourcemanager/hdinsight/armhdinsight/zz_generated_extensions_client.go | 34722 | //go:build go1.16
// +build go1.16
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armhdinsight
import (
"context"
"errors"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
"net/url"
"strings"
)
// ExtensionsClient contains the methods for the Extensions group.
// Don't use this type directly, use NewExtensionsClient() instead.
type ExtensionsClient struct {
host string
subscriptionID string
pl runtime.Pipeline
}
// NewExtensionsClient creates a new instance of ExtensionsClient with the specified values.
// subscriptionID - The subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID
// forms part of the URI for every service call.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewExtensionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *ExtensionsClient {
cp := arm.ClientOptions{}
if options != nil {
cp = *options
}
if len(cp.Endpoint) == 0 {
cp.Endpoint = arm.AzurePublicCloud
}
client := &ExtensionsClient{
subscriptionID: subscriptionID,
host: string(cp.Endpoint),
pl: armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, &cp),
}
return client
}
// BeginCreate - Creates an HDInsight cluster extension.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// extensionName - The name of the cluster extension.
// parameters - The cluster extensions create request.
// options - ExtensionsClientBeginCreateOptions contains the optional parameters for the ExtensionsClient.BeginCreate method.
func (client *ExtensionsClient) BeginCreate(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, parameters Extension, options *ExtensionsClientBeginCreateOptions) (ExtensionsClientCreatePollerResponse, error) {
resp, err := client.create(ctx, resourceGroupName, clusterName, extensionName, parameters, options)
if err != nil {
return ExtensionsClientCreatePollerResponse{}, err
}
result := ExtensionsClientCreatePollerResponse{
RawResponse: resp,
}
pt, err := armruntime.NewPoller("ExtensionsClient.Create", "location", resp, client.pl)
if err != nil {
return ExtensionsClientCreatePollerResponse{}, err
}
result.Poller = &ExtensionsClientCreatePoller{
pt: pt,
}
return result, nil
}
// Create - Creates an HDInsight cluster extension.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *ExtensionsClient) create(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, parameters Extension, options *ExtensionsClientBeginCreateOptions) (*http.Response, error) {
req, err := client.createCreateRequest(ctx, resourceGroupName, clusterName, extensionName, parameters, options)
if err != nil {
return nil, err
}
resp, err := client.pl.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {
return nil, runtime.NewResponseError(resp)
}
return resp, nil
}
// createCreateRequest creates the Create request.
func (client *ExtensionsClient) createCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, parameters Extension, options *ExtensionsClientBeginCreateOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
if extensionName == "" {
return nil, errors.New("parameter extensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{extensionName}", url.PathEscape(extensionName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, runtime.MarshalAsJSON(req, parameters)
}
// BeginDelete - Deletes the specified extension for HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// extensionName - The name of the cluster extension.
// options - ExtensionsClientBeginDeleteOptions contains the optional parameters for the ExtensionsClient.BeginDelete method.
func (client *ExtensionsClient) BeginDelete(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, options *ExtensionsClientBeginDeleteOptions) (ExtensionsClientDeletePollerResponse, error) {
resp, err := client.deleteOperation(ctx, resourceGroupName, clusterName, extensionName, options)
if err != nil {
return ExtensionsClientDeletePollerResponse{}, err
}
result := ExtensionsClientDeletePollerResponse{
RawResponse: resp,
}
pt, err := armruntime.NewPoller("ExtensionsClient.Delete", "location", resp, client.pl)
if err != nil {
return ExtensionsClientDeletePollerResponse{}, err
}
result.Poller = &ExtensionsClientDeletePoller{
pt: pt,
}
return result, nil
}
// Delete - Deletes the specified extension for HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *ExtensionsClient) deleteOperation(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, options *ExtensionsClientBeginDeleteOptions) (*http.Response, error) {
req, err := client.deleteCreateRequest(ctx, resourceGroupName, clusterName, extensionName, options)
if err != nil {
return nil, err
}
resp, err := client.pl.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
return nil, runtime.NewResponseError(resp)
}
return resp, nil
}
// deleteCreateRequest creates the Delete request.
func (client *ExtensionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, options *ExtensionsClientBeginDeleteOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
if extensionName == "" {
return nil, errors.New("parameter extensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{extensionName}", url.PathEscape(extensionName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// BeginDisableAzureMonitor - Disables the Azure Monitor on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// options - ExtensionsClientBeginDisableAzureMonitorOptions contains the optional parameters for the ExtensionsClient.BeginDisableAzureMonitor
// method.
func (client *ExtensionsClient) BeginDisableAzureMonitor(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientBeginDisableAzureMonitorOptions) (ExtensionsClientDisableAzureMonitorPollerResponse, error) {
resp, err := client.disableAzureMonitor(ctx, resourceGroupName, clusterName, options)
if err != nil {
return ExtensionsClientDisableAzureMonitorPollerResponse{}, err
}
result := ExtensionsClientDisableAzureMonitorPollerResponse{
RawResponse: resp,
}
pt, err := armruntime.NewPoller("ExtensionsClient.DisableAzureMonitor", "location", resp, client.pl)
if err != nil {
return ExtensionsClientDisableAzureMonitorPollerResponse{}, err
}
result.Poller = &ExtensionsClientDisableAzureMonitorPoller{
pt: pt,
}
return result, nil
}
// DisableAzureMonitor - Disables the Azure Monitor on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *ExtensionsClient) disableAzureMonitor(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientBeginDisableAzureMonitorOptions) (*http.Response, error) {
req, err := client.disableAzureMonitorCreateRequest(ctx, resourceGroupName, clusterName, options)
if err != nil {
return nil, err
}
resp, err := client.pl.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
return nil, runtime.NewResponseError(resp)
}
return resp, nil
}
// disableAzureMonitorCreateRequest creates the DisableAzureMonitor request.
func (client *ExtensionsClient) disableAzureMonitorCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientBeginDisableAzureMonitorOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/azureMonitor"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// BeginDisableMonitoring - Disables the Operations Management Suite (OMS) on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// options - ExtensionsClientBeginDisableMonitoringOptions contains the optional parameters for the ExtensionsClient.BeginDisableMonitoring
// method.
func (client *ExtensionsClient) BeginDisableMonitoring(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientBeginDisableMonitoringOptions) (ExtensionsClientDisableMonitoringPollerResponse, error) {
resp, err := client.disableMonitoring(ctx, resourceGroupName, clusterName, options)
if err != nil {
return ExtensionsClientDisableMonitoringPollerResponse{}, err
}
result := ExtensionsClientDisableMonitoringPollerResponse{
RawResponse: resp,
}
pt, err := armruntime.NewPoller("ExtensionsClient.DisableMonitoring", "location", resp, client.pl)
if err != nil {
return ExtensionsClientDisableMonitoringPollerResponse{}, err
}
result.Poller = &ExtensionsClientDisableMonitoringPoller{
pt: pt,
}
return result, nil
}
// DisableMonitoring - Disables the Operations Management Suite (OMS) on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *ExtensionsClient) disableMonitoring(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientBeginDisableMonitoringOptions) (*http.Response, error) {
req, err := client.disableMonitoringCreateRequest(ctx, resourceGroupName, clusterName, options)
if err != nil {
return nil, err
}
resp, err := client.pl.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
return nil, runtime.NewResponseError(resp)
}
return resp, nil
}
// disableMonitoringCreateRequest creates the DisableMonitoring request.
func (client *ExtensionsClient) disableMonitoringCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientBeginDisableMonitoringOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/clustermonitoring"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// BeginEnableAzureMonitor - Enables the Azure Monitor on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// parameters - The Log Analytics workspace parameters.
// options - ExtensionsClientBeginEnableAzureMonitorOptions contains the optional parameters for the ExtensionsClient.BeginEnableAzureMonitor
// method.
func (client *ExtensionsClient) BeginEnableAzureMonitor(ctx context.Context, resourceGroupName string, clusterName string, parameters AzureMonitorRequest, options *ExtensionsClientBeginEnableAzureMonitorOptions) (ExtensionsClientEnableAzureMonitorPollerResponse, error) {
resp, err := client.enableAzureMonitor(ctx, resourceGroupName, clusterName, parameters, options)
if err != nil {
return ExtensionsClientEnableAzureMonitorPollerResponse{}, err
}
result := ExtensionsClientEnableAzureMonitorPollerResponse{
RawResponse: resp,
}
pt, err := armruntime.NewPoller("ExtensionsClient.EnableAzureMonitor", "location", resp, client.pl)
if err != nil {
return ExtensionsClientEnableAzureMonitorPollerResponse{}, err
}
result.Poller = &ExtensionsClientEnableAzureMonitorPoller{
pt: pt,
}
return result, nil
}
// EnableAzureMonitor - Enables the Azure Monitor on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *ExtensionsClient) enableAzureMonitor(ctx context.Context, resourceGroupName string, clusterName string, parameters AzureMonitorRequest, options *ExtensionsClientBeginEnableAzureMonitorOptions) (*http.Response, error) {
req, err := client.enableAzureMonitorCreateRequest(ctx, resourceGroupName, clusterName, parameters, options)
if err != nil {
return nil, err
}
resp, err := client.pl.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {
return nil, runtime.NewResponseError(resp)
}
return resp, nil
}
// enableAzureMonitorCreateRequest creates the EnableAzureMonitor request.
func (client *ExtensionsClient) enableAzureMonitorCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, parameters AzureMonitorRequest, options *ExtensionsClientBeginEnableAzureMonitorOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/azureMonitor"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, runtime.MarshalAsJSON(req, parameters)
}
// BeginEnableMonitoring - Enables the Operations Management Suite (OMS) on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// parameters - The Operations Management Suite (OMS) workspace parameters.
// options - ExtensionsClientBeginEnableMonitoringOptions contains the optional parameters for the ExtensionsClient.BeginEnableMonitoring
// method.
func (client *ExtensionsClient) BeginEnableMonitoring(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterMonitoringRequest, options *ExtensionsClientBeginEnableMonitoringOptions) (ExtensionsClientEnableMonitoringPollerResponse, error) {
resp, err := client.enableMonitoring(ctx, resourceGroupName, clusterName, parameters, options)
if err != nil {
return ExtensionsClientEnableMonitoringPollerResponse{}, err
}
result := ExtensionsClientEnableMonitoringPollerResponse{
RawResponse: resp,
}
pt, err := armruntime.NewPoller("ExtensionsClient.EnableMonitoring", "location", resp, client.pl)
if err != nil {
return ExtensionsClientEnableMonitoringPollerResponse{}, err
}
result.Poller = &ExtensionsClientEnableMonitoringPoller{
pt: pt,
}
return result, nil
}
// EnableMonitoring - Enables the Operations Management Suite (OMS) on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
func (client *ExtensionsClient) enableMonitoring(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterMonitoringRequest, options *ExtensionsClientBeginEnableMonitoringOptions) (*http.Response, error) {
req, err := client.enableMonitoringCreateRequest(ctx, resourceGroupName, clusterName, parameters, options)
if err != nil {
return nil, err
}
resp, err := client.pl.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {
return nil, runtime.NewResponseError(resp)
}
return resp, nil
}
// enableMonitoringCreateRequest creates the EnableMonitoring request.
func (client *ExtensionsClient) enableMonitoringCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterMonitoringRequest, options *ExtensionsClientBeginEnableMonitoringOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/clustermonitoring"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, runtime.MarshalAsJSON(req, parameters)
}
// Get - Gets the extension properties for the specified HDInsight cluster extension.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// extensionName - The name of the cluster extension.
// options - ExtensionsClientGetOptions contains the optional parameters for the ExtensionsClient.Get method.
func (client *ExtensionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, options *ExtensionsClientGetOptions) (ExtensionsClientGetResponse, error) {
req, err := client.getCreateRequest(ctx, resourceGroupName, clusterName, extensionName, options)
if err != nil {
return ExtensionsClientGetResponse{}, err
}
resp, err := client.pl.Do(req)
if err != nil {
return ExtensionsClientGetResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return ExtensionsClientGetResponse{}, runtime.NewResponseError(resp)
}
return client.getHandleResponse(resp)
}
// getCreateRequest creates the Get request.
func (client *ExtensionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, options *ExtensionsClientGetOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
if extensionName == "" {
return nil, errors.New("parameter extensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{extensionName}", url.PathEscape(extensionName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// getHandleResponse handles the Get response.
func (client *ExtensionsClient) getHandleResponse(resp *http.Response) (ExtensionsClientGetResponse, error) {
result := ExtensionsClientGetResponse{RawResponse: resp}
if err := runtime.UnmarshalAsJSON(resp, &result.ClusterMonitoringResponse); err != nil {
return ExtensionsClientGetResponse{}, err
}
return result, nil
}
// GetAzureAsyncOperationStatus - Gets the async operation status.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// extensionName - The name of the cluster extension.
// operationID - The long running operation id.
// options - ExtensionsClientGetAzureAsyncOperationStatusOptions contains the optional parameters for the ExtensionsClient.GetAzureAsyncOperationStatus
// method.
func (client *ExtensionsClient) GetAzureAsyncOperationStatus(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, operationID string, options *ExtensionsClientGetAzureAsyncOperationStatusOptions) (ExtensionsClientGetAzureAsyncOperationStatusResponse, error) {
req, err := client.getAzureAsyncOperationStatusCreateRequest(ctx, resourceGroupName, clusterName, extensionName, operationID, options)
if err != nil {
return ExtensionsClientGetAzureAsyncOperationStatusResponse{}, err
}
resp, err := client.pl.Do(req)
if err != nil {
return ExtensionsClientGetAzureAsyncOperationStatusResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return ExtensionsClientGetAzureAsyncOperationStatusResponse{}, runtime.NewResponseError(resp)
}
return client.getAzureAsyncOperationStatusHandleResponse(resp)
}
// getAzureAsyncOperationStatusCreateRequest creates the GetAzureAsyncOperationStatus request.
func (client *ExtensionsClient) getAzureAsyncOperationStatusCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, extensionName string, operationID string, options *ExtensionsClientGetAzureAsyncOperationStatusOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/{extensionName}/azureAsyncOperations/{operationId}"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
if extensionName == "" {
return nil, errors.New("parameter extensionName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{extensionName}", url.PathEscape(extensionName))
if operationID == "" {
return nil, errors.New("parameter operationID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{operationId}", url.PathEscape(operationID))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// getAzureAsyncOperationStatusHandleResponse handles the GetAzureAsyncOperationStatus response.
func (client *ExtensionsClient) getAzureAsyncOperationStatusHandleResponse(resp *http.Response) (ExtensionsClientGetAzureAsyncOperationStatusResponse, error) {
result := ExtensionsClientGetAzureAsyncOperationStatusResponse{RawResponse: resp}
if err := runtime.UnmarshalAsJSON(resp, &result.AsyncOperationResult); err != nil {
return ExtensionsClientGetAzureAsyncOperationStatusResponse{}, err
}
return result, nil
}
// GetAzureMonitorStatus - Gets the status of Azure Monitor on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// options - ExtensionsClientGetAzureMonitorStatusOptions contains the optional parameters for the ExtensionsClient.GetAzureMonitorStatus
// method.
func (client *ExtensionsClient) GetAzureMonitorStatus(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientGetAzureMonitorStatusOptions) (ExtensionsClientGetAzureMonitorStatusResponse, error) {
req, err := client.getAzureMonitorStatusCreateRequest(ctx, resourceGroupName, clusterName, options)
if err != nil {
return ExtensionsClientGetAzureMonitorStatusResponse{}, err
}
resp, err := client.pl.Do(req)
if err != nil {
return ExtensionsClientGetAzureMonitorStatusResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return ExtensionsClientGetAzureMonitorStatusResponse{}, runtime.NewResponseError(resp)
}
return client.getAzureMonitorStatusHandleResponse(resp)
}
// getAzureMonitorStatusCreateRequest creates the GetAzureMonitorStatus request.
func (client *ExtensionsClient) getAzureMonitorStatusCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientGetAzureMonitorStatusOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/azureMonitor"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// getAzureMonitorStatusHandleResponse handles the GetAzureMonitorStatus response.
func (client *ExtensionsClient) getAzureMonitorStatusHandleResponse(resp *http.Response) (ExtensionsClientGetAzureMonitorStatusResponse, error) {
result := ExtensionsClientGetAzureMonitorStatusResponse{RawResponse: resp}
if err := runtime.UnmarshalAsJSON(resp, &result.AzureMonitorResponse); err != nil {
return ExtensionsClientGetAzureMonitorStatusResponse{}, err
}
return result, nil
}
// GetMonitoringStatus - Gets the status of Operations Management Suite (OMS) on the HDInsight cluster.
// If the operation fails it returns an *azcore.ResponseError type.
// resourceGroupName - The name of the resource group.
// clusterName - The name of the cluster.
// options - ExtensionsClientGetMonitoringStatusOptions contains the optional parameters for the ExtensionsClient.GetMonitoringStatus
// method.
func (client *ExtensionsClient) GetMonitoringStatus(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientGetMonitoringStatusOptions) (ExtensionsClientGetMonitoringStatusResponse, error) {
req, err := client.getMonitoringStatusCreateRequest(ctx, resourceGroupName, clusterName, options)
if err != nil {
return ExtensionsClientGetMonitoringStatusResponse{}, err
}
resp, err := client.pl.Do(req)
if err != nil {
return ExtensionsClientGetMonitoringStatusResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return ExtensionsClientGetMonitoringStatusResponse{}, runtime.NewResponseError(resp)
}
return client.getMonitoringStatusHandleResponse(resp)
}
// getMonitoringStatusCreateRequest creates the GetMonitoringStatus request.
func (client *ExtensionsClient) getMonitoringStatusCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ExtensionsClientGetMonitoringStatusOptions) (*policy.Request, error) {
urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/extensions/clustermonitoring"
if client.subscriptionID == "" {
return nil, errors.New("parameter client.subscriptionID cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
if resourceGroupName == "" {
return nil, errors.New("parameter resourceGroupName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
if clusterName == "" {
return nil, errors.New("parameter clusterName cannot be empty")
}
urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName))
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-06-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// getMonitoringStatusHandleResponse handles the GetMonitoringStatus response.
func (client *ExtensionsClient) getMonitoringStatusHandleResponse(resp *http.Response) (ExtensionsClientGetMonitoringStatusResponse, error) {
result := ExtensionsClientGetMonitoringStatusResponse{RawResponse: resp}
if err := runtime.UnmarshalAsJSON(resp, &result.ClusterMonitoringResponse); err != nil {
return ExtensionsClientGetMonitoringStatusResponse{}, err
}
return result, nil
}
| mit |
NoUseFreak/Interview | src/NoUseFreak/InterviewBundle/Form/QuestionType.php | 1564 | <?php
namespace NoUseFreak\InterviewBundle\Form;
use NoUseFreak\InterviewBundle\Entity\Question;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class QuestionType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('question')
->add('type', 'choice', array(
'choices' => array(
Question::TYPE_TERM => Question::TYPE_TERM,
Question::TYPE_PROBLEM => Question::TYPE_PROBLEM,
Question::TYPE_MULTI => Question::TYPE_MULTI,
)
))
->add('difficulty', 'entity', array(
'class' => 'NoUseFreakInterviewBundle:QuestionDifficulty',
))
->add('category', 'entity', array(
'class' => 'NoUseFreakInterviewBundle:QuestionCategory',
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'NoUseFreak\InterviewBundle\Entity\Question'
));
}
/**
* @return string
*/
public function getName()
{
return 'nousefreak_interviewbundle_question';
}
}
| mit |
johan--/tahi | lib/generators/task/templates/ember/view.js | 235 | ETahi.<%= class_name %>OverlayView = ETahi.OverlayView.extend({
templateName: "<%= engine_file_name %>/overlays/<%= file_name %>_overlay",
layoutName: "layouts/overlay_layout",
setup: function() {
}.on('didInsertElement')
});
| mit |
AourpallyNikhil/qstore | QStore4S/src/main/java/edu/asu/qstore4s/db/neo4j/impl/StoreObjectsToDb.java | 17648 | package edu.asu.qstore4s.db.neo4j.impl;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import edu.asu.qstore4s.converter.IXmlElements;
import edu.asu.qstore4s.db.neo4j.IStoreObjectsToDb;
import edu.asu.qstore4s.domain.elements.impl.Element;
import edu.asu.qstore4s.domain.elements.impl.Relation;
import edu.asu.qstore4s.domain.elements.impl.Term;
import edu.asu.qstore4s.domain.elements.impl.TermPart;
import edu.asu.qstore4s.domain.elements.impl.TermParts;
import edu.asu.qstore4s.domain.events.impl.AppellationEvent;
import edu.asu.qstore4s.domain.events.impl.CreationEvent;
import edu.asu.qstore4s.domain.events.impl.RelationEvent;
import edu.asu.qstore4s.exception.InvalidDataException;
import edu.asu.qstore4s.repository.AppellationEventRepository;
import edu.asu.qstore4s.repository.RelationEventRepository;
import edu.asu.qstore4s.repository.RelationRepository;
import edu.asu.qstore4s.repository.TermPartRepository;
import edu.asu.qstore4s.repository.TermPartsRepository;
import edu.asu.qstore4s.repository.TermRepository;
/**
* This class stores the objects created out of the input string to database.
*
* @author Veena Borannagowda, Bhargav Desai
*
*/
@PropertySource(value = "classpath:/qstore4s.properties")
@Service
public class StoreObjectsToDb implements IStoreObjectsToDb {
@Autowired
private Environment env;
@Autowired
private AppellationEventRepository appellationEventRepository;
@Autowired
private RelationEventRepository relationEventRepository;
@Autowired
private RelationRepository relationRepository;
@Autowired
private TermRepository termRepository;
@Autowired
private TermPartRepository termPartRepository;
@Autowired
private TermPartsRepository termPartsRepository;
/**
* {@inheritDoc}
*/
@Transactional
public List<CreationEvent> writeObjectsToDb(
List<List<Element>> creationEventList) throws URISyntaxException,
InvalidDataException {
List<CreationEvent> newCreationEventList = new ArrayList<CreationEvent>();
List<Element> creationEventObjects = (creationEventList.get(0));
List<Element> referencedList = creationEventList.get(1);
Iterator<Element> creationEventIterator = creationEventObjects
.iterator();
List<AppellationEvent> appellationsToStore = new ArrayList<AppellationEvent>();
List<RelationEvent> relationsToStore = new ArrayList<RelationEvent>();
while (creationEventIterator.hasNext()) {
CreationEvent creationEventObject = (CreationEvent) (creationEventIterator
.next());
if (creationEventObject instanceof AppellationEvent) {
AppellationEvent appellation = getAppellationObject(
(AppellationEvent) creationEventObject, referencedList);
appellationsToStore.add(appellation);
newCreationEventList.add(appellation);
} else if (creationEventObject instanceof RelationEvent) {
RelationEvent relation = getRelationEventObject(
(RelationEvent) creationEventObject, referencedList);
relationsToStore.add(relation);
newCreationEventList.add(relation);
}
}
for (AppellationEvent a : appellationsToStore)
appellationEventRepository.save(a);
for (RelationEvent r : relationsToStore)
relationEventRepository.save(r);
return newCreationEventList;
}
/**
* This method stores relationObject into the database.
*
* @param relationEventObject
* the relation event object to store in the db.
* @param termsList
* the list of the terms already stored in the db.
* @return URI of the node in the database.
*/
public RelationEvent getRelationEventObject(
RelationEvent relationEventObject, List<Element> referencedList)
throws URISyntaxException, InvalidDataException {
if (isInternalIdSet(relationEventObject)) {
for (Element element : referencedList) {
if (element.getRefId().equals(relationEventObject.getInternal_refId())) {
relationEventObject = (RelationEvent) element;
return relationEventObject;
}
}
throw new InvalidDataException("The referrenced relation event is not present");
}
if (isExternalIdSet(relationEventObject)) {
String externalRefId = relationEventObject.getExternal_refId();
if(externalRefId.startsWith(IXmlElements.REL_EVENT_ID_PREFIX)) {
relationEventObject = relationEventRepository
.findById(relationEventObject.getExternal_refId());
if (relationEventObject != null) {
relationEventObject.setExternal_refId(externalRefId);
return relationEventObject;
} else {
throw new InvalidDataException("Relation Event with "
+ externalRefId + " not present in database.");
}
}
else throw new InvalidDataException("The given ID is not corresponding to RELATION_EVENT");
}
if (!isIdSet(relationEventObject)) {
relationEventObject.setId(createId(IXmlElements.REL_EVENT_ID_PREFIX));
relationEventObject.setIdAssigned(true);
} else {
if (!relationEventObject.isIdAssigned())
throw new InvalidDataException(
"The Id for the relation event is already assigned");
}
Relation relationObject = relationEventObject.getRelation();
relationObject = getRelationObjcet(relationObject, referencedList);
relationEventObject.setRelation(relationObject);
return relationEventObject;
}
private boolean isIdSet(Element element) {
return element.getId() != null && !element.getId().trim().isEmpty();
}
private boolean isInternalIdSet(Element element) {
return element.getInternal_refId() != null && !element.getInternal_refId().trim().isEmpty();
}
private boolean isExternalIdSet(Element element) {
return element.getExternal_refId() != null && !element.getExternal_refId().trim().isEmpty();
}
/**
* This method stores relationObject
* @param relationObject
* @param referencedList
* @return
* @throws InvalidDataException
* @throws URISyntaxException
*/
public Relation getRelationObjcet(Relation relationObject,
List<Element> referencedList) throws InvalidDataException,
URISyntaxException {
if (isInternalIdSet(relationObject)) {
for (Element element : referencedList) {
if (element.getRefId().equals(relationObject.getInternal_refId())) {
String internalRefId= relationObject.getInternal_refId();
relationObject = (Relation) element;
relationObject.setInternal_refId(internalRefId);
return relationObject;
}
}
throw new InvalidDataException("The referenced relation is not present");
}
if (isExternalIdSet(relationObject)) {
String externalRefId = relationObject.getExternal_refId();
if (externalRefId.startsWith(IXmlElements.REL_ID_PREFIX)) {
relationObject = relationRepository.findById(relationObject
.getExternal_refId());
if (relationObject != null) {
relationObject.setExternal_refId(externalRefId);
return relationObject;
} else {
throw new InvalidDataException("Relation with "
+ externalRefId + " not present in database.");
}
}
else throw new InvalidDataException("The given id is not corresponding to RELATION");
}
if (!isIdSet(relationObject)) {
relationObject.setId(createId(IXmlElements.REL_ID_PREFIX));
relationObject.setIdAssigned(true);
} else {
if (!relationObject.isIdAssigned())
throw new InvalidDataException(
"The Id for the relation event is already assigned");
}
{
CreationEvent relationChild = relationObject.getSubject();
if (relationChild instanceof AppellationEvent) {
AppellationEvent subject = getAppellationObject(
(AppellationEvent) relationChild, referencedList);
relationObject.setSubject(subject);
} else if (relationChild instanceof RelationEvent) {
RelationEvent childRelationEvent = getRelationEventObject(
(RelationEvent) relationChild, referencedList);
relationObject.setSubject(childRelationEvent);
}
}
{
CreationEvent relationChild = relationObject.getPredicate();
if (relationChild instanceof AppellationEvent) {
AppellationEvent predicate = getAppellationObject(
(AppellationEvent) relationChild, referencedList);
relationObject.setPredicate(predicate);
}
}
{
CreationEvent relationChild = relationObject.getObject();
if (relationChild instanceof AppellationEvent) {
AppellationEvent object = getAppellationObject(
(AppellationEvent) relationChild, referencedList);
relationObject.setObject(object);
} else if (relationChild instanceof RelationEvent) {
RelationEvent childRelationEvent = getRelationEventObject(
(RelationEvent) relationChild, referencedList);
relationObject.setObject(childRelationEvent);
}
}
return relationObject;
}
/**
* This method stores appellationObject into the database.
*
* @param appellationObject
* the appellation event object to store in the db.
* @param termsList
* the list of the terms already stored in the db.
* @return URI of the node in the database.
*/
public AppellationEvent getAppellationObject(
AppellationEvent appellationObject, List<Element> referencedList)
throws URISyntaxException, InvalidDataException {
// check if the object refers to an existing appellation event or one in the list
if (isInternalIdSet(appellationObject)) {
for (Element element : referencedList) {
if (element.getRefId().equals(appellationObject.getInternal_refId()))
return (AppellationEvent) element;
}
throw new InvalidDataException("The referenced appellation event is not present");
}
if (isExternalIdSet(appellationObject)) {
String externalRefId = appellationObject.getExternal_refId();
if(externalRefId.startsWith(IXmlElements.APPELLATION_ID_PREFIX)) {
appellationObject = appellationEventRepository
.findById(appellationObject.getExternal_refId());
if (appellationObject != null) {
appellationObject.setExternal_refId(externalRefId);
return appellationObject;
} else throw new InvalidDataException("Appellation Event with "
+ externalRefId + " not present in database.");
}
else throw new InvalidDataException("The given ID is not corresponding to APPELLATION");
}
if (!isIdSet(appellationObject)) {
appellationObject.setId(createId(IXmlElements.APPELLATION_ID_PREFIX));
appellationObject.setIdAssigned(true);
} else {
if (!appellationObject.isIdAssigned())
throw new InvalidDataException(
"The Id for the appellation event is already assigned");
}
Term termObject = appellationObject.getTerm();
Term termNode = getTermObject(termObject, referencedList);
appellationObject.setTerm(termNode);
return appellationObject;
}
/**
* This method creates an ID that starts with the provided prefix.
* @param prefix
* @return
*/
private String createId(String prefix) {
return prefix + UUID.randomUUID().getMostSignificantBits();
}
/**
* This method stores term objects into the database.
*
* @param term
* Object the term object to store in the database.
* @return URI of the node in the database.
*/
public Term getTermObject(Term termObject, List<Element> referencedList)
throws URISyntaxException, InvalidDataException {
int refFoundFlag = 0;
if (isInternalIdSet(termObject)) {
for (Element element : referencedList) {
if (element.getRefId().equals(termObject.getInternal_refId())
&& element instanceof Term) {
termObject = (Term) element;
refFoundFlag = 1;
}
}
if(refFoundFlag == 0)
throw new InvalidDataException("The referenced term is not present");
} else if (isExternalIdSet(termObject)) {
String externalRefId = termObject.getExternal_refId();
if(externalRefId.startsWith(IXmlElements.TERM_ID_PERFIX))
{
termObject = termRepository
.findById(termObject.getExternal_refId());
if (termObject != null)
return termObject;
throw new InvalidDataException("Term with " + externalRefId
+ "not present in database.");
}
throw new InvalidDataException("The given ID is not corresponding to TERM");
}
if (!isIdSet(termObject)) {
termObject.setId(createId(IXmlElements.TERM_ID_PERFIX));
termObject.setIdAssigned(true);
} else {
if (!termObject.isIdAssigned())
throw new InvalidDataException(
"The Id for the term event is already assigned");
}
TermParts termPartsObject = termObject.getPrintedRepresentation();
TermParts termParts = getTermPartsObject(termPartsObject,
referencedList);
Set<TermPart> termPartSet = termPartsObject.getTermParts();
Iterator<TermPart> termPartIterator = termPartSet.iterator();
Set<TermPart> newTermPartSet = new HashSet<TermPart>();
while (termPartIterator.hasNext()) {
TermPart termPartObject = termPartIterator.next();
newTermPartSet.add(getTermPartObject(termPartObject, referencedList));
}
termParts.setTermParts(newTermPartSet);
termObject.setPrintedRepresentation(termParts);
Set<Term> referencedTermsList = termObject.getReferencedTerms();
Iterator<Term> referencedTermsIterator = referencedTermsList
.iterator();
Set<Term> newReferencedTermsList = new HashSet<Term>();
while (referencedTermsIterator.hasNext()) {
Term refTerm = referencedTermsIterator.next();
Term refNode = getTermObject(refTerm, referencedList);
newReferencedTermsList.add(refNode);
}
termObject.setReferencedTerms(newReferencedTermsList);
return termObject;
}
/**
* This method stores termParts object into the database.
*
* @param termParts
* Object the term object to store in the database.
* @return URI of the node in the database.
* @throws URISyntaxException
*/
public TermParts getTermPartsObject(TermParts termPartsObject,
List<Element> referencedList) throws InvalidDataException,
URISyntaxException {
int refFoundFlag = 0;
if (isInternalIdSet(termPartsObject)) {
for (Element element : referencedList) {
if (element.getRefId().equals(
termPartsObject.getInternal_refId())) {
termPartsObject = (TermParts) element;
refFoundFlag = 1;
}
}
if(refFoundFlag == 0)
throw new InvalidDataException("The referenced term parts is not present");
} else if (isExternalIdSet(termPartsObject)) {
String externalRefId = termPartsObject.getExternal_refId();
if(externalRefId.startsWith(IXmlElements.TERMPARTS_ID_PREFIX))
{
termPartsObject = termPartsRepository.findById(termPartsObject
.getExternal_refId());
if (termPartsObject != null)
return termPartsObject;
throw new InvalidDataException("Printed Representation with "
+ externalRefId + "not present in database.");
}
throw new InvalidDataException("The given id is not corresponding to TERMPARTS");
}
if (!isIdSet(termPartsObject)) {
termPartsObject.setId(createId(IXmlElements.TERMPARTS_ID_PREFIX));
termPartsObject.setIdAssigned(true);
} else {
if (!termPartsObject.isIdAssigned())
throw new InvalidDataException(
"The Id for the termParts event is already assigned");
}
return termPartsObject;
}
/**
* This method stores termPart object into the database.
*
* @param termPart
* Object the term object to store in the database.
* @return URI of the node in the database.
* @throws URISyntaxException
*/
public TermPart getTermPartObject(TermPart termPartObject,
List<Element> referencedList) throws URISyntaxException,
InvalidDataException {
int refFoundFlag = 0;
if (isInternalIdSet(termPartObject)) {
for (Element element : referencedList) {
if (element.getRefId().equals(
termPartObject.getInternal_refId())) {
termPartObject = (TermPart) element;
refFoundFlag = 1;
}
}
if(refFoundFlag == 0)
throw new InvalidDataException("The referenced term part is not present");
} else if (isExternalIdSet(termPartObject)) {
String externalRefId = termPartObject.getExternal_refId();
if(externalRefId.startsWith(IXmlElements.TERMPART_ID_PERFIX))
{
termPartObject = termPartRepository.findById(termPartObject
.getExternal_refId());
if (termPartObject != null)
return termPartObject;
throw new InvalidDataException("TermPart with " + externalRefId
+ "not present in database.");
}
else
throw new InvalidDataException("The given id is not correspoding to TERMPART");
}
if (!isIdSet(termPartObject)) {
termPartObject.setId(createId(IXmlElements.TERMPART_ID_PERFIX));
termPartObject.setIdAssigned(true);
} else {
if (!termPartObject.isIdAssigned())
throw new InvalidDataException(
"The Id for the termpart event is already assigned");
}
return termPartObject;
}
}
| mit |
zzzprojects/Z.ExtensionMethods | tool/Z.ExtensionMethods.Tool.FixGeneratedVbNet/Program.cs | 971 | // Description: C# Extension Methods | Enhance the .NET Framework and .NET Core with over 1000 extension methods.
// Website & Documentation: https://csharp-extension.com/
// Issues: https://github.com/zzzprojects/Z.ExtensionMethods/issues
// License (MIT): https://github.com/zzzprojects/Z.ExtensionMethods/blob/master/LICENSE
// More projects: https://zzzprojects.com/
// Copyright © ZZZ Projects Inc. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Z.ExtensionMethods.Tool.FixGeneratedVbNet
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| mit |