code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
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 <srs_utest_amf0.hpp>
#include <string>
using namespace std;
#include <srs_core_autofree.hpp>
#include <srs_kernel_error.hpp>
#include <srs_kernel_stream.hpp>
// user scenario: coding and decoding with amf0
VOID TEST(AMF0Test, ScenarioMain)
{
// coded amf0 object
int nb_bytes = 0;
char* bytes = NULL;
// coding data to binaries by amf0
// for example, send connect app response to client.
if (true) {
// props: object
// fmsVer: string
// capabilities: number
// mode: number
// info: object
// level: string
// code: string
// descrption: string
// objectEncoding: number
// data: array
// version: string
// srs_sig: string
SrsAmf0Object* props = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, props, false);
props->set("fmsVer", SrsAmf0Any::str("FMS/3,5,3,888"));
props->set("capabilities", SrsAmf0Any::number(253));
props->set("mode", SrsAmf0Any::number(123));
SrsAmf0Object* info = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, info, false);
info->set("level", SrsAmf0Any::str("info"));
info->set("code", SrsAmf0Any::str("NetStream.Connnect.Success"));
info->set("descrption", SrsAmf0Any::str("connected"));
info->set("objectEncoding", SrsAmf0Any::number(3));
SrsAmf0EcmaArray* data = SrsAmf0Any::ecma_array();
info->set("data", data);
data->set("version", SrsAmf0Any::str("FMS/3,5,3,888"));
data->set("srs_sig", SrsAmf0Any::str("srs"));
// buf store the serialized props/info
nb_bytes = props->total_size() + info->total_size();
ASSERT_GT(nb_bytes, 0);
bytes = new char[nb_bytes];
// use SrsStream to write props/info to binary buf.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
EXPECT_EQ(ERROR_SUCCESS, props->write(&s));
EXPECT_EQ(ERROR_SUCCESS, info->write(&s));
EXPECT_TRUE(s.empty());
// now, user can use the buf
EXPECT_EQ(0x03, bytes[0]);
EXPECT_EQ(0x09, bytes[nb_bytes - 1]);
}
SrsAutoFree(char, bytes, true);
// decoding amf0 object from bytes
// when user know the schema
if (true) {
ASSERT_TRUE(NULL != bytes);
// use SrsStream to assist amf0 object to read from bytes.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
// decoding
// if user know the schema, for instance, it's an amf0 object,
// user can use specified object to decoding.
SrsAmf0Object* props = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, props, false);
EXPECT_EQ(ERROR_SUCCESS, props->read(&s));
// user can use specified object to decoding.
SrsAmf0Object* info = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, info, false);
EXPECT_EQ(ERROR_SUCCESS, info->read(&s));
// use the decoded data.
SrsAmf0Any* prop = NULL;
// if user requires specified property, use ensure of amf0 object
EXPECT_TRUE(NULL != (prop = props->ensure_property_string("fmsVer")));
// the property can assert to string.
ASSERT_TRUE(prop->is_string());
// get the prop string value.
EXPECT_STREQ("FMS/3,5,3,888", prop->to_str().c_str());
// get other type property value
EXPECT_TRUE(NULL != (prop = info->get_property("data")));
// we cannot assert the property is ecma array
if (prop->is_ecma_array()) {
SrsAmf0EcmaArray* data = prop->to_ecma_array();
// it must be a ecma array.
ASSERT_TRUE(NULL != data);
// get property of array
EXPECT_TRUE(NULL != (prop = data->ensure_property_string("srs_sig")));
ASSERT_TRUE(prop->is_string());
EXPECT_STREQ("srs", prop->to_str().c_str());
}
// confidence about the schema
EXPECT_TRUE(NULL != (prop = info->ensure_property_string("level")));
ASSERT_TRUE(prop->is_string());
EXPECT_STREQ("info", prop->to_str().c_str());
}
// use any to decoding it,
// if user donot know the schema
if (true) {
ASSERT_TRUE(NULL != bytes);
// use SrsStream to assist amf0 object to read from bytes.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
// decoding a amf0 any, for user donot know
SrsAmf0Any* any = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &any));
SrsAutoFree(SrsAmf0Any, any, false);
// for amf0 object
if (any->is_object()) {
SrsAmf0Object* obj = any->to_object();
ASSERT_TRUE(NULL != obj);
// use foreach to process properties
for (int i = 0; i < obj->count(); ++i) {
string name = obj->key_at(i);
SrsAmf0Any* value = obj->value_at(i);
// use the property name
EXPECT_TRUE("" != name);
// use the property value
EXPECT_TRUE(NULL != value);
}
}
}
}
VOID TEST(AMF0Test, ApiSize)
{
// size of elem
EXPECT_EQ(2+6, SrsAmf0Size::utf8("winlin"));
EXPECT_EQ(2+0, SrsAmf0Size::utf8(""));
EXPECT_EQ(1+2+6, SrsAmf0Size::str("winlin"));
EXPECT_EQ(1+2+0, SrsAmf0Size::str(""));
EXPECT_EQ(1+8, SrsAmf0Size::number());
EXPECT_EQ(1, SrsAmf0Size::null());
EXPECT_EQ(1, SrsAmf0Size::undefined());
EXPECT_EQ(1+1, SrsAmf0Size::boolean());
// object: empty
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// object: elem
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
o->set("age", SrsAmf0Any::number(9));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
o->set("email", SrsAmf0Any::null());
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
o->set("email", SrsAmf0Any::undefined());
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
o->set("sex", SrsAmf0Any::boolean(true));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: empty
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// array: elem
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
o->set("age", SrsAmf0Any::number(9));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
o->set("email", SrsAmf0Any::null());
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
o->set("email", SrsAmf0Any::undefined());
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
o->set("sex", SrsAmf0Any::boolean(true));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// object: array
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
SrsAmf0EcmaArray* params = SrsAmf0Any::ecma_array();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::ecma_array(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: object
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
SrsAmf0Object* params = SrsAmf0Any::object();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// object: object
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
SrsAmf0Object* params = SrsAmf0Any::object();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: array
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
SrsAmf0EcmaArray* params = SrsAmf0Any::ecma_array();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::ecma_array(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
}
VOID TEST(AMF0Test, ApiAnyElem)
{
SrsAmf0Any* o = NULL;
// string
if (true) {
o = SrsAmf0Any::str();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_string());
EXPECT_STREQ("", o->to_str().c_str());
}
if (true) {
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_string());
EXPECT_STREQ("winlin", o->to_str().c_str());
}
// bool
if (true) {
o = SrsAmf0Any::boolean();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_FALSE(o->to_boolean());
}
if (true) {
o = SrsAmf0Any::boolean(false);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_FALSE(o->to_boolean());
}
if (true) {
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_TRUE(o->to_boolean());
}
// number
if (true) {
o = SrsAmf0Any::number();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(0, o->to_number());
}
if (true) {
o = SrsAmf0Any::number(100);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(100, o->to_number());
}
if (true) {
o = SrsAmf0Any::number(-100);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(-100, o->to_number());
}
// null
if (true) {
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_null());
}
// undefined
if (true) {
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_undefined());
}
}
VOID TEST(AMF0Test, ApiAnyIO)
{
SrsStream s;
SrsAmf0Any* o = NULL;
char buf[1024];
memset(buf, 0, sizeof(buf));
EXPECT_EQ(ERROR_SUCCESS, s.initialize(buf, sizeof(buf)));
// object eof
if (true) {
s.reset();
s.current()[2] = 0x09;
o = SrsAmf0Any::object_eof();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_EQ(3, s.pos());
s.reset();
s.current()[0] = 0x01;
EXPECT_NE(ERROR_SUCCESS, o->read(&s));
}
if (true) {
s.reset();
o = SrsAmf0Any::object_eof();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_EQ(3, s.pos());
s.skip(-3);
EXPECT_EQ(0x09, s.read_3bytes());
}
// string
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(2, s.read_1bytes());
EXPECT_EQ(6, s.read_2bytes());
EXPECT_EQ('w', s.current()[0]);
EXPECT_EQ('n', s.current()[5]);
s.reset();
s.current()[3] = 'x';
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_STREQ("xinlin", o->to_str().c_str());
}
// number
if (true) {
s.reset();
o = SrsAmf0Any::number(10);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(0, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_DOUBLE_EQ(10, o->to_number());
}
// boolean
if (true) {
s.reset();
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(1, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->to_boolean());
}
if (true) {
s.reset();
o = SrsAmf0Any::boolean(false);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(1, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_FALSE(o->to_boolean());
}
// null
if (true) {
s.reset();
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(5, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->is_null());
}
// undefined
if (true) {
s.reset();
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(6, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->is_undefined());
}
// any: string
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_string());
EXPECT_STREQ("winlin", po->to_str().c_str());
}
// any: number
if (true) {
s.reset();
o = SrsAmf0Any::number(10);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_number());
EXPECT_DOUBLE_EQ(10, po->to_number());
}
// any: boolean
if (true) {
s.reset();
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_boolean());
EXPECT_TRUE(po->to_boolean());
}
// any: null
if (true) {
s.reset();
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_null());
}
// any: undefined
if (true) {
s.reset();
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_undefined());
}
// mixed any
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::number(10);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::boolean(true);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::null();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::undefined();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_string());
EXPECT_STREQ("winlin", po->to_str().c_str());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_number());
EXPECT_DOUBLE_EQ(10, po->to_number());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_boolean());
EXPECT_TRUE(po->to_boolean());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_null());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_undefined());
srs_freep(po);
}
}
VOID TEST(AMF0Test, ApiAnyAssert)
{
SrsStream s;
SrsAmf0Any* o = NULL;
char buf[1024];
memset(buf, 0, sizeof(buf));
EXPECT_EQ(ERROR_SUCCESS, s.initialize(buf, sizeof(buf)));
// read any
if (true) {
s.reset();
s.current()[0] = 0x12;
EXPECT_NE(ERROR_SUCCESS, srs_amf0_read_any(&s, &o));
EXPECT_TRUE(NULL == o);
srs_freep(o);
}
// any convert
if (true) {
o = SrsAmf0Any::str();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_string());
}
if (true) {
o = SrsAmf0Any::number();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_number());
}
if (true) {
o = SrsAmf0Any::boolean();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_boolean());
}
if (true) {
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_null());
}
if (true) {
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_undefined());
}
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_object());
}
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_ecma_array());
}
// empty object
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Any, o, false);
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(1+3, s.pos());
}
// empty ecma array
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0Any, o, false);
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(1+4+3, s.pos());
}
}
VOID TEST(AMF0Test, ApiObjectProps)
{
SrsAmf0Object* o = NULL;
// get/set property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_TRUE(NULL == o->get_property("name"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->get_property("name"));
EXPECT_TRUE(NULL == o->get_property("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->get_property("age"));
}
// index property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
o->set("age", SrsAmf0Any::number(100));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
EXPECT_STREQ("age", o->key_at(1).c_str());
ASSERT_TRUE(o->value_at(1)->is_number());
EXPECT_DOUBLE_EQ(100, o->value_at(1)->to_number());
}
// ensure property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_TRUE(NULL == o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL != o->ensure_property_number("age"));
EXPECT_TRUE(NULL == o->ensure_property_string("age"));
}
// count
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_EQ(0, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("age", SrsAmf0Any::number(100));
EXPECT_EQ(2, o->count());
}
}
VOID TEST(AMF0Test, ApiEcmaArrayProps)
{
SrsAmf0EcmaArray* o = NULL;
// get/set property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_TRUE(NULL == o->get_property("name"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->get_property("name"));
EXPECT_TRUE(NULL == o->get_property("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->get_property("age"));
}
// index property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
o->set("age", SrsAmf0Any::number(100));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
EXPECT_STREQ("age", o->key_at(1).c_str());
ASSERT_TRUE(o->value_at(1)->is_number());
EXPECT_DOUBLE_EQ(100, o->value_at(1)->to_number());
}
// ensure property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_TRUE(NULL == o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL != o->ensure_property_number("age"));
EXPECT_TRUE(NULL == o->ensure_property_string("age"));
}
// count
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_EQ(0, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("age", SrsAmf0Any::number(100));
EXPECT_EQ(2, o->count());
}
}
| wjyadlx/simple-rtmp-server | trunk/src/utest/srs_utest_amf0.cpp | C++ | mit | 32,587 |
#!/usr/bin/env node
'use strict';
/**
* bitcoind.js example
*/
process.title = 'bitcoind.js';
/**
* daemon
*/
var daemon = require('../').daemon({
datadir: process.env.BITCOINDJS_DIR || '~/.bitcoin',
});
daemon.on('ready', function() {
console.log('ready');
});
daemon.on('tx', function(txid) {
console.log('txid', txid);
});
daemon.on('error', function(err) {
daemon.log('error="%s"', err.message);
});
daemon.on('open', function(status) {
daemon.log('status="%s"', status);
});
| bankonme/bitcoind.js | example/index.js | JavaScript | mit | 502 |
package protocol
import (
"crypto/hmac"
"crypto/md5"
"hash"
"v2ray.com/core/common"
"v2ray.com/core/common/uuid"
)
const (
IDBytesLen = 16
)
type IDHash func(key []byte) hash.Hash
func DefaultIDHash(key []byte) hash.Hash {
return hmac.New(md5.New, key)
}
// The ID of en entity, in the form of a UUID.
type ID struct {
uuid uuid.UUID
cmdKey [IDBytesLen]byte
}
// Equals returns true if this ID equals to the other one.
func (id *ID) Equals(another *ID) bool {
return id.uuid.Equals(&(another.uuid))
}
func (id *ID) Bytes() []byte {
return id.uuid.Bytes()
}
func (id *ID) String() string {
return id.uuid.String()
}
func (id *ID) UUID() uuid.UUID {
return id.uuid
}
func (id ID) CmdKey() []byte {
return id.cmdKey[:]
}
// NewID returns an ID with given UUID.
func NewID(uuid uuid.UUID) *ID {
id := &ID{uuid: uuid}
md5hash := md5.New()
common.Must2(md5hash.Write(uuid.Bytes()))
common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21")))
md5hash.Sum(id.cmdKey[:0])
return id
}
func nextID(u *uuid.UUID) uuid.UUID {
md5hash := md5.New()
common.Must2(md5hash.Write(u.Bytes()))
common.Must2(md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")))
var newid uuid.UUID
for {
md5hash.Sum(newid[:0])
if !newid.Equals(u) {
return newid
}
common.Must2(md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")))
}
}
func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
alterIDs := make([]*ID, alterIDCount)
prevID := primary.UUID()
for idx := range alterIDs {
newid := nextID(&prevID)
alterIDs[idx] = NewID(newid)
prevID = newid
}
return alterIDs
}
| LiuWenJu/v2ray-core | common/protocol/id.go | GO | mit | 1,634 |
require 'spec_helper'
RSpec.describe RailsAdmin::Config::Fields::Types::StringLike do
describe '#treat_empty_as_nil?', active_record: true do
context 'with a nullable field' do
subject do
RailsAdmin.config('Team').fields.detect do |f|
f.name == :name
end.with(object: Team.new)
end
it 'is true' do
expect(subject.treat_empty_as_nil?).to be true
end
end
context 'with a non-nullable field' do
subject do
RailsAdmin.config('Team').fields.detect do |f|
f.name == :manager
end.with(object: Team.new)
end
it 'is false' do
expect(subject.treat_empty_as_nil?).to be false
end
end
end
describe '#parse_input' do
subject do
RailsAdmin.config('FieldTest').fields.detect do |f|
f.name == :string_field
end.with(object: FieldTest.new)
end
context 'with treat_empty_as_nil being true' do
before do
RailsAdmin.config FieldTest do
field :string_field do
treat_empty_as_nil true
end
end
end
context 'when value is empty' do
let(:params) { {string_field: ''} }
it 'makes the value nil' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be true
expect(params[:string_field]).to be nil
end
end
context 'when value does not exist in params' do
let(:params) { {} }
it 'does not touch params' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be false
end
end
end
context 'with treat_empty_as_nil being false' do
before do
RailsAdmin.config FieldTest do
field :string_field do
treat_empty_as_nil false
end
end
end
let(:params) { {string_field: ''} }
it 'keeps the value untouched' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be true
expect(params[:string_field]).to eq ''
end
end
end
end
| widgetworks/rails_admin | spec/rails_admin/config/fields/types/string_like_spec.rb | Ruby | mit | 2,109 |
<?php
$TRANSLATIONS = array(
"Shared with you" => "Опубликованы вами",
"Shared with others" => "Опубликованы другими",
"Shared by link" => "Доступно по ссылке",
"No files have been shared with you yet." => "Вы ещё не опубликовали файлы",
"You haven't shared any files yet." => "Вы не имеете файлов в открытом доступе",
"Add {name} from {owner}@{remote}" => "Добавить {name} из {owner}@{remote}",
"Password" => "Пароль",
"Invalid ownCloud url" => "Не верный ownCloud адрес",
"Shared by {owner}" => "Доступ открыл {owner}",
"Shared by" => "Опубликовано",
"This share is password-protected" => "Для доступа к информации необходимо ввести пароль",
"The password is wrong. Try again." => "Неверный пароль. Попробуйте еще раз.",
"Name" => "Имя",
"Share time" => "Дата публикации",
"Sorry, this link doesn’t seem to work anymore." => "Эта ссылка устарела и более не действительна.",
"Reasons might be:" => "Причиной может быть:",
"the item was removed" => "объект был удалён",
"the link expired" => "срок действия ссылки истёк",
"sharing is disabled" => "доступ к информации заблокирован",
"For more info, please ask the person who sent this link." => "Для получения дополнительной информации, пожалуйста, свяжитесь с тем, кто отправил Вам эту ссылку.",
"Save" => "Сохранить",
"Download" => "Скачать",
"Download %s" => "Скачать %s",
"Direct link" => "Прямая ссылка"
);
$PLURAL_FORMS = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);";
| ACOKing/ArcherSys | owncloud-serv/apps/files_sharing/l10n/ru.php | PHP | mit | 1,975 |
<?php
class Node_BreakStmt extends NodeAbstract
{
} | VelvetMirror/test | vendor/bundles/Sensio/Bundle/GeneratorBundle/PHP-Parser/lib/Node/BreakStmt.php | PHP | mit | 52 |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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.
# Check DNSSEC trust chain.
# Todo: verify expiration dates
#
# Based on
# http://backreference.org/2010/11/17/dnssec-verification-with-dig/
# https://github.com/rthalley/dnspython/blob/master/tests/test_dnssec.py
import dns
import dns.name
import dns.query
import dns.dnssec
import dns.message
import dns.resolver
import dns.rdatatype
import dns.rdtypes.ANY.NS
import dns.rdtypes.ANY.CNAME
import dns.rdtypes.ANY.DLV
import dns.rdtypes.ANY.DNSKEY
import dns.rdtypes.ANY.DS
import dns.rdtypes.ANY.NSEC
import dns.rdtypes.ANY.NSEC3
import dns.rdtypes.ANY.NSEC3PARAM
import dns.rdtypes.ANY.RRSIG
import dns.rdtypes.ANY.SOA
import dns.rdtypes.ANY.TXT
import dns.rdtypes.IN.A
import dns.rdtypes.IN.AAAA
from .logging import get_logger
_logger = get_logger(__name__)
# hard-coded trust anchors (root KSKs)
trust_anchors = [
# KSK-2017:
dns.rrset.from_text('.', 1 , 'IN', 'DNSKEY', '257 3 8 AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU='),
# KSK-2010:
dns.rrset.from_text('.', 15202, 'IN', 'DNSKEY', '257 3 8 AwEAAagAIKlVZrpC6Ia7gEzahOR+9W29euxhJhVVLOyQbSEW0O8gcCjF FVQUTf6v58fLjwBd0YI0EzrAcQqBGCzh/RStIoO8g0NfnfL2MTJRkxoX bfDaUeVPQuYEhg37NZWAJQ9VnMVDxP/VHL496M/QZxkjf5/Efucp2gaD X6RS6CXpoY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3LQpz W5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGOYl7OyQdXfZ57relS Qageu+ipAdTTJ25AsRTAoub8ONGcLmqrAmRLKBP1dfwhYB4N7knNnulq QxA+Uk1ihz0='),
]
def _check_query(ns, sub, _type, keys):
q = dns.message.make_query(sub, _type, want_dnssec=True)
response = dns.query.tcp(q, ns, timeout=5)
assert response.rcode() == 0, 'No answer'
answer = response.answer
assert len(answer) != 0, ('No DNS record found', sub, _type)
assert len(answer) != 1, ('No DNSSEC record found', sub, _type)
if answer[0].rdtype == dns.rdatatype.RRSIG:
rrsig, rrset = answer
elif answer[1].rdtype == dns.rdatatype.RRSIG:
rrset, rrsig = answer
else:
raise Exception('No signature set in record')
if keys is None:
keys = {dns.name.from_text(sub):rrset}
dns.dnssec.validate(rrset, rrsig, keys)
return rrset
def _get_and_validate(ns, url, _type):
# get trusted root key
root_rrset = None
for dnskey_rr in trust_anchors:
try:
# Check if there is a valid signature for the root dnskey
root_rrset = _check_query(ns, '', dns.rdatatype.DNSKEY, {dns.name.root: dnskey_rr})
break
except dns.dnssec.ValidationFailure:
# It's OK as long as one key validates
continue
if not root_rrset:
raise dns.dnssec.ValidationFailure('None of the trust anchors found in DNS')
keys = {dns.name.root: root_rrset}
# top-down verification
parts = url.split('.')
for i in range(len(parts), 0, -1):
sub = '.'.join(parts[i-1:])
name = dns.name.from_text(sub)
# If server is authoritative, don't fetch DNSKEY
query = dns.message.make_query(sub, dns.rdatatype.NS)
response = dns.query.udp(query, ns, 3)
assert response.rcode() == dns.rcode.NOERROR, "query error"
rrset = response.authority[0] if len(response.authority) > 0 else response.answer[0]
rr = rrset[0]
if rr.rdtype == dns.rdatatype.SOA:
continue
# get DNSKEY (self-signed)
rrset = _check_query(ns, sub, dns.rdatatype.DNSKEY, None)
# get DS (signed by parent)
ds_rrset = _check_query(ns, sub, dns.rdatatype.DS, keys)
# verify that a signed DS validates DNSKEY
for ds in ds_rrset:
for dnskey in rrset:
htype = 'SHA256' if ds.digest_type == 2 else 'SHA1'
good_ds = dns.dnssec.make_ds(name, dnskey, htype)
if ds == good_ds:
break
else:
continue
break
else:
raise Exception("DS does not match DNSKEY")
# set key for next iteration
keys = {name: rrset}
# get TXT record (signed by zone)
rrset = _check_query(ns, url, _type, keys)
return rrset
def query(url, rtype):
# 8.8.8.8 is Google's public DNS server
nameservers = ['8.8.8.8']
ns = nameservers[0]
try:
out = _get_and_validate(ns, url, rtype)
validated = True
except Exception as e:
_logger.info(f"DNSSEC error: {repr(e)}")
out = dns.resolver.resolve(url, rtype)
validated = False
return out, validated
| wakiyamap/electrum-mona | electrum_mona/dnssec.py | Python | mit | 5,922 |
SS::Application.routes.draw do
Gws::Report::Initializer
concern :deletion do
get :delete, on: :member
delete :destroy_all, on: :collection, path: ''
end
gws 'report' do
get '/' => redirect { |p, req| "#{req.path}/forms" }, as: :setting
resources :forms, concerns: :deletion do
match :publish, on: :member, via: [:get, :post]
match :depublish, on: :member, via: [:get, :post]
resources :columns, concerns: :deletion
end
resources :categories, concerns: [:deletion]
scope :files do
get '/' => redirect { |p, req| "#{req.path}/inbox" }, as: :files_main
resources :trashes, concerns: [:deletion], except: [:new, :create, :edit, :update] do
match :undo_delete, on: :member, via: [:get, :post]
end
resources :files, path: ':state', except: [:destroy] do
get :print, on: :member
match :publish, on: :member, via: [:get, :post]
match :depublish, on: :member, via: [:get, :post]
match :copy, on: :member, via: [:get, :post]
match :soft_delete, on: :member, via: [:get, :post]
post :soft_delete_all, on: :collection
end
resources :files, path: ':state/:form_id', only: [:new, :create], as: 'form_files'
end
namespace 'apis' do
get 'categories' => 'categories#index'
get 'files' => 'files#index'
end
end
end
| itowtips/shirasagi | config/routes/gws/report/routes.rb | Ruby | mit | 1,375 |
var path = require('path');
var util = require('util');
var Item = require('./item');
var constants = process.binding('constants');
/**
* A directory.
* @constructor
*/
function Directory() {
Item.call(this);
/**
* Items in this directory.
* @type {Object.<string, Item>}
*/
this._items = {};
/**
* Permissions.
*/
this._mode = 0777;
}
util.inherits(Directory, Item);
/**
* Add an item to the directory.
* @param {string} name The name to give the item.
* @param {Item} item The item to add.
* @return {Item} The added item.
*/
Directory.prototype.addItem = function(name, item) {
if (this._items.hasOwnProperty(name)) {
throw new Error('Item with the same name already exists: ' + name);
}
this._items[name] = item;
++item.links;
if (item instanceof Directory) {
// for '.' entry
++item.links;
// for subdirectory
++this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get a named item.
* @param {string} name Item name.
* @return {Item} The named item (or null if none).
*/
Directory.prototype.getItem = function(name) {
var item = null;
if (this._items.hasOwnProperty(name)) {
item = this._items[name];
}
return item;
};
/**
* Remove an item.
* @param {string} name Name of item to remove.
* @return {Item} The orphan item.
*/
Directory.prototype.removeItem = function(name) {
if (!this._items.hasOwnProperty(name)) {
throw new Error('Item does not exist in directory: ' + name);
}
var item = this._items[name];
delete this._items[name];
--item.links;
if (item instanceof Directory) {
// for '.' entry
--item.links;
// for subdirectory
--this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get list of item names in this directory.
* @return {Array.<string>} Item names.
*/
Directory.prototype.list = function() {
return Object.keys(this._items).sort();
};
/**
* Get directory stats.
* @return {Object} Stats properties.
*/
Directory.prototype.getStats = function() {
var stats = Item.prototype.getStats.call(this);
stats.mode = this.getMode() | constants.S_IFDIR;
stats.size = 1;
stats.blocks = 1;
return stats;
};
/**
* Export the constructor.
* @type {function()}
*/
exports = module.exports = Directory;
| wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/lib/directory.js | JavaScript | mit | 2,300 |
module MigrationConstraintHelpers
# Creates a foreign key from +table+.+field+ against referenced_table.referenced_field
#
# table: The tablename
# field: A field of the table
# referenced_table: The table which contains the field referenced
# referenced_field: The field (which should be part of the primary key) of the referenced table
# cascade: delete & update on cascade?
def foreign_key(table, field, referenced_table, referenced_field = :id, cascade = true)
execute "ALTER TABLE #{table} ADD CONSTRAINT #{constraint_name(table, field)}
FOREIGN KEY #{constraint_name(table, field)} (#{field_list(field)})
REFERENCES #{referenced_table}(#{field_list(referenced_field)})
#{(cascade ? 'ON DELETE CASCADE ON UPDATE CASCADE' : '')}"
end
# Drops a foreign key from +table+.+field+ that has been created before with
# foreign_key method
#
# table: The table name
# field: A field (or array of fields) of the table
def drop_foreign_key(table, field)
execute "ALTER TABLE #{table} DROP FOREIGN KEY #{constraint_name(table, field)}"
end
# Creates a primary key for +table+, which right now HAS NOT primary key defined
#
# table: The table name
# field: A field (or array of fields) of the table that will be part of the primary key
def primary_key(table, field)
execute "ALTER TABLE #{table} ADD PRIMARY KEY(#{field_list(field)})"
end
private
# Creates a constraint name for table and field given as parameters
#
# table: The table name
# field: A field of the table
def constraint_name(table, field)
"fk_#{table}_#{field_list_name(field)}"
end
def field_list(fields)
fields.is_a?(Array) ? fields.join(',') : fields
end
def field_list_name(fields)
fields.is_a?(Array) ? fields.join('_') : fields
end
end
| beachyapp/standalone-migrations | vendor/migration_helpers/lib/migration_helper.rb | Ruby | mit | 1,887 |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper class for handling XmlHttpRequests.
*
* One off requests can be sent through goog.net.XhrIo.send() or an
* instance can be created to send multiple requests. Each request uses its
* own XmlHttpRequest object and handles clearing of the event callback to
* ensure no leaks.
*
* XhrIo is event based, it dispatches events on success, failure, finishing,
* ready-state change, or progress (download and upload).
*
* The ready-state or timeout event fires first, followed by
* a generic completed event. Then the abort, error, or success event
* is fired as appropriate. Progress events are fired as they are
* received. Lastly, the ready event will fire to indicate that the
* object may be used to make another request.
*
* The error event may also be called before completed and
* ready-state-change if the XmlHttpRequest.open() or .send() methods throw.
*
* This class does not support multiple requests, queuing, or prioritization.
*
* When progress events are supported by the browser, and progress is
* enabled via .setProgressEventsEnabled(true), the
* goog.net.EventType.PROGRESS event will be the re-dispatched browser
* progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event
* will be fired for download and upload progress respectively.
*
*/
goog.provide('goog.net.XhrIo');
goog.provide('goog.net.XhrIo.ResponseType');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug.entryPointRegistry');
goog.require('goog.events.EventTarget');
goog.require('goog.json');
goog.require('goog.log');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.net.HttpStatus');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.structs');
goog.require('goog.structs.Map');
goog.require('goog.uri.utils');
goog.require('goog.userAgent');
goog.forwardDeclare('goog.Uri');
/**
* Basic class for handling XMLHttpRequests.
* @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when
* creating XMLHttpRequest objects.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.net.XhrIo = function(opt_xmlHttpFactory) {
goog.net.XhrIo.base(this, 'constructor');
/**
* Map of default headers to add to every request, use:
* XhrIo.headers.set(name, value)
* @type {!goog.structs.Map}
*/
this.headers = new goog.structs.Map();
/**
* Optional XmlHttpFactory
* @private {goog.net.XmlHttpFactory}
*/
this.xmlHttpFactory_ = opt_xmlHttpFactory || null;
/**
* Whether XMLHttpRequest is active. A request is active from the time send()
* is called until onReadyStateChange() is complete, or error() or abort()
* is called.
* @private {boolean}
*/
this.active_ = false;
/**
* The XMLHttpRequest object that is being used for the transfer.
* @private {?goog.net.XhrLike.OrNative}
*/
this.xhr_ = null;
/**
* The options to use with the current XMLHttpRequest object.
* @private {Object}
*/
this.xhrOptions_ = null;
/**
* Last URL that was requested.
* @private {string|goog.Uri}
*/
this.lastUri_ = '';
/**
* Method for the last request.
* @private {string}
*/
this.lastMethod_ = '';
/**
* Last error code.
* @private {!goog.net.ErrorCode}
*/
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
/**
* Last error message.
* @private {Error|string}
*/
this.lastError_ = '';
/**
* Used to ensure that we don't dispatch an multiple ERROR events. This can
* happen in IE when it does a synchronous load and one error is handled in
* the ready statte change and one is handled due to send() throwing an
* exception.
* @private {boolean}
*/
this.errorDispatched_ = false;
/**
* Used to make sure we don't fire the complete event from inside a send call.
* @private {boolean}
*/
this.inSend_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.open.
* @private {boolean}
*/
this.inOpen_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.abort.
* @private {boolean}
*/
this.inAbort_ = false;
/**
* Number of milliseconds after which an incomplete request will be aborted
* and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout
* is set.
* @private {number}
*/
this.timeoutInterval_ = 0;
/**
* Timer to track request timeout.
* @private {?number}
*/
this.timeoutId_ = null;
/**
* The requested type for the response. The empty string means use the default
* XHR behavior.
* @private {goog.net.XhrIo.ResponseType}
*/
this.responseType_ = goog.net.XhrIo.ResponseType.DEFAULT;
/**
* Whether a "credentialed" request is to be sent (one that is aware of
* cookies and authentication). This is applicable only for cross-domain
* requests and more recent browsers that support this part of the HTTP Access
* Control standard.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute
*
* @private {boolean}
*/
this.withCredentials_ = false;
/**
* Whether progress events are enabled for this request. This is
* disabled by default because setting a progress event handler
* causes pre-flight OPTIONS requests to be sent for CORS requests,
* even in cases where a pre-flight request would not otherwise be
* sent.
*
* @see http://xhr.spec.whatwg.org/#security-considerations
*
* Note that this can cause problems for Firefox 22 and below, as an
* older "LSProgressEvent" will be dispatched by the browser. That
* progress event is no longer supported, and can lead to failures,
* including throwing exceptions.
*
* @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631
* @see b/23469793
*
* @private {boolean}
*/
this.progressEventsEnabled_ = false;
/**
* True if we can use XMLHttpRequest's timeout directly.
* @private {boolean}
*/
this.useXhr2Timeout_ = false;
};
goog.inherits(goog.net.XhrIo, goog.events.EventTarget);
/**
* Response types that may be requested for XMLHttpRequests.
* @enum {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute
*/
goog.net.XhrIo.ResponseType = {
DEFAULT: '',
TEXT: 'text',
DOCUMENT: 'document',
// Not supported as of Chrome 10.0.612.1 dev
BLOB: 'blob',
ARRAY_BUFFER: 'arraybuffer'
};
/**
* A reference to the XhrIo logger
* @private {goog.debug.Logger}
* @const
*/
goog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');
/**
* The Content-Type HTTP header name
* @type {string}
*/
goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';
/**
* The pattern matching the 'http' and 'https' URI schemes
* @type {!RegExp}
*/
goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;
/**
* The methods that typically come along with form data. We set different
* headers depending on whether the HTTP action is one of these.
*/
goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];
/**
* The Content-Type HTTP header value for a url-encoded form
* @type {string}
*/
goog.net.XhrIo.FORM_CONTENT_TYPE =
'application/x-www-form-urlencoded;charset=utf-8';
/**
* The XMLHttpRequest Level two timeout delay ms property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';
/**
* The XMLHttpRequest Level two ontimeout handler property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';
/**
* All non-disposed instances of goog.net.XhrIo created
* by {@link goog.net.XhrIo.send} are in this Array.
* @see goog.net.XhrIo.cleanup
* @private {!Array<!goog.net.XhrIo>}
*/
goog.net.XhrIo.sendInstances_ = [];
/**
* Static send that creates a short lived instance of XhrIo to send the
* request.
* @see goog.net.XhrIo.cleanup
* @param {string|goog.Uri} url Uri to make request to.
* @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function
* for when request is complete.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
* @param {number=} opt_timeoutInterval Number of milliseconds after which an
* incomplete request will be aborted; 0 means no timeout is set.
* @param {boolean=} opt_withCredentials Whether to send credentials with the
* request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.
* @return {!goog.net.XhrIo} The sent XhrIo.
*/
goog.net.XhrIo.send = function(
url, opt_callback, opt_method, opt_content, opt_headers,
opt_timeoutInterval, opt_withCredentials) {
var x = new goog.net.XhrIo();
goog.net.XhrIo.sendInstances_.push(x);
if (opt_callback) {
x.listen(goog.net.EventType.COMPLETE, opt_callback);
}
x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);
if (opt_timeoutInterval) {
x.setTimeoutInterval(opt_timeoutInterval);
}
if (opt_withCredentials) {
x.setWithCredentials(opt_withCredentials);
}
x.send(url, opt_method, opt_content, opt_headers);
return x;
};
/**
* Disposes all non-disposed instances of goog.net.XhrIo created by
* {@link goog.net.XhrIo.send}.
* {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance
* it creates when the request completes or fails. However, if
* the request never completes, then the goog.net.XhrIo is not disposed.
* This can occur if the window is unloaded before the request completes.
* We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo
* it creates and make the client of {@link goog.net.XhrIo.send} be
* responsible for disposing it in this case. However, this makes things
* significantly more complicated for the client, and the whole point
* of {@link goog.net.XhrIo.send} is that it's simple and easy to use.
* Clients of {@link goog.net.XhrIo.send} should call
* {@link goog.net.XhrIo.cleanup} when doing final
* cleanup on window unload.
*/
goog.net.XhrIo.cleanup = function() {
var instances = goog.net.XhrIo.sendInstances_;
while (instances.length) {
instances.pop().dispose();
}
};
/**
* Installs exception protection for all entry point introduced by
* goog.net.XhrIo instances which are not protected by
* {@link goog.debug.ErrorHandler#protectWindowSetTimeout},
* {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or
* {@link goog.events.protectBrowserEventEntryPoint}.
*
* @param {goog.debug.ErrorHandler} errorHandler Error handler with which to
* protect the entry point(s).
*/
goog.net.XhrIo.protectEntryPoints = function(errorHandler) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
errorHandler.protectEntryPoint(
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
};
/**
* Disposes of the specified goog.net.XhrIo created by
* {@link goog.net.XhrIo.send} and removes it from
* {@link goog.net.XhrIo.pendingStaticSendInstances_}.
* @private
*/
goog.net.XhrIo.prototype.cleanupSend_ = function() {
this.dispose();
goog.array.remove(goog.net.XhrIo.sendInstances_, this);
};
/**
* Returns the number of milliseconds after which an incomplete request will be
* aborted, or 0 if no timeout is set.
* @return {number} Timeout interval in milliseconds.
*/
goog.net.XhrIo.prototype.getTimeoutInterval = function() {
return this.timeoutInterval_;
};
/**
* Sets the number of milliseconds after which an incomplete request will be
* aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no
* timeout is set.
* @param {number} ms Timeout interval in milliseconds; 0 means none.
*/
goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {
this.timeoutInterval_ = Math.max(0, ms);
};
/**
* Sets the desired type for the response. At time of writing, this is only
* supported in very recent versions of WebKit (10.0.612.1 dev and later).
*
* If this is used, the response may only be accessed via {@link #getResponse}.
*
* @param {goog.net.XhrIo.ResponseType} type The desired type for the response.
*/
goog.net.XhrIo.prototype.setResponseType = function(type) {
this.responseType_ = type;
};
/**
* Gets the desired type for the response.
* @return {goog.net.XhrIo.ResponseType} The desired type for the response.
*/
goog.net.XhrIo.prototype.getResponseType = function() {
return this.responseType_;
};
/**
* Sets whether a "credentialed" request that is aware of cookie and
* authentication information should be made. This option is only supported by
* browsers that support HTTP Access Control. As of this writing, this option
* is not supported in IE.
*
* @param {boolean} withCredentials Whether this should be a "credentialed"
* request.
*/
goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {
this.withCredentials_ = withCredentials;
};
/**
* Gets whether a "credentialed" request is to be sent.
* @return {boolean} The desired type for the response.
*/
goog.net.XhrIo.prototype.getWithCredentials = function() {
return this.withCredentials_;
};
/**
* Sets whether progress events are enabled for this request. Note
* that progress events require pre-flight OPTIONS request handling
* for CORS requests, and may cause trouble with older browsers. See
* progressEventsEnabled_ for details.
* @param {boolean} enabled Whether progress events should be enabled.
*/
goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {
this.progressEventsEnabled_ = enabled;
};
/**
* Gets whether progress events are enabled.
* @return {boolean} Whether progress events are enabled for this request.
*/
goog.net.XhrIo.prototype.getProgressEventsEnabled = function() {
return this.progressEventsEnabled_;
};
/**
* Instance send that actually uses XMLHttpRequest to make a server call.
* @param {string|goog.Uri} url Uri to make request to.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
*/
goog.net.XhrIo.prototype.send = function(
url, opt_method, opt_content, opt_headers) {
if (this.xhr_) {
throw Error(
'[goog.net.XhrIo] Object is active with another request=' +
this.lastUri_ + '; newUri=' + url);
}
var method = opt_method ? opt_method.toUpperCase() : 'GET';
this.lastUri_ = url;
this.lastError_ = '';
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
this.lastMethod_ = method;
this.errorDispatched_ = false;
this.active_ = true;
// Use the factory to create the XHR object and options
this.xhr_ = this.createXhr();
this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :
goog.net.XmlHttp.getOptions();
// Set up the onreadystatechange callback
this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);
// Set up upload/download progress events, if progress events are supported.
if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {
this.xhr_.onprogress =
goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);
if (this.xhr_.upload) {
this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);
}
}
/**
* Try to open the XMLHttpRequest (always async), if an error occurs here it
* is generally permission denied
* @preserveTry
*/
try {
goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));
this.inOpen_ = true;
this.xhr_.open(method, String(url), true); // Always async!
this.inOpen_ = false;
} catch (err) {
goog.log.fine(
this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
return;
}
// We can't use null since this won't allow requests with form data to have a
// content length specified which will cause some proxies to return a 411
// error.
var content = opt_content || '';
var headers = this.headers.clone();
// Add headers specific to this request
if (opt_headers) {
goog.structs.forEach(
opt_headers, function(value, key) { headers.set(key, value); });
}
// Find whether a content type header is set, ignoring case.
// HTTP header names are case-insensitive. See:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
var contentTypeKey =
goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);
var contentIsFormData =
(goog.global['FormData'] && (content instanceof goog.global['FormData']));
if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&
!contentTypeKey && !contentIsFormData) {
// For requests typically with form data, default to the url-encoded form
// content type unless this is a FormData request. For FormData,
// the browser will automatically add a multipart/form-data content type
// with an appropriate multipart boundary.
headers.set(
goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);
}
// Add the headers to the Xhr object
headers.forEach(function(value, key) {
this.xhr_.setRequestHeader(key, value);
}, this);
if (this.responseType_) {
this.xhr_.responseType = this.responseType_;
}
if (goog.object.containsKey(this.xhr_, 'withCredentials')) {
this.xhr_.withCredentials = this.withCredentials_;
}
/**
* Try to send the request, or other wise report an error (404 not found).
* @preserveTry
*/
try {
this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.
if (this.timeoutInterval_ > 0) {
this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);
goog.log.fine(
this.logger_, this.formatMsg_(
'Will abort after ' + this.timeoutInterval_ +
'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));
if (this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =
goog.bind(this.timeout_, this);
} else {
this.timeoutId_ =
goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);
}
}
goog.log.fine(this.logger_, this.formatMsg_('Sending request'));
this.inSend_ = true;
this.xhr_.send(content);
this.inSend_ = false;
} catch (err) {
goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
}
};
/**
* Determines if the argument is an XMLHttpRequest that supports the level 2
* timeout value and event.
*
* Currently, FF 21.0 OS X has the fields but won't actually call the timeout
* handler. Perhaps the confusion in the bug referenced below hasn't
* entirely been resolved.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816
*
* @param {!goog.net.XhrLike.OrNative} xhr The request.
* @return {boolean} True if the request supports level 2 timeout.
* @private
*/
goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {
return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&
goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&
goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);
};
/**
* @param {string} header An HTTP header key.
* @return {boolean} Whether the key is a content type header (ignoring
* case.
* @private
*/
goog.net.XhrIo.isContentTypeHeader_ = function(header) {
return goog.string.caseInsensitiveEquals(
goog.net.XhrIo.CONTENT_TYPE_HEADER, header);
};
/**
* Creates a new XHR object.
* @return {!goog.net.XhrLike.OrNative} The newly created XHR object.
* @protected
*/
goog.net.XhrIo.prototype.createXhr = function() {
return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :
goog.net.XmlHttp();
};
/**
* The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}
* milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts
* the request.
* @private
*/
goog.net.XhrIo.prototype.timeout_ = function() {
if (typeof goog == 'undefined') {
// If goog is undefined then the callback has occurred as the application
// is unloading and will error. Thus we let it silently fail.
} else if (this.xhr_) {
this.lastError_ =
'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';
this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;
goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));
this.dispatchEvent(goog.net.EventType.TIMEOUT);
this.abort(goog.net.ErrorCode.TIMEOUT);
}
};
/**
* Something errorred, so inactivate, fire error callback and clean up
* @param {goog.net.ErrorCode} errorCode The error code.
* @param {Error} err The error object.
* @private
*/
goog.net.XhrIo.prototype.error_ = function(errorCode, err) {
this.active_ = false;
if (this.xhr_) {
this.inAbort_ = true;
this.xhr_.abort(); // Ensures XHR isn't hung (FF)
this.inAbort_ = false;
}
this.lastError_ = err;
this.lastErrorCode_ = errorCode;
this.dispatchErrors_();
this.cleanUpXhr_();
};
/**
* Dispatches COMPLETE and ERROR in case of an error. This ensures that we do
* not dispatch multiple error events.
* @private
*/
goog.net.XhrIo.prototype.dispatchErrors_ = function() {
if (!this.errorDispatched_) {
this.errorDispatched_ = true;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ERROR);
}
};
/**
* Abort the current XMLHttpRequest
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
* defaults to ABORT.
*/
goog.net.XhrIo.prototype.abort = function(opt_failureCode) {
if (this.xhr_ && this.active_) {
goog.log.fine(this.logger_, this.formatMsg_('Aborting'));
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ABORT);
this.cleanUpXhr_();
}
};
/**
* Nullifies all callbacks to reduce risks of leaks.
* @override
* @protected
*/
goog.net.XhrIo.prototype.disposeInternal = function() {
if (this.xhr_) {
// We explicitly do not call xhr_.abort() unless active_ is still true.
// This is to avoid unnecessarily aborting a successful request when
// dispose() is called in a callback triggered by a complete response, but
// in which browser cleanup has not yet finished.
// (See http://b/issue?id=1684217.)
if (this.active_) {
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
}
this.cleanUpXhr_(true);
}
goog.net.XhrIo.base(this, 'disposeInternal');
};
/**
* Internal handler for the XHR object's readystatechange event. This method
* checks the status and the readystate and fires the correct callbacks.
* If the request has ended, the handlers are cleaned up and the XHR object is
* nullified.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChange_ = function() {
if (this.isDisposed()) {
// This method is the target of an untracked goog.Timer.callOnce().
return;
}
if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {
// Were not being called from within a call to this.xhr_.send
// this.xhr_.abort, or this.xhr_.open, so this is an entry point
this.onReadyStateChangeEntryPoint_();
} else {
this.onReadyStateChangeHelper_();
}
};
/**
* Used to protect the onreadystatechange handler entry point. Necessary
* as {#onReadyStateChange_} maybe called from within send or abort, this
* method is only called when {#onReadyStateChange_} is called as an
* entry point.
* {@see #protectEntryPoints}
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {
this.onReadyStateChangeHelper_();
};
/**
* Helper for {@link #onReadyStateChange_}. This is used so that
* entry point calls to {@link #onReadyStateChange_} can be routed through
* {@link #onReadyStateChangeEntryPoint_}.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {
if (!this.active_) {
// can get called inside abort call
return;
}
if (typeof goog == 'undefined') {
// NOTE(user): If goog is undefined then the callback has occurred as the
// application is unloading and will error. Thus we let it silently fail.
} else if (
this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&
this.getStatus() == 2) {
// NOTE(user): In IE if send() errors on a *local* request the readystate
// is still changed to COMPLETE. We need to ignore it and allow the
// try/catch around send() to pick up the error.
goog.log.fine(
this.logger_,
this.formatMsg_('Local request error detected and ignored'));
} else {
// In IE when the response has been cached we sometimes get the callback
// from inside the send call and this usually breaks code that assumes that
// XhrIo is asynchronous. If that is the case we delay the callback
// using a timer.
if (this.inSend_ &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {
goog.Timer.callOnce(this.onReadyStateChange_, 0, this);
return;
}
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
// readyState indicates the transfer has finished
if (this.isComplete()) {
goog.log.fine(this.logger_, this.formatMsg_('Request complete'));
this.active_ = false;
try {
// Call the specific callbacks for success or failure. Only call the
// success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)
if (this.isSuccess()) {
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.SUCCESS);
} else {
this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;
this.lastError_ =
this.getStatusText() + ' [' + this.getStatus() + ']';
this.dispatchErrors_();
}
} finally {
this.cleanUpXhr_();
}
}
}
};
/**
* Internal handler for the XHR object's onprogress event. Fires both a generic
* PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to
* allow specific binding for each XHR progress event.
* @param {!ProgressEvent} e XHR progress event.
* @param {boolean=} opt_isDownload Whether the current progress event is from a
* download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS
* event should be dispatched.
* @private
*/
goog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {
goog.asserts.assert(
e.type === goog.net.EventType.PROGRESS,
'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(
e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :
goog.net.EventType.UPLOAD_PROGRESS));
};
/**
* Creates a representation of the native ProgressEvent. IE doesn't support
* constructing ProgressEvent via "new", and the alternatives (e.g.,
* ProgressEvent.initProgressEvent) are non-standard or deprecated.
* @param {!ProgressEvent} e XHR progress event.
* @param {!goog.net.EventType} eventType The type of the event.
* @return {!ProgressEvent} The progress event.
* @private
*/
goog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {
return /** @type {!ProgressEvent} */ ({
type: eventType,
lengthComputable: e.lengthComputable,
loaded: e.loaded,
total: e.total
});
};
/**
* Remove the listener to protect against leaks, and nullify the XMLHttpRequest
* object.
* @param {boolean=} opt_fromDispose If this is from the dispose (don't want to
* fire any events).
* @private
*/
goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {
if (this.xhr_) {
// Cancel any pending timeout event handler.
this.cleanUpTimeoutTimer_();
// Save reference so we can mark it as closed after the READY event. The
// READY event may trigger another request, thus we must nullify this.xhr_
var xhr = this.xhr_;
var clearedOnReadyStateChange =
this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?
goog.nullFunction :
null;
this.xhr_ = null;
this.xhrOptions_ = null;
if (!opt_fromDispose) {
this.dispatchEvent(goog.net.EventType.READY);
}
try {
// NOTE(user): Not nullifying in FireFox can still leak if the callbacks
// are defined in the same scope as the instance of XhrIo. But, IE doesn't
// allow you to set the onreadystatechange to NULL so nullFunction is
// used.
xhr.onreadystatechange = clearedOnReadyStateChange;
} catch (e) {
// This seems to occur with a Gears HTTP request. Delayed the setting of
// this onreadystatechange until after READY is sent out and catching the
// error to see if we can track down the problem.
goog.log.error(
this.logger_,
'Problem encountered resetting onreadystatechange: ' + e.message);
}
}
};
/**
* Make sure the timeout timer isn't running.
* @private
*/
goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {
if (this.xhr_ && this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;
}
if (goog.isNumber(this.timeoutId_)) {
goog.Timer.clear(this.timeoutId_);
this.timeoutId_ = null;
}
};
/**
* @return {boolean} Whether there is an active request.
*/
goog.net.XhrIo.prototype.isActive = function() {
return !!this.xhr_;
};
/**
* @return {boolean} Whether the request has completed.
*/
goog.net.XhrIo.prototype.isComplete = function() {
return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;
};
/**
* @return {boolean} Whether the request completed with a success.
*/
goog.net.XhrIo.prototype.isSuccess = function() {
var status = this.getStatus();
// A zero status code is considered successful for local files.
return goog.net.HttpStatus.isSuccess(status) ||
status === 0 && !this.isLastUriEffectiveSchemeHttp_();
};
/**
* @return {boolean} whether the effective scheme of the last URI that was
* fetched was 'http' or 'https'.
* @private
*/
goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {
var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));
return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);
};
/**
* Get the readystate from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.
*/
goog.net.XhrIo.prototype.getReadyState = function() {
return this.xhr_ ?
/** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :
goog.net.XmlHttp.ReadyState
.UNINITIALIZED;
};
/**
* Get the status from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {number} Http status.
*/
goog.net.XhrIo.prototype.getStatus = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.status :
-1;
} catch (e) {
return -1;
}
};
/**
* Get the status text from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {string} Status text.
*/
goog.net.XhrIo.prototype.getStatusText = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.statusText :
'';
} catch (e) {
goog.log.fine(this.logger_, 'Can not get status: ' + e.message);
return '';
}
};
/**
* Get the last Uri that was requested
* @return {string} Last Uri.
*/
goog.net.XhrIo.prototype.getLastUri = function() {
return String(this.lastUri_);
};
/**
* Get the response text from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {string} Result from the server, or '' if no result available.
*/
goog.net.XhrIo.prototype.getResponseText = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseText : '';
} catch (e) {
// http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
// states that responseText should return '' (and responseXML null)
// when the state is not LOADING or DONE. Instead, IE can
// throw unexpected exceptions, for example when a request is aborted
// or no data is available yet.
goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);
return '';
}
};
/**
* Get the response body from the Xhr object. This property is only available
* in IE since version 7 according to MSDN:
* http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx
* Will only return correct result when called from the context of a callback.
*
* One option is to construct a VBArray from the returned object and convert
* it to a JavaScript array using the toArray method:
* {@code (new window['VBArray'](xhrIo.getResponseBody())).toArray()}
* This will result in an array of numbers in the range of [0..255]
*
* Another option is to use the VBScript CStr method to convert it into a
* string as outlined in http://stackoverflow.com/questions/1919972
*
* @return {Object} Binary result from the server or null if not available.
*/
goog.net.XhrIo.prototype.getResponseBody = function() {
/** @preserveTry */
try {
if (this.xhr_ && 'responseBody' in this.xhr_) {
return this.xhr_['responseBody'];
}
} catch (e) {
// IE can throw unexpected exceptions, for example when a request is aborted
// or no data is yet available.
goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);
}
return null;
};
/**
* Get the response XML from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {Document} The DOM Document representing the XML file, or null
* if no result available.
*/
goog.net.XhrIo.prototype.getResponseXml = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseXML : null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);
return null;
}
};
/**
* Get the response and evaluates it as JSON from the Xhr object
* Will only return correct result when called from the context of a callback
* @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for
* stripping of the response before parsing. This needs to be set only if
* your backend server prepends the same prefix string to the JSON response.
* @return {Object|undefined} JavaScript object.
*/
goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {
if (!this.xhr_) {
return undefined;
}
var responseText = this.xhr_.responseText;
if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {
responseText = responseText.substring(opt_xssiPrefix.length);
}
return goog.json.parse(responseText);
};
/**
* Get the response as the type specificed by {@link #setResponseType}. At time
* of writing, this is only directly supported in very recent versions of WebKit
* (10.0.612.1 dev and later). If the field is not supported directly, we will
* try to emulate it.
*
* Emulating the response means following the rules laid out at
* http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute
*
* On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only
* response types of DEFAULT or TEXT may be used, and the response returned will
* be the text response.
*
* On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),
* only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the
* response returned will be either the text response or the Mozilla
* implementation of the array buffer response.
*
* On browsers will full support, any valid response type supported by the
* browser may be used, and the response provided by the browser will be
* returned.
*
* @return {*} The response.
*/
goog.net.XhrIo.prototype.getResponse = function() {
/** @preserveTry */
try {
if (!this.xhr_) {
return null;
}
if ('response' in this.xhr_) {
return this.xhr_.response;
}
switch (this.responseType_) {
case goog.net.XhrIo.ResponseType.DEFAULT:
case goog.net.XhrIo.ResponseType.TEXT:
return this.xhr_.responseText;
// DOCUMENT and BLOB don't need to be handled here because they are
// introduced in the same spec that adds the .response field, and would
// have been caught above.
// ARRAY_BUFFER needs an implementation for Firefox 4, where it was
// implemented using a draft spec rather than the final spec.
case goog.net.XhrIo.ResponseType.ARRAY_BUFFER:
if ('mozResponseArrayBuffer' in this.xhr_) {
return this.xhr_.mozResponseArrayBuffer;
}
}
// Fell through to a response type that is not supported on this browser.
goog.log.error(
this.logger_, 'Response type ' + this.responseType_ + ' is not ' +
'supported on this browser');
return null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get response: ' + e.message);
return null;
}
};
/**
* Get the value of the response-header with the given name from the Xhr object
* Will only return correct result when called from the context of a callback
* and the request has completed
* @param {string} key The name of the response-header to retrieve.
* @return {string|undefined} The value of the response-header named key.
*/
goog.net.XhrIo.prototype.getResponseHeader = function(key) {
return this.xhr_ && this.isComplete() ? this.xhr_.getResponseHeader(key) :
undefined;
};
/**
* Gets the text of all the headers in the response.
* Will only return correct result when called from the context of a callback
* and the request has completed.
* @return {string} The value of the response headers or empty string.
*/
goog.net.XhrIo.prototype.getAllResponseHeaders = function() {
return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() :
'';
};
/**
* Returns all response headers as a key-value map.
* Multiple values for the same header key can be combined into one,
* separated by a comma and a space.
* Note that the native getResponseHeader method for retrieving a single header
* does a case insensitive match on the header name. This method does not
* include any case normalization logic, it will just return a key-value
* representation of the headers.
* See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
* @return {!Object<string, string>} An object with the header keys as keys
* and header values as values.
*/
goog.net.XhrIo.prototype.getResponseHeaders = function() {
var headersObject = {};
var headersArray = this.getAllResponseHeaders().split('\r\n');
for (var i = 0; i < headersArray.length; i++) {
if (goog.string.isEmptyOrWhitespace(headersArray[i])) {
continue;
}
var keyValue = goog.string.splitLimit(headersArray[i], ': ', 2);
if (headersObject[keyValue[0]]) {
headersObject[keyValue[0]] += ', ' + keyValue[1];
} else {
headersObject[keyValue[0]] = keyValue[1];
}
}
return headersObject;
};
/**
* Get the last error message
* @return {goog.net.ErrorCode} Last error code.
*/
goog.net.XhrIo.prototype.getLastErrorCode = function() {
return this.lastErrorCode_;
};
/**
* Get the last error message
* @return {string} Last error message.
*/
goog.net.XhrIo.prototype.getLastError = function() {
return goog.isString(this.lastError_) ? this.lastError_ :
String(this.lastError_);
};
/**
* Adds the last method, status and URI to the message. This is used to add
* this information to the logging calls.
* @param {string} msg The message text that we want to add the extra text to.
* @return {string} The message with the extra text appended.
* @private
*/
goog.net.XhrIo.prototype.formatMsg_ = function(msg) {
return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +
this.getStatus() + ']';
};
// Register the xhr handler as an entry point, so that
// it can be monitored for exception handling, etc.
goog.debug.entryPointRegistry.register(
/**
* @param {function(!Function): !Function} transformer The transforming
* function.
*/
function(transformer) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
});
| cbetheridge/simpleclassroom | static/third-party/closure-library/closure/goog/net/xhrio.js | JavaScript | mit | 43,124 |
package ranrotb
// Call with seed and it will return a closure
// which will return pseudo-random numbers on
// consecutive calls
// Note: seed could be uint32(time.Now().Unix())
func rrbRand(seed uint32) func() uint32 {
var lo, hi uint32
// In Go ^ is the bitwise complement operator
// In C this would be the tilde (~)
lo, hi = seed, ^seed
return func() uint32 {
hi = (hi << 16) + (lo >> 16)
hi += lo
lo += hi
return hi
}
}
| n1ghtmare/Algorithm-Implementations | Ranrot-B-Pseudo_Random_Number_Generator/Go/jcla1/ranrotb_prng.go | GO | mit | 443 |
package ru.atom.model.dao;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.atom.model.data.Match;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class MatchDao implements Dao<Match> {
private static final Logger log = LogManager.getLogger(MatchDao.class);
@Override
public List<Match> getAll() {
throw new NotImplementedException();
}
@Override
public List<Match> getAllWhere(String... hqlConditions) {
throw new NotImplementedException();
}
@Override
public void insert(Match match) {
}
}
| Bragaman/atom | lecture6/source/src/main/java/ru/atom/model/dao/MatchDao.java | Java | mit | 737 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.engine.rmi;
/**
* @author heraldkllapi
*/
public class OptimizerConstants {
public static boolean USE_SKETCH = false;
public static int MAX_TABLE_PARTS = 2;
}
| XristosMallios/cache | exareme-master/src/main/java/madgik/exareme/master/engine/rmi/OptimizerConstants.java | Java | mit | 248 |
'use strict';
const Code = require('code');
const Constants = require('../../../../../../client/pages/admin/statuses/search/constants');
const FluxConstant = require('flux-constant');
const Lab = require('lab');
const Proxyquire = require('proxyquire');
const lab = exports.lab = Lab.script();
const stub = {
ApiActions: {
get: function () {
stub.ApiActions.get.mock.apply(null, arguments);
},
post: function () {
stub.ApiActions.post.mock.apply(null, arguments);
}
},
Store: {
dispatch: function () {
stub.Store.dispatch.mock.apply(null, arguments);
}
},
ReactRouter: {
browserHistory: {
push: () => {},
replace: () => {}
}
}
};
const Actions = Proxyquire('../../../../../../client/pages/admin/statuses/search/actions', {
'../../../../actions/api': stub.ApiActions,
'./store': stub.Store,
'react-router': stub.ReactRouter
});
lab.experiment('Admin Statuses Search Actions', () => {
lab.test('it calls ApiActions.get from getResults', (done) => {
stub.ApiActions.get.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.not.exist();
done();
};
Actions.getResults({});
});
lab.test('it calls browserHistory.push from changeSearchQuery', (done) => {
const scrollTo = global.window.scrollTo;
global.window.scrollTo = function () {
global.window.scrollTo = scrollTo;
done();
};
stub.ReactRouter.browserHistory.push = function (config) {
stub.ReactRouter.browserHistory.push = () => {};
Code.expect(config.pathname).to.be.a.string();
Code.expect(config.query).to.be.an.object();
};
Actions.changeSearchQuery({});
});
lab.test('it calls dispatch from showCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.SHOW_CREATE_NEW) {
done();
}
};
Actions.showCreateNew();
});
lab.test('it calls dispatch from hideCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.HIDE_CREATE_NEW) {
done();
}
};
Actions.hideCreateNew();
});
lab.test('it calls ApiActions.post from createNew (success)', (done) => {
stub.Store.dispatch.mock = () => {};
stub.ReactRouter.browserHistory.replace = function (location) {
stub.ReactRouter.browserHistory.replace = () => {};
Code.expect(location).to.be.an.object();
done();
};
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(null, {});
};
Actions.createNew({});
});
lab.test('it calls ApiActions.post from createNew (failure)', (done) => {
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(new Error('sorry pal'));
done();
};
Actions.createNew({});
});
});
| fahidRM/aqua-couch-test | test/client/pages/admin/statuses/search/actions.js | JavaScript | mit | 4,225 |
version https://git-lfs.github.com/spec/v1
oid sha256:3e7e8daeb7e94086c854616e881862ffc0555684031d339b30c0b67afa82b530
size 492
| yogeshsaroya/new-cdnjs | ajax/libs/bootstrap-datepicker/1.2.0-rc.1/js/locales/bootstrap-datepicker.et.min.js | JavaScript | mit | 128 |
import { getCell, getColumnByCell, getRowIdentity } from './util';
import ElCheckbox from 'element-ui/packages/checkbox';
export default {
components: {
ElCheckbox
},
props: {
store: {
required: true
},
context: {},
layout: {
required: true
},
rowClassName: [String, Function],
rowStyle: [Object, Function],
fixed: String,
highlight: Boolean
},
render(h) {
const columnsHidden = this.columns.map((column, index) => this.isColumnHidden(index));
return (
<table
class="el-table__body"
cellspacing="0"
cellpadding="0"
border="0">
<colgroup>
{
this._l(this.columns, column =>
<col
name={ column.id }
width={ column.realWidth || column.width }
/>)
}
</colgroup>
<tbody>
{
this._l(this.data, (row, $index) =>
[<tr
style={ this.rowStyle ? this.getRowStyle(row, $index) : null }
key={ this.table.rowKey ? this.getKeyOfRow(row, $index) : $index }
on-dblclick={ ($event) => this.handleDoubleClick($event, row) }
on-click={ ($event) => this.handleClick($event, row) }
on-contextmenu={ ($event) => this.handleContextMenu($event, row) }
on-mouseenter={ _ => this.handleMouseEnter($index) }
on-mouseleave={ _ => this.handleMouseLeave() }
class={ [this.getRowClass(row, $index)] }>
{
this._l(this.columns, (column, cellIndex) =>
<td
class={ [column.id, column.align, column.className || '', columnsHidden[cellIndex] ? 'is-hidden' : '' ] }
on-mouseenter={ ($event) => this.handleCellMouseEnter($event, row) }
on-mouseleave={ this.handleCellMouseLeave }>
{
column.renderCell.call(this._renderProxy, h, { row, column, $index, store: this.store, _self: this.context || this.table.$vnode.context }, columnsHidden[cellIndex])
}
</td>
)
}
{
!this.fixed && this.layout.scrollY && this.layout.gutterWidth ? <td class="gutter" /> : ''
}
</tr>,
this.store.states.expandRows.indexOf(row) > -1
? (<tr>
<td colspan={ this.columns.length } class="el-table__expanded-cell">
{ this.table.renderExpanded ? this.table.renderExpanded(h, { row, $index, store: this.store }) : ''}
</td>
</tr>)
: ''
]
)
}
</tbody>
</table>
);
},
watch: {
'store.states.hoverRow'(newVal, oldVal) {
if (!this.store.states.isComplex) return;
const el = this.$el;
if (!el) return;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[oldVal];
const newRow = rows[newVal];
if (oldRow) {
oldRow.classList.remove('hover-row');
}
if (newRow) {
newRow.classList.add('hover-row');
}
},
'store.states.currentRow'(newVal, oldVal) {
if (!this.highlight) return;
const el = this.$el;
if (!el) return;
const data = this.store.states.data;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[data.indexOf(oldVal)];
const newRow = rows[data.indexOf(newVal)];
if (oldRow) {
oldRow.classList.remove('current-row');
} else if (rows) {
[].forEach.call(rows, row => row.classList.remove('current-row'));
}
if (newRow) {
newRow.classList.add('current-row');
}
}
},
computed: {
table() {
return this.$parent;
},
data() {
return this.store.states.data;
},
columnsCount() {
return this.store.states.columns.length;
},
leftFixedCount() {
return this.store.states.fixedColumns.length;
},
rightFixedCount() {
return this.store.states.rightFixedColumns.length;
},
columns() {
return this.store.states.columns;
}
},
data() {
return {
tooltipDisabled: true
};
},
methods: {
getKeyOfRow(row, index) {
const rowKey = this.table.rowKey;
if (rowKey) {
return getRowIdentity(row, rowKey);
}
return index;
},
isColumnHidden(index) {
if (this.fixed === true || this.fixed === 'left') {
return index >= this.leftFixedCount;
} else if (this.fixed === 'right') {
return index < this.columnsCount - this.rightFixedCount;
} else {
return (index < this.leftFixedCount) || (index >= this.columnsCount - this.rightFixedCount);
}
},
getRowStyle(row, index) {
const rowStyle = this.rowStyle;
if (typeof rowStyle === 'function') {
return rowStyle.call(null, row, index);
}
return rowStyle;
},
getRowClass(row, index) {
const classes = [];
const rowClassName = this.rowClassName;
if (typeof rowClassName === 'string') {
classes.push(rowClassName);
} else if (typeof rowClassName === 'function') {
classes.push(rowClassName.call(null, row, index) || '');
}
return classes.join(' ');
},
handleCellMouseEnter(event, row) {
const table = this.table;
const cell = getCell(event);
if (cell) {
const column = getColumnByCell(table, cell);
const hoverState = table.hoverState = {cell, column, row};
table.$emit('cell-mouse-enter', hoverState.row, hoverState.column, hoverState.cell, event);
}
// 判断是否text-overflow, 如果是就显示tooltip
const cellChild = event.target.querySelector('.cell');
this.tooltipDisabled = cellChild.scrollWidth <= cellChild.offsetWidth;
},
handleCellMouseLeave(event) {
const cell = getCell(event);
if (!cell) return;
const oldHoverState = this.table.hoverState;
this.table.$emit('cell-mouse-leave', oldHoverState.row, oldHoverState.column, oldHoverState.cell, event);
},
handleMouseEnter(index) {
this.store.commit('setHoverRow', index);
},
handleMouseLeave() {
this.store.commit('setHoverRow', null);
},
handleContextMenu(event, row) {
this.handleEvent(event, row, 'contextmenu');
},
handleDoubleClick(event, row) {
this.handleEvent(event, row, 'dblclick');
},
handleClick(event, row) {
this.store.commit('setCurrentRow', row);
this.handleEvent(event, row, 'click');
},
handleEvent(event, row, name) {
const table = this.table;
const cell = getCell(event);
let column;
if (cell) {
column = getColumnByCell(table, cell);
if (column) {
table.$emit(`cell-${name}`, row, column, cell, event);
}
}
table.$emit(`row-${name}`, row, event, column);
},
handleExpandClick(row) {
this.store.commit('toggleRowExpanded', row);
}
}
};
| imyzf/element | packages/table/src/table-body.js | JavaScript | mit | 7,259 |
using System;
using NBitcoin;
namespace Stratis.Bitcoin.Features.BlockStore.Pruning
{
/// <summary>
/// This service starts an async loop task that periodically deletes from the blockstore.
/// <para>
/// If the height of the node's block store is more than <see cref="PruneBlockStoreService.MaxBlocksToKeep"/>, the node will
/// be pruned, leaving a margin of <see cref="PruneBlockStoreService.MaxBlocksToKeep"/> in the block database.
/// </para>
/// <para>
/// For example if the block store's height is 5000, the node will be pruned up to height 4000, meaning that 1000 blocks will be kept on disk.
/// </para>
/// </summary>
public interface IPruneBlockStoreService : IDisposable
{
/// <summary>
/// This is the header of where the node has been pruned up to.
/// <para>
/// It should be noted that deleting (pruning) blocks from the repository only removes the reference, it does not decrease the actual size on disk.
/// </para>
/// </summary>
ChainedHeader PrunedUpToHeaderTip { get; }
/// <summary>
/// Starts an async loop task that periodically deletes from the blockstore.
/// </summary>
void Initialize();
/// <summary>
/// Delete blocks continuously from the back of the store.
/// </summary>
void PruneBlocks();
}
}
| Neurosploit/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.BlockStore/Pruning/IPruneBlockStoreService.cs | C# | mit | 1,414 |
var searchData=
[
['w',['w',['../structedda_1_1dist_1_1GMMTuple.html#a3f52857178189dcb76b5132a60c0a50a',1,'edda::dist::GMMTuple']]],
['weights',['weights',['../classedda_1_1dist_1_1JointGMM.html#a479a4af061d7414da3a2b42df3f2e87f',1,'edda::dist::JointGMM']]],
['width',['width',['../structBMPImage.html#a35875dd635eb414965fd87e169b8fb25',1,'BMPImage']]]
];
| GRAVITYLab/edda | html/search/variables_15.js | JavaScript | mit | 362 |
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// support friendly urls for files within the application
$path = $request->path();
if(strpos($path, 'sites/') !== FALSE) {
if(strpos($path, '.html') === FALSE) {
$file = app()->basePath('public/'.$path.'.html');
if(file_exists($file)) {
return file_get_contents($file);
}
}
}
return parent::render($request, $e);
}
}
| OnekO/respond | app/Exceptions/Handler.php | PHP | mit | 1,610 |
package org.spongycastle;
/**
* The Bouncy Castle License
*
* Copyright (c) 2000-2015 The Legion Of The Bouncy Castle Inc. (http://www.bouncycastle.org)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
* <p>
* 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.
*/
public class LICENSE
{
public static String licenseText =
"Copyright (c) 2000-2015 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) "
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "Permission is hereby granted, free of charge, to any person obtaining a copy of this software "
+ System.getProperty("line.separator")
+ "and associated documentation files (the \"Software\"), to deal in the Software without restriction, "
+ System.getProperty("line.separator")
+ "including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, "
+ System.getProperty("line.separator")
+ "and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,"
+ System.getProperty("line.separator")
+ "subject to the following conditions:"
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "The above copyright notice and this permission notice shall be included in all copies or substantial"
+ System.getProperty("line.separator")
+ "portions of the Software."
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,"
+ System.getProperty("line.separator")
+ "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR"
+ System.getProperty("line.separator")
+ "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE"
+ System.getProperty("line.separator")
+ "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR"
+ System.getProperty("line.separator")
+ "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER"
+ System.getProperty("line.separator")
+ "DEALINGS IN THE SOFTWARE.";
public static void main(
String[] args)
{
System.out.println(licenseText);
}
}
| savichris/spongycastle | core/src/main/java/org/spongycastle/LICENSE.java | Java | mit | 3,397 |
<?php
namespace Kanboard\Controller;
use Kanboard\Core\ExternalTask\ExternalTaskException;
/**
* Class ExternalTaskViewController
*
* @package Kanboard\Controller
* @author Frederic Guillot
*/
class ExternalTaskViewController extends BaseController
{
public function show()
{
try {
$task = $this->getTask();
$taskProvider = $this->externalTaskManager->getProvider($task['external_provider']);
$externalTask = $taskProvider->fetch($task['external_uri'], $task['project_id']);
$this->response->html($this->template->render($taskProvider->getViewTemplate(), array(
'task' => $task,
'external_task' => $externalTask,
)));
} catch (ExternalTaskException $e) {
$this->response->html('<div class="alert alert-error">'.$e->getMessage().'</div>');
}
}
}
| libin/kanboard | app/Controller/ExternalTaskViewController.php | PHP | mit | 895 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
/**
* Various custom line cap types
*/
internal enum CustomLineCapType
{
Default = 0,
AdjustableArrowCap = 1
}
}
| dotnet-bot/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/CustomLineCapType.cs | C# | mit | 396 |
var Data = {};
Data.matrix = {
valueName: 'Wert',
stakeholdersName : 'Berührungs​gruppe',
negativeCriteriaName : 'Negativ-Kriterien',
values : [
'Menschen​würde',
'Solidarität',
'Ökologische Nachhaltigkeit',
'Soziale Gerechtigkeit',
'Demokratische Mitbestimmung & Transparenz'
],
stakeholders : [
{
shortcode : 'A',
name: 'Lieferant​Innen',
values: [
{
shortcode : 'A1',
shortcodeSlug : 'a1',
title: 'Ethisches Beschaffungsmanagement',
content: 'Aktive Auseinandersetzung mit den Risiken zugekaufter Produkte / Dienstleistungen, Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl von LieferantInnen und DienstleistungsnehmerInnen.',
points: 90,
soleProprietorship: true
}
]
},
{
shortcode : 'B',
name: 'Geldgeber​Innen',
values: [
{
shortcode : 'B1',
shortcodeSlug : 'b1',
title: 'Ethisches Finanzmanagement',
content: 'Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl der Finanzdienstleistungen; gemeinwohlorienterte Veranlagung und Finanzierung',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'C',
name: 'Mitarbeiter​Innen inklusive Eigentümer​Innen',
values: [
{
shortcode : 'C1',
shortcodeSlug : 'c1',
title: 'Arbeitsplatz​qualität und Gleichstellung',
content: 'Mitarbeiter​orientierte Organisations-kultur und –strukturen, Faire Beschäftigungs- und Entgeltpolitik, Arbeitsschutz und Gesundheits​förderung einschließlich Work-Life-Balance/flexible Arbeitszeiten, Gleichstellung und Diversität',
points: 90,
soleProprietorship: true
},
{
shortcode : 'C2',
shortcodeSlug : 'c2',
title: 'Gerechte Verteilung der Erwerbsarbeit',
content: 'Abbau von Überstunden, Verzicht auf All-inclusive-Verträge, Reduktion der Regelarbeitszeit, Beitrag zur Reduktion der Arbeitslosigkeit',
points: 50,
soleProprietorship: true
},
{
shortcode : 'C3',
shortcodeSlug : 'c3',
title: 'Förderung ökologischen Verhaltens der Mitarbeiter​Innen',
content: 'Aktive Förderung eines nachhaltigen Lebensstils der MitarbeiterInnen (Mobilität, Ernährung), Weiterbildung und Bewusstsein schaffende Maßnahmen, nachhaltige Organisationskultur',
points: 30,
soleProprietorship: true
},
{
shortcode : 'C4',
shortcodeSlug : 'c4',
title: 'Gerechte Verteilung des Einkommens',
content: 'Geringe innerbetriebliche Einkommens​spreizung (netto), Einhaltung von Mindest​einkommen und Höchst​einkommen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'C5',
shortcodeSlug : 'c5',
title: 'Inner​betriebliche Demokratie und Transparenz',
content: 'Umfassende innerbetriebliche Transparenz, Wahl der Führungskräfte durch die Mitarbeiter, konsensuale Mitbestimmung bei Grundsatz- und Rahmen​entscheidungen, Übergabe Eigentum an MitarbeiterInnen. Z.B. Soziokratie',
points: 90,
soleProprietorship: false
}
]
},
{
shortcode : 'D',
name: 'KundInnen / Produkte / Dienst​leistungen / Mit​unternehmen',
values: [
{
shortcode : 'D1',
shortcodeSlug : 'd1',
title: 'Ethische Kunden​beziehung',
content: 'Ethischer Umgang mit KundInnen, KundInnen​orientierung/ - mitbestimmung, gemeinsame Produkt​entwicklung, hohe Servicequalität, hohe Produkt​transparenz',
points: 50,
soleProprietorship: true
},
{
shortcode : 'D2',
shortcodeSlug : 'd2',
title: 'Solidarität mit Mit​unternehmen',
content: 'Weitergabe von Information, Know-how, Arbeitskräften, Aufträgen, zinsfreien Krediten; Beteiligung an kooperativem Marketing und kooperativer Krisenbewältigung',
points: 70,
soleProprietorship: true
},
{
shortcode : 'D3',
shortcodeSlug : 'd3',
title: 'Ökologische Gestaltung der Produkte und Dienst​leistungen',
content: 'Angebot ökologisch höherwertiger Produkte / Dienstleistungen; Bewusstsein schaffende Maßnahmen; Berücksichtigung ökologischer Aspekte bei der KundInnenwahl',
points: 90,
soleProprietorship: true
},
{
shortcode : 'D4',
shortcodeSlug : 'd4',
title: 'Soziale Gestaltung der Produkte und Dienst​leistungen',
content: 'Informationen / Produkten / Dienstleistungen für benachteiligte KundInnen-Gruppen. Unterstützung förderungs​würdiger Marktstrukturen.',
points: 30,
soleProprietorship: true
},
{
shortcode : 'D5',
shortcodeSlug : 'd5',
title: 'Erhöhung der sozialen und ökologischen Branchen​standards',
content: 'Vorbildwirkung, Entwicklung von höheren Standards mit MitbewerberInnen, Lobbying',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'E',
name: 'Gesell​schaftliches Umfeld:',
explanation: 'Region, Souverän, zukünftige Generationen, Zivil​gesellschaft, Mitmenschen und Natur',
values: [
{
shortcode : 'E1',
shortcodeSlug : 'e1',
title: 'Sinn und Gesell​schaftliche Wirkung der Produkte / Dienst​leistungen',
content: 'P/DL decken den Grundbedarf oder dienen der Entwicklung der Menschen / der Gemeinschaft / der Erde und generieren positiven Nutzen.',
points: 50,
soleProprietorship: true
},
{
shortcode : 'E2',
shortcodeSlug : 'e2',
title: 'Beitrag zum Gemeinwesen',
content: 'Gegenseitige Unterstützung und Kooperation durch Finanzmittel, Dienstleistungen, Produkte, Logistik, Zeit, Know-How, Wissen, Kontakte, Einfluss',
points: 40,
soleProprietorship: true
},
{
shortcode : 'E3',
shortcodeSlug : 'e3',
title: 'Reduktion ökologischer Auswirkungen',
content: 'Reduktion der Umwelt​auswirkungen auf ein zukunftsfähiges Niveau: Ressourcen, Energie & Klima, Emissionen, Abfälle etc.',
points: 70,
soleProprietorship: true
},
{
shortcode : 'E4',
shortcodeSlug : 'e4',
title: 'Gemeinwohl​orientierte Gewinn-Verteilung',
content: 'Sinkende / keine Gewinn​ausschüttung an Externe, Ausschüttung an Mitarbeiter, Stärkung des Eigenkapitals, sozial-ökologische Investitionen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'E5',
shortcodeSlug : 'e5',
title: 'Gesellschaft​liche Transparenz und Mitbestimmung',
content: 'Gemeinwohl- oder Nachhaltigkeits​bericht, Mitbestimmung von regionalen und zivilgesell​schaftlichen Berührungs​gruppen',
points: 30,
soleProprietorship: true
}
]
}
],
negativeCriteria : [
{
values: [
{
shortcode : 'N1',
shortcodeSlug : 'n1',
titleShort: 'Verletzung der ILO-Arbeitsnormen / Menschenrechte',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N2',
shortcodeSlug : 'n2',
titleShort: 'Menschen​unwürdige Produkte, z.B. Tretminen, Atomstrom, GMO',
title: 'Menschenunwürdige Produkte und Dienstleistungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N3',
shortcodeSlug : 'n3',
titleShort: 'Beschaffung bei / Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
title: 'Menschenunwürdige Produkte und Dienstbeschaffung bei bzt. Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
points: -150,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N4',
shortcodeSlug : 'n4',
titleShort: 'Feindliche Übernahme',
title: 'Feindliche Übernahme',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N5',
shortcodeSlug : 'n5',
titleShort: 'Sperrpatente',
title: 'Sperrpatente',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N6',
shortcodeSlug : 'n6',
titleShort: 'Dumping​preise',
title: 'Dumpingpreise',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N7',
shortcodeSlug : 'n7',
titleShort: 'Illegitime Umweltbelastungen',
title: 'Illegitime Umweltbelastungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N8',
shortcodeSlug : 'n8',
titleShort: 'Verstöße gegen Umweltauflagen',
title: 'Verstöße gegen Umweltauflagen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N9',
shortcodeSlug : 'n9',
titleShort: 'Geplante Obsoleszenz (kurze Lebensdauer der Produkte)',
title: 'Geplante Obsoleszenz',
points: -100,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N10',
shortcodeSlug : 'n10',
titleShort: 'Arbeits​rechtliches Fehlverhalten seitens des Unternehmens',
title: 'Arbeitsrechtliches Fehlverhalten seitens des Unternehmens',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N11',
shortcodeSlug : 'n11',
titleShort: 'Arbeitsplatz​abbau oder Standortverlagerung bei Gewinn',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N12',
shortcodeSlug : 'n12',
titleShort: 'Umgehung der Steuerpflicht',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N13',
shortcodeSlug : 'n13',
titleShort: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
title: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N14',
shortcodeSlug : 'n14',
titleShort: 'Nicht​offenlegung aller Beteiligungen und Töchter',
title: 'Nichtoffenlegung aller Beteiligungen und Töchter',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N15',
shortcodeSlug : 'n15',
titleShort: 'Verhinderung eines Betriebsrats',
title: 'Verhinderung eines Betriebsrats',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N16',
shortcodeSlug : 'n16',
titleShort: 'Nicht​offenlegung aller Finanzflüsse an Lobbies / Eintragung in das EU-Lobbyregister',
title: 'Nichtoffenlegung aller Finanzflüsse an Lobbyisten und Lobby-Organisationen / Nichteintragung ins Lobby-Register der EU',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N17',
shortcodeSlug : 'n17',
titleShort: 'Exzessive Einkommensspreizung',
title: 'Exzessive Einkommensspreizung',
points: -100,
soleProprietorship: true
}
]
}
]
};
exports.Data = Data;
| sinnwerkstatt/common-good-online-balance | ecg_balancing/templates/ecg_balancing/dustjs/gwoe-matrix-data_en.js | JavaScript | mit | 15,425 |
package org.apache.cordova.facebook;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookDialogException;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.FacebookSdk;
import com.facebook.FacebookServiceException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.GameRequestContent;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.ShareOpenGraphObject;
import com.facebook.share.model.ShareOpenGraphAction;
import com.facebook.share.model.ShareOpenGraphContent;
import com.facebook.share.model.AppInviteContent;
import com.facebook.share.widget.GameRequestDialog;
import com.facebook.share.widget.MessageDialog;
import com.facebook.share.widget.ShareDialog;
import com.facebook.share.widget.AppInviteDialog;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ConnectPlugin extends CordovaPlugin {
private static final int INVALID_ERROR_CODE = -2; //-1 is FacebookRequestError.INVALID_ERROR_CODE
private static final String PUBLISH_PERMISSION_PREFIX = "publish";
private static final String MANAGE_PERMISSION_PREFIX = "manage";
@SuppressWarnings("serial")
private static final Set<String> OTHER_PUBLISH_PERMISSIONS = new HashSet<String>() {
{
add("ads_management");
add("create_event");
add("rsvp_event");
}
};
private final String TAG = "ConnectPlugin";
private CallbackManager callbackManager;
private AppEventsLogger logger;
private CallbackContext loginContext = null;
private CallbackContext showDialogContext = null;
private CallbackContext graphContext = null;
private String graphPath;
private ShareDialog shareDialog;
private GameRequestDialog gameRequestDialog;
private AppInviteDialog appInviteDialog;
private MessageDialog messageDialog;
@Override
protected void pluginInitialize() {
FacebookSdk.sdkInitialize(cordova.getActivity().getApplicationContext());
// create callbackManager
callbackManager = CallbackManager.Factory.create();
// create AppEventsLogger
logger = AppEventsLogger.newLogger(cordova.getActivity().getApplicationContext());
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
if (response.getError() != null) {
if (graphContext != null) {
graphContext.error(getFacebookRequestErrorResponse(response.getError()));
} else if (loginContext != null) {
loginContext.error(getFacebookRequestErrorResponse(response.getError()));
}
return;
}
// If this login comes after doing a new permission request
// make the outstanding graph call
if (graphContext != null) {
makeGraphCall();
return;
}
Log.d(TAG, "returning login object " + jsonObject.toString());
loginContext.success(getResponse());
loginContext = null;
}
}).executeAsync();
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, loginContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, loginContext);
}
});
shareDialog = new ShareDialog(cordova.getActivity());
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
if (showDialogContext != null) {
showDialogContext.success(result.getPostId());
showDialogContext = null;
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
messageDialog = new MessageDialog(cordova.getActivity());
messageDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
if (showDialogContext != null) {
showDialogContext.success();
showDialogContext = null;
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
gameRequestDialog = new GameRequestDialog(cordova.getActivity());
gameRequestDialog.registerCallback(callbackManager, new FacebookCallback<GameRequestDialog.Result>() {
@Override
public void onSuccess(GameRequestDialog.Result result) {
if (showDialogContext != null) {
try {
JSONObject json = new JSONObject();
json.put("requestId", result.getRequestId());
json.put("recipientsIds", new JSONArray(result.getRequestRecipients()));
showDialogContext.success(json);
showDialogContext = null;
} catch (JSONException ex) {
showDialogContext.success();
showDialogContext = null;
}
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
appInviteDialog = new AppInviteDialog(cordova.getActivity());
appInviteDialog.registerCallback(callbackManager, new FacebookCallback<AppInviteDialog.Result>() {
@Override
public void onSuccess(AppInviteDialog.Result result) {
if (showDialogContext != null) {
try {
JSONObject json = new JSONObject();
Bundle bundle = result.getData();
for (String key : bundle.keySet()) {
json.put(key, wrapObject(bundle.get(key)));
}
showDialogContext.success(json);
showDialogContext = null;
} catch (JSONException e) {
showDialogContext.success();
showDialogContext = null;
}
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
// Developers can observe how frequently users activate their app by logging an app activation event.
AppEventsLogger.activateApp(cordova.getActivity());
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
AppEventsLogger.deactivateApp(cordova.getActivity());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Log.d(TAG, "activity result in plugin: requestCode(" + requestCode + "), resultCode(" + resultCode + ")");
callbackManager.onActivityResult(requestCode, resultCode, intent);
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("login")) {
executeLogin(args, callbackContext);
return true;
} else if (action.equals("logout")) {
if (hasAccessToken()) {
LoginManager.getInstance().logOut();
callbackContext.success();
} else {
callbackContext.error("No valid session found, must call init and login before logout.");
}
return true;
} else if (action.equals("getLoginStatus")) {
callbackContext.success(getResponse());
return true;
} else if (action.equals("getAccessToken")) {
if (hasAccessToken()) {
callbackContext.success(AccessToken.getCurrentAccessToken().getToken());
} else {
// Session not open
callbackContext.error("Session not open.");
}
return true;
} else if (action.equals("logEvent")) {
executeLogEvent(args, callbackContext);
return true;
} else if (action.equals("logPurchase")) {
/*
* While calls to logEvent can be made to register purchase events,
* there is a helper method that explicitly takes a currency indicator.
*/
if (args.length() != 2) {
callbackContext.error("Invalid arguments");
return true;
}
int value = args.getInt(0);
String currency = args.getString(1);
logger.logPurchase(BigDecimal.valueOf(value), Currency.getInstance(currency));
callbackContext.success();
return true;
} else if (action.equals("showDialog")) {
executeDialog(args, callbackContext);
return true;
} else if (action.equals("graphApi")) {
executeGraph(args, callbackContext);
return true;
} else if (action.equals("appInvite")) {
executeAppInvite(args, callbackContext);
return true;
} else if (action.equals("activateApp")) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
AppEventsLogger.activateApp(cordova.getActivity());
}
});
return true;
}
return false;
}
private void executeAppInvite(JSONArray args, CallbackContext callbackContext) {
String url = null;
String picture = null;
JSONObject parameters;
try {
parameters = args.getJSONObject(0);
} catch (JSONException e) {
parameters = new JSONObject();
}
if (parameters.has("url")) {
try {
url = parameters.getString("url");
} catch (JSONException e) {
Log.e(TAG, "Non-string 'url' parameter provided to dialog");
callbackContext.error("Incorrect 'url' parameter");
return;
}
} else {
callbackContext.error("Missing required 'url' parameter");
return;
}
if (parameters.has("picture")) {
try {
picture = parameters.getString("picture");
} catch (JSONException e) {
Log.e(TAG, "Non-string 'picture' parameter provided to dialog");
callbackContext.error("Incorrect 'picture' parameter");
return;
}
}
if (AppInviteDialog.canShow()) {
AppInviteContent.Builder builder = new AppInviteContent.Builder();
builder.setApplinkUrl(url);
if (picture != null) {
builder.setPreviewImageUrl(picture);
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
cordova.setActivityResultCallback(this);
appInviteDialog.show(builder.build());
} else {
callbackContext.error("Unable to show dialog");
}
}
private void executeDialog(JSONArray args, CallbackContext callbackContext) throws JSONException {
Map<String, String> params = new HashMap<String, String>();
String method = null;
JSONObject parameters;
try {
parameters = args.getJSONObject(0);
} catch (JSONException e) {
parameters = new JSONObject();
}
Iterator<String> iter = parameters.keys();
while (iter.hasNext()) {
String key = iter.next();
if (key.equals("method")) {
try {
method = parameters.getString(key);
} catch (JSONException e) {
Log.w(TAG, "Nonstring method parameter provided to dialog");
}
} else {
try {
params.put(key, parameters.getString(key));
} catch (JSONException e) {
// Need to handle JSON parameters
Log.w(TAG, "Non-string parameter provided to dialog discarded");
}
}
}
if (method == null) {
callbackContext.error("No method provided");
} else if (method.equalsIgnoreCase("apprequests")) {
if (!GameRequestDialog.canShow()) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
GameRequestContent.Builder builder = new GameRequestContent.Builder();
if (params.containsKey("message"))
builder.setMessage(params.get("message"));
if (params.containsKey("to"))
builder.setTo(params.get("to"));
if (params.containsKey("data"))
builder.setData(params.get("data"));
if (params.containsKey("title"))
builder.setTitle(params.get("title"));
if (params.containsKey("objectId"))
builder.setObjectId(params.get("objectId"));
if (params.containsKey("actionType")) {
try {
final GameRequestContent.ActionType actionType = GameRequestContent.ActionType.valueOf(params.get("actionType"));
builder.setActionType(actionType);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Discarding invalid argument actionType");
}
}
if (params.containsKey("filters")) {
try {
final GameRequestContent.Filters filters = GameRequestContent.Filters.valueOf(params.get("filters"));
builder.setFilters(filters);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Discarding invalid argument filters");
}
}
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
gameRequestDialog.show(builder.build());
} else if (method.equalsIgnoreCase("share") || method.equalsIgnoreCase("feed")) {
if (!ShareDialog.canShow(ShareLinkContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
ShareLinkContent content = buildContent(params);
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
shareDialog.show(content);
} else if (method.equalsIgnoreCase("share_open_graph")) {
if (!ShareDialog.canShow(ShareOpenGraphContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
if (!params.containsKey("action")) {
callbackContext.error("Missing required parameter 'action'");
}
if (!params.containsKey("object")) {
callbackContext.error("Missing required parameter 'object'.");
}
ShareOpenGraphObject.Builder objectBuilder = new ShareOpenGraphObject.Builder();
JSONObject jObject = new JSONObject(params.get("object"));
Iterator<?> objectKeys = jObject.keys();
String objectType = "";
while ( objectKeys.hasNext() ) {
String key = (String)objectKeys.next();
String value = jObject.getString(key);
objectBuilder.putString(key, value);
if (key.equals("og:type"))
objectType = value;
}
if (objectType.equals("")) {
callbackContext.error("Missing required object parameter 'og:type'");
}
ShareOpenGraphAction.Builder actionBuilder = new ShareOpenGraphAction.Builder();
actionBuilder.setActionType(params.get("action"));
if (params.containsKey("action_properties")) {
JSONObject jActionProperties = new JSONObject(params.get("action_properties"));
Iterator<?> actionKeys = jActionProperties.keys();
while ( actionKeys.hasNext() ) {
String actionKey = (String)actionKeys.next();
actionBuilder.putString(actionKey, jActionProperties.getString(actionKey));
}
}
actionBuilder.putObject(objectType, objectBuilder.build());
ShareOpenGraphContent.Builder content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName(objectType)
.setAction(actionBuilder.build());
shareDialog.show(content.build());
} else if (method.equalsIgnoreCase("send")) {
if (!MessageDialog.canShow(ShareLinkContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
ShareLinkContent.Builder builder = new ShareLinkContent.Builder();
if(params.containsKey("link"))
builder.setContentUrl(Uri.parse(params.get("link")));
if(params.containsKey("caption"))
builder.setContentTitle(params.get("caption"));
if(params.containsKey("picture"))
builder.setImageUrl(Uri.parse(params.get("picture")));
if(params.containsKey("description"))
builder.setContentDescription(params.get("description"));
messageDialog.show(builder.build());
} else {
callbackContext.error("Unsupported dialog method.");
}
}
private void executeGraph(JSONArray args, CallbackContext callbackContext) throws JSONException {
graphContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
graphContext.sendPluginResult(pr);
graphPath = args.getString(0);
JSONArray arr = args.getJSONArray(1);
final Set<String> permissions = new HashSet<String>(arr.length());
for (int i = 0; i < arr.length(); i++) {
permissions.add(arr.getString(i));
}
if (permissions.size() == 0) {
makeGraphCall();
return;
}
boolean publishPermissions = false;
boolean readPermissions = false;
String declinedPermission = null;
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken.getPermissions().containsAll(permissions)) {
makeGraphCall();
return;
}
Set<String> declined = accessToken.getDeclinedPermissions();
// Figure out if we have all permissions
for (String permission : permissions) {
if (declined.contains(permission)) {
declinedPermission = permission;
break;
}
if (isPublishPermission(permission)) {
publishPermissions = true;
} else {
readPermissions = true;
}
// Break if we have a mixed bag, as this is an error
if (publishPermissions && readPermissions) {
break;
}
}
if (declinedPermission != null) {
graphContext.error("This request needs declined permission: " + declinedPermission);
}
if (publishPermissions && readPermissions) {
graphContext.error("Cannot ask for both read and publish permissions.");
return;
}
cordova.setActivityResultCallback(this);
LoginManager loginManager = LoginManager.getInstance();
// Check for write permissions, the default is read (empty)
if (publishPermissions) {
// Request new publish permissions
loginManager.logInWithPublishPermissions(cordova.getActivity(), permissions);
} else {
// Request new read permissions
loginManager.logInWithReadPermissions(cordova.getActivity(), permissions);
}
}
private void executeLogEvent(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (args.length() == 0) {
// Not enough parameters
callbackContext.error("Invalid arguments");
return;
}
String eventName = args.getString(0);
if (args.length() == 1) {
logger.logEvent(eventName);
callbackContext.success();
return;
}
// Arguments is greater than 1
JSONObject params = args.getJSONObject(1);
Bundle parameters = new Bundle();
Iterator<String> iter = params.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
// Try get a String
String value = params.getString(key);
parameters.putString(key, value);
} catch (JSONException e) {
// Maybe it was an int
Log.w(TAG, "Type in AppEvent parameters was not String for key: " + key);
try {
int value = params.getInt(key);
parameters.putInt(key, value);
} catch (JSONException e2) {
// Nope
Log.e(TAG, "Unsupported type in AppEvent parameters for key: " + key);
}
}
}
if (args.length() == 2) {
logger.logEvent(eventName, parameters);
callbackContext.success();
}
if (args.length() == 3) {
double value = args.getDouble(2);
logger.logEvent(eventName, value, parameters);
callbackContext.success();
}
}
private void executeLogin(JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "login FB");
// Get the permissions
Set<String> permissions = new HashSet<String>(args.length());
for (int i = 0; i < args.length(); i++) {
permissions.add(args.getString(i));
}
// Set a pending callback to cordova
loginContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
loginContext.sendPluginResult(pr);
// Check if the active session is open
if (!hasAccessToken()) {
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
// Create the request
LoginManager.getInstance().logInWithReadPermissions(cordova.getActivity(), permissions);
return;
}
// Reauthorize flow
boolean publishPermissions = false;
boolean readPermissions = false;
// Figure out if this will be a read or publish reauthorize
if (permissions.size() == 0) {
// No permissions, read
readPermissions = true;
}
// Loop through the permissions to see what
// is being requested
for (String permission : permissions) {
if (isPublishPermission(permission)) {
publishPermissions = true;
} else {
readPermissions = true;
}
// Break if we have a mixed bag, as this is an error
if (publishPermissions && readPermissions) {
break;
}
}
if (publishPermissions && readPermissions) {
loginContext.error("Cannot ask for both read and publish permissions.");
loginContext = null;
return;
}
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
// Check for write permissions, the default is read (empty)
if (publishPermissions) {
// Request new publish permissions
LoginManager.getInstance().logInWithPublishPermissions(cordova.getActivity(), permissions);
} else {
// Request new read permissions
LoginManager.getInstance().logInWithReadPermissions(cordova.getActivity(), permissions);
}
}
private ShareLinkContent buildContent(Map<String, String> paramBundle) {
ShareLinkContent.Builder builder = new ShareLinkContent.Builder();
if (paramBundle.containsKey("caption"))
builder.setContentTitle(paramBundle.get("caption"));
if (paramBundle.containsKey("description"))
builder.setContentDescription(paramBundle.get("description"));
if (paramBundle.containsKey("href"))
builder.setContentUrl(Uri.parse(paramBundle.get("href")));
if (paramBundle.containsKey("picture"))
builder.setImageUrl(Uri.parse(paramBundle.get("picture")));
return builder.build();
}
// Simple active session check
private boolean hasAccessToken() {
return AccessToken.getCurrentAccessToken() != null;
}
private void handleError(FacebookException exception, CallbackContext context) {
if (exception.getMessage() != null) {
Log.e(TAG, exception.toString());
}
String errMsg = "Facebook error: " + exception.getMessage();
int errorCode = INVALID_ERROR_CODE;
// User clicked "x"
if (exception instanceof FacebookOperationCanceledException) {
errMsg = "User cancelled dialog";
errorCode = 4201;
} else if (exception instanceof FacebookDialogException) {
// Dialog error
errMsg = "Dialog error: " + exception.getMessage();
}
if (context != null) {
context.error(getErrorResponse(exception, errMsg, errorCode));
} else {
Log.e(TAG, "Error already sent so no context, msg: " + errMsg + ", code: " + errorCode);
}
}
private void makeGraphCall() {
//If you're using the paging URLs they will be URLEncoded, let's decode them.
try {
graphPath = URLDecoder.decode(graphPath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] urlParts = graphPath.split("\\?");
String graphAction = urlParts[0];
GraphRequest graphRequest = GraphRequest.newGraphPathRequest(AccessToken.getCurrentAccessToken(), graphAction, new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
if (graphContext != null) {
if (response.getError() != null) {
graphContext.error(getFacebookRequestErrorResponse(response.getError()));
} else {
graphContext.success(response.getJSONObject());
}
graphPath = null;
graphContext = null;
}
}
});
Bundle params = graphRequest.getParameters();
if (urlParts.length > 1) {
String[] queries = urlParts[1].split("&");
for (String query : queries) {
int splitPoint = query.indexOf("=");
if (splitPoint > 0) {
String key = query.substring(0, splitPoint);
String value = query.substring(splitPoint + 1, query.length());
params.putString(key, value);
}
}
}
graphRequest.setParameters(params);
graphRequest.executeAsync();
}
/*
* Checks for publish permissions
*/
private boolean isPublishPermission(String permission) {
return permission != null &&
(permission.startsWith(PUBLISH_PERMISSION_PREFIX) ||
permission.startsWith(MANAGE_PERMISSION_PREFIX) ||
OTHER_PUBLISH_PERMISSIONS.contains(permission));
}
/**
* Create a Facebook Response object that matches the one for the Javascript SDK
* @return JSONObject - the response object
*/
public JSONObject getResponse() {
String response;
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (hasAccessToken()) {
Date today = new Date();
long expiresTimeInterval = (accessToken.getExpires().getTime() - today.getTime()) / 1000L;
response = "{"
+ "\"status\": \"connected\","
+ "\"authResponse\": {"
+ "\"accessToken\": \"" + accessToken.getToken() + "\","
+ "\"expiresIn\": \"" + Math.max(expiresTimeInterval, 0) + "\","
+ "\"session_key\": true,"
+ "\"sig\": \"...\","
+ "\"userID\": \"" + accessToken.getUserId() + "\""
+ "}"
+ "}";
} else {
response = "{"
+ "\"status\": \"unknown\""
+ "}";
}
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
public JSONObject getFacebookRequestErrorResponse(FacebookRequestError error) {
String response = "{"
+ "\"errorCode\": \"" + error.getErrorCode() + "\","
+ "\"errorType\": \"" + error.getErrorType() + "\","
+ "\"errorMessage\": \"" + error.getErrorMessage() + "\"";
if (error.getErrorUserMessage() != null) {
response += ",\"errorUserMessage\": \"" + error.getErrorUserMessage() + "\"";
}
if (error.getErrorUserTitle() != null) {
response += ",\"errorUserTitle\": \"" + error.getErrorUserTitle() + "\"";
}
response += "}";
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
public JSONObject getErrorResponse(Exception error, String message, int errorCode) {
if (error instanceof FacebookServiceException) {
return getFacebookRequestErrorResponse(((FacebookServiceException) error).getRequestError());
}
String response = "{";
if (error instanceof FacebookDialogException) {
errorCode = ((FacebookDialogException) error).getErrorCode();
}
if (errorCode != INVALID_ERROR_CODE) {
response += "\"errorCode\": \"" + errorCode + "\",";
}
if (message == null) {
message = error.getMessage();
}
response += "\"errorMessage\": \"" + message + "\"}";
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
/**
* Wraps the given object if necessary.
*
* If the object is null or , returns {@link #JSONObject.NULL}.
* If the object is a {@code JSONArray} or {@code JSONObject}, no wrapping is necessary.
* If the object is {@code JSONObject.NULL}, no wrapping is necessary.
* If the object is an array or {@code Collection}, returns an equivalent {@code JSONArray}.
* If the object is a {@code Map}, returns an equivalent {@code JSONObject}.
* If the object is a primitive wrapper type or {@code String}, returns the object.
* Otherwise if the object is from a {@code java} package, returns the result of {@code toString}.
* If wrapping fails, returns null.
*/
private static Object wrapObject(Object o) {
if (o == null) {
return JSONObject.NULL;
}
if (o instanceof JSONArray || o instanceof JSONObject) {
return o;
}
if (o.equals(JSONObject.NULL)) {
return o;
}
try {
if (o instanceof Collection) {
return new JSONArray((Collection) o);
} else if (o.getClass().isArray()) {
return new JSONArray(o);
}
if (o instanceof Map) {
return new JSONObject((Map) o);
}
if (o instanceof Boolean ||
o instanceof Byte ||
o instanceof Character ||
o instanceof Double ||
o instanceof Float ||
o instanceof Integer ||
o instanceof Long ||
o instanceof Short ||
o instanceof String) {
return o;
}
if (o.getClass().getPackage().getName().startsWith("java.")) {
return o.toString();
}
} catch (Exception ignored) {
}
return null;
}
}
| CONDACORE/fahndo-app | plugins/cordova-plugin-facebook4/src/android/ConnectPlugin.java | Java | mit | 37,503 |
<?php
/***************************************************************************\
* SPIP, Systeme de publication pour l'internet *
* *
* Copyright (c) 2001-2011 *
* Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
* *
* Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
* Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
\***************************************************************************/
if (!defined('_ECRIRE_INC_VERSION')) return;
// Donne la liste des champs/tables ou l'on sait chercher/remplacer
// avec un poids pour le score
// http://doc.spip.org/@liste_des_champs
function liste_des_champs() {
return
pipeline('rechercher_liste_des_champs',
array(
'article' => array(
'surtitre' => 5, 'titre' => 8, 'soustitre' => 5, 'chapo' => 3,
'texte' => 1, 'ps' => 1, 'nom_site' => 1, 'url_site' => 1,
'descriptif' => 4
),
'breve' => array(
'titre' => 8, 'texte' => 2, 'lien_titre' => 1, 'lien_url' => 1
),
'rubrique' => array(
'titre' => 8, 'descriptif' => 5, 'texte' => 1
),
'site' => array(
'nom_site' => 5, 'url_site' => 1, 'descriptif' => 3
),
'mot' => array(
'titre' => 8, 'texte' => 1, 'descriptif' => 5
),
'auteur' => array(
'nom' => 5, 'bio' => 1, 'email' => 1, 'nom_site' => 1, 'url_site' => 1, 'login' => 1
),
'forum' => array(
'titre' => 3, 'texte' => 1, 'auteur' => 2, 'email_auteur' => 2, 'nom_site' => 1, 'url_site' => 1
),
'document' => array(
'titre' => 3, 'descriptif' => 1, 'fichier' => 1
),
'syndic_article' => array(
'titre' => 5, 'descriptif' => 1
),
'signature' => array(
'nom_email' => 2, 'ad_email' => 4,
'nom_site' => 2, 'url_site' => 4,
'message' => 1
)
)
);
}
// Recherche des auteurs et mots-cles associes
// en ne regardant que le titre ou le nom
// http://doc.spip.org/@liste_des_jointures
function liste_des_jointures() {
return
pipeline('rechercher_liste_des_jointures',
array(
'article' => array(
'auteur' => array('nom' => 10),
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'breve' => array(
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'rubrique' => array(
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'document' => array(
'mot' => array('titre' => 3)
)
)
);
}
// Effectue une recherche sur toutes les tables de la base de donnees
// options :
// - toutvoir pour eviter autoriser(voir)
// - flags pour eviter les flags regexp par defaut (UimsS)
// - champs pour retourner les champs concernes
// - score pour retourner un score
// On peut passer les tables, ou une chaine listant les tables souhaitees
// http://doc.spip.org/@recherche_en_base
function recherche_en_base($recherche='', $tables=NULL, $options=array(), $serveur='') {
include_spip('base/abstract_sql');
if (!is_array($tables)) {
$liste = liste_des_champs();
if (is_string($tables)
AND $tables != '') {
$toutes = array();
foreach(explode(',', $tables) as $t)
if (isset($liste[$t]))
$toutes[$t] = $liste[$t];
$tables = $toutes;
unset($toutes);
} else
$tables = $liste;
}
include_spip('inc/autoriser');
// options par defaut
$options = array_merge(array(
'preg_flags' => 'UimsS',
'toutvoir' => false,
'champs' => false,
'score' => false,
'matches' => false,
'jointures' => false
),
$options
);
$results = array();
if (!strlen($recherche) OR !count($tables))
return array();
include_spip('inc/charsets');
$recherche = translitteration($recherche);
$is_preg = false;
if (substr($recherche,0,1)=='/' AND substr($recherche,-1,1)=='/'){
// c'est une preg
$preg = $recherche.$options['preg_flags'];
$is_preg = true;
}
else
$preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
// Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
// ou si l'expression reguliere est invalide
if (!$is_preg
OR (@preg_match($preg,'')===FALSE) ) {
$methode = 'LIKE';
$u = $GLOBALS['meta']['pcre_u'];
// eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
$recherche = str_replace(
array('(',')','?','[', ']', '+', '*', '/'),
array('\(','\)','[?]', '\[', '\]', '\+', '\*', '\/'),
$recherche);
$recherche_mod = $recherche;
// echapper les % et _
$q = str_replace(array('%','_'), array('\%', '\_'), trim($recherche));
// les expressions entre " " sont un mot a chercher tel quel
// -> on remplace les espaces par un _ et on enleve les guillemets
if (preg_match(',["][^"]+["],Uims',$q,$matches)){
foreach($matches as $match){
// corriger le like dans le $q
$word = preg_replace(",\s+,Uims","_",$match);
$word = trim($word,'"');
$q = str_replace($match,$word,$q);
// corriger la regexp
$word = preg_replace(",\s+,Uims","[\s]",$match);
$word = trim($word,'"');
$recherche_mod = str_replace($match,$word,$recherche_mod);
}
}
$q = sql_quote(
"%"
. preg_replace(",\s+,".$u, "%", $q)
. "%"
);
$preg = '/'.preg_replace(",\s+,".$u, ".+", trim($recherche_mod)).'/' . $options['preg_flags'];
} else {
$methode = 'REGEXP';
$q = sql_quote(substr($recherche,1,-1));
}
$jointures = $options['jointures']
? liste_des_jointures()
: array();
foreach ($tables as $table => $champs) {
$requete = array(
"SELECT"=>array(),
"FROM"=>array(),
"WHERE"=>array(),
"GROUPBY"=>array(),
"ORDERBY"=>array(),
"LIMIT"=>"",
"HAVING"=>array()
);
$_id_table = id_table_objet($table);
$requete['SELECT'][] = "t.".$_id_table;
$a = array();
// Recherche fulltext
foreach ($champs as $champ => $poids) {
if (is_array($champ)){
spip_log("requetes imbriquees interdites");
} else {
if (strpos($champ,".")===FALSE)
$champ = "t.$champ";
$requete['SELECT'][] = $champ;
$a[] = $champ.' '.$methode.' '.$q;
}
}
if ($a) $requete['WHERE'][] = join(" OR ", $a);
$requete['FROM'][] = table_objet_sql($table).' AS t';
$s = sql_select(
$requete['SELECT'], $requete['FROM'], $requete['WHERE'],
implode(" ",$requete['GROUPBY']),
$requete['ORDERBY'], $requete['LIMIT'],
$requete['HAVING'], $serveur
);
while ($t = sql_fetch($s,$serveur)) {
$id = intval($t[$_id_table]);
if ($options['toutvoir']
OR autoriser('voir', $table, $id)) {
// indiquer les champs concernes
$champs_vus = array();
$score = 0;
$matches = array();
$vu = false;
foreach ($champs as $champ => $poids) {
$champ = explode('.',$champ);
$champ = end($champ);
if ($n =
($options['score'] || $options['matches'])
? preg_match_all($preg, translitteration_rapide($t[$champ]), $regs, PREG_SET_ORDER)
: preg_match($preg, translitteration_rapide($t[$champ]))
) {
$vu = true;
if ($options['champs'])
$champs_vus[$champ] = $t[$champ];
if ($options['score'])
$score += $n * $poids;
if ($options['matches'])
$matches[$champ] = $regs;
if (!$options['champs']
AND !$options['score']
AND !$options['matches'])
break;
}
}
if ($vu) {
if (!isset($results[$table]))
$results[$table] = array();
$results[$table][$id] = array();
if ($champs_vus)
$results[$table][$id]['champs'] = $champs_vus;
if ($score)
$results[$table][$id]['score'] = $score;
if ($matches)
$results[$table][$id]['matches'] = $matches;
}
}
}
// Gerer les donnees associees
if (isset($jointures[$table])
AND $joints = recherche_en_base(
$recherche,
$jointures[$table],
array_merge($options, array('jointures' => false))
)
) {
foreach ($joints as $table_liee => $ids_trouves) {
if (!$rechercher_joints = charger_fonction("rechercher_joints_${table}_${table_liee}","inc",true)){
$cle_depart = id_table_objet($table);
$cle_arrivee = id_table_objet($table_liee);
$table_sql = preg_replace('/^spip_/', '', table_objet_sql($table));
$table_liee_sql = preg_replace('/^spip_/', '', table_objet_sql($table_liee));
if ($table_liee == 'document')
$s = sql_select("id_objet as $cle_depart, $cle_arrivee", "spip_documents_liens", array("objet='$table'",sql_in('id_'.${table_liee}, array_keys($ids_trouves))), '','','','',$serveur);
else
$s = sql_select("$cle_depart,$cle_arrivee", "spip_${table_liee_sql}_${table_sql}", sql_in('id_'.${table_liee}, array_keys($ids_trouves)), '','','','',$serveur);
}
else
list($cle_depart,$cle_arrivee,$s) = $rechercher_joints($table,$table_liee,array_keys($ids_trouves), $serveur);
while ($t = is_array($s)?array_shift($s):sql_fetch($s)) {
$id = $t[$cle_depart];
$joint = $ids_trouves[$t[$cle_arrivee]];
if (!isset($results[$table]))
$results[$table] = array();
if (!isset($results[$table][$id]))
$results[$table][$id] = array();
if ($joint['score'])
$results[$table][$id]['score'] += $joint['score'];
if ($joint['champs'])
foreach($joint['champs'] as $c => $val)
$results[$table][$id]['champs'][$table_liee.'.'.$c] = $val;
if ($joint['matches'])
foreach($joint['matches'] as $c => $val)
$results[$table][$id]['matches'][$table_liee.'.'.$c] = $val;
}
}
}
}
return $results;
}
// Effectue une recherche sur toutes les tables de la base de donnees
// http://doc.spip.org/@remplace_en_base
function remplace_en_base($recherche='', $remplace=NULL, $tables=NULL, $options=array()) {
include_spip('inc/modifier');
// options par defaut
$options = array_merge(array(
'preg_flags' => 'UimsS',
'toutmodifier' => false
),
$options
);
$options['champs'] = true;
if (!is_array($tables))
$tables = liste_des_champs();
$results = recherche_en_base($recherche, $tables, $options);
$preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
foreach ($results as $table => $r) {
$_id_table = id_table_objet($table);
foreach ($r as $id => $x) {
if ($options['toutmodifier']
OR autoriser('modifier', $table, $id)) {
$modifs = array();
foreach ($x['champs'] as $key => $val) {
if ($key == $_id_table) next;
$repl = preg_replace($preg, $remplace, $val);
if ($repl <> $val)
$modifs[$key] = $repl;
}
if ($modifs)
modifier_contenu($table, $id,
array(
'champs' => array_keys($modifs),
),
$modifs);
}
}
}
}
?>
| eyeswebcrea/cheminee-mario.com | spip/ecrire/inc/rechercher.php | PHP | mit | 10,890 |
<?php
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*/
$aConfig = array(
/**
* Main Section.
*/
'title' => 'Organizations',
'version_from' => '8.0.1',
'version_to' => '8.0.2',
'vendor' => 'BoonEx',
'compatible_with' => array(
'8.0.0.A8'
),
/**
* 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars.
*/
'home_dir' => 'boonex/organizations/updates/update_8.0.1_8.0.2/',
'home_uri' => 'orgs_update_801_802',
'module_dir' => 'boonex/organizations/',
'module_uri' => 'orgs',
'db_prefix' => 'bx_organizations_',
'class_prefix' => 'BxOrgs',
/**
* Installation/Uninstallation Section.
*/
'install' => array(
'execute_sql' => 1,
'update_files' => 1,
'update_languages' => 1,
'clear_db_cache' => 1,
),
/**
* Category for language keys.
*/
'language_category' => 'Organizations',
);
| camperjz/trident | modules/boonex/organizations/updates/8.0.1_8.0.2/install/config.php | PHP | mit | 1,044 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest.Azure.Authentication.Properties;
namespace Microsoft.Rest.Azure.Authentication
{
/// <summary>
/// Settings for authentication with an Azure or Azure Stack service using Active Directory.
/// </summary>
public sealed class ActiveDirectoryServiceSettings
{
private Uri _authenticationEndpoint;
private static readonly ActiveDirectoryServiceSettings AzureSettings = new ActiveDirectoryServiceSettings
{
AuthenticationEndpoint= new Uri("https://login.windows.net/"),
TokenAudience = new Uri("https://management.core.windows.net/"),
ValidateAuthority = true
};
private static readonly ActiveDirectoryServiceSettings AzureChinaSettings = new ActiveDirectoryServiceSettings
{
AuthenticationEndpoint= new Uri("https://login.chinacloudapi.cn/"),
TokenAudience = new Uri("https://management.core.chinacloudapi.cn/"),
ValidateAuthority = true
};
/// <summary>
/// Gets the serviceSettings for authentication with Azure
/// </summary>
public static ActiveDirectoryServiceSettings Azure { get { return AzureSettings; } }
/// <summary>
/// Gets the serviceSettings for authentication with Azure China
/// </summary>
public static ActiveDirectoryServiceSettings AzureChina { get { return AzureChinaSettings; } }
/// <summary>
/// Gets or sets the ActiveDirectory Endpoint for the Azure Environment
/// </summary>
public Uri AuthenticationEndpoint
{
get { return _authenticationEndpoint; }
set { _authenticationEndpoint = EnsureTrailingSlash(value); }
}
/// <summary>
/// Gets or sets the Token audience for an endpoint
/// </summary>
public Uri TokenAudience { get; set; }
/// <summary>
/// Gets or sets a value that determines whether the authentication endpoint should be validated with Azure AD
/// </summary>
public bool ValidateAuthority { get; set; }
private static Uri EnsureTrailingSlash(Uri authenticationEndpoint)
{
if (authenticationEndpoint == null)
{
throw new ArgumentNullException("authenticationEndpoint");
}
UriBuilder builder = new UriBuilder(authenticationEndpoint);
if (!string.IsNullOrEmpty(builder.Query))
{
throw new ArgumentOutOfRangeException(Resources.AuthenticationEndpointContainsQuery);
}
var path = builder.Path;
if (string.IsNullOrWhiteSpace(path))
{
path = "/";
}
else if (!path.EndsWith("/", StringComparison.Ordinal))
{
path = path + "/";
}
builder.Path = path;
return builder.Uri;
}
}
}
| colemickens/autorest | ClientRuntimes/CSharp/ClientRuntime.Azure.Authentication/ActiveDirectoryServiceSettings.cs | C# | mit | 3,207 |
# frozen_string_literal: true
module ActiveSupport
module NumberHelper
class NumberToRoundedConverter < NumberConverter # :nodoc:
self.namespace = :precision
self.validate_float = true
def convert
helper = RoundingHelper.new(options)
rounded_number = helper.round(number)
if precision = options[:precision]
if options[:significant] && precision > 0
digits = helper.digit_count(rounded_number)
precision -= digits
precision = 0 if precision < 0 # don't let it be negative
end
formatted_string =
if BigDecimal === rounded_number && rounded_number.finite?
s = rounded_number.to_s("F")
s << "0".freeze * precision
a, b = s.split(".".freeze, 2)
a << ".".freeze
a << b[0, precision]
else
"%00.#{precision}f" % rounded_number
end
else
formatted_string = rounded_number
end
delimited_number = NumberToDelimitedConverter.convert(formatted_string, options)
format_number(delimited_number)
end
private
def calculate_rounded_number(multiplier)
(number / BigDecimal.new(multiplier.to_f.to_s)).round * multiplier
end
def digit_count(number)
number.zero? ? 1 : (Math.log10(absolute_number(number)) + 1).floor
end
def strip_insignificant_zeros
options[:strip_insignificant_zeros]
end
def format_number(number)
if strip_insignificant_zeros
escaped_separator = Regexp.escape(options[:separator])
number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, "")
else
number
end
end
end
end
end
| felipecvo/rails | activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb | Ruby | mit | 1,873 |
/**
* Module dependencies.
*/
var finalhandler = require('finalhandler');
var flatten = require('./utils').flatten;
var Router = require('./router');
var methods = require('methods');
var middleware = require('./middleware/init');
var query = require('./middleware/query');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var deprecate = require('depd')('express');
var merge = require('utils-merge');
var resolve = require('path').resolve;
var slice = Array.prototype.slice;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @api private
*/
app.init = function(){
this.cache = {};
this.settings = {};
this.engines = {};
this.defaultConfiguration();
};
/**
* Initialize application configuration.
*
* @api private
*/
app.defaultConfiguration = function(){
// default settings
this.enable('x-powered-by');
this.set('etag', 'weak');
var env = process.env.NODE_ENV || 'development';
this.set('env', env);
this.set('query parser', 'extended');
this.set('subdomain offset', 2);
this.set('trust proxy', false);
debug('booting in %s mode', env);
// inherit protos
this.on('mount', function(parent){
this.request.__proto__ = parent.request;
this.response.__proto__ = parent.response;
this.engines.__proto__ = parent.engines;
this.settings.__proto__ = parent.settings;
});
// setup locals
this.locals = Object.create(null);
// top-most app is mounted at /
this.mountpath = '/';
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('view', View);
this.set('views', resolve('views'));
this.set('jsonp callback name', 'callback');
if (env === 'production') {
this.enable('view cache');
}
Object.defineProperty(this, 'router', {
get: function() {
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
}
});
};
/**
* lazily adds the base router if it has not yet been added.
*
* We cannot add the base router in the defaultConfiguration because
* it reads app settings which might be set after that has run.
*
* @api private
*/
app.lazyrouter = function() {
if (!this._router) {
this._router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));
}
};
/**
* Dispatch a req, res pair into the application. Starts pipeline processing.
*
* If no _done_ callback is provided, then default error handlers will respond
* in the event of an error bubbling through the stack.
*
* @api private
*/
app.handle = function(req, res, done) {
var router = this._router;
// final handler
done = done || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// no routes
if (!router) {
debug('no routes defined on app');
done();
return;
}
router.handle(req, res, done);
};
/**
* Proxy `Router#use()` to add middleware to the app router.
* See Router#use() documentation for details.
*
* If the _fn_ parameter is an express app, then it will be
* mounted at the _route_ specified.
*
* @api public
*/
app.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate app.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var fns = flatten(slice.call(arguments, offset));
if (fns.length === 0) {
throw new TypeError('app.use() requires middleware functions');
}
// setup router
this.lazyrouter();
var router = this._router;
fns.forEach(function (fn) {
// non-express app
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
debug('.use app under %s', path);
fn.mountpath = path;
fn.parent = this;
// restore .app property on req and res
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
req.__proto__ = orig.request;
res.__proto__ = orig.response;
next(err);
});
});
// mounted an app
fn.emit('mount', this);
}, this);
return this;
};
/**
* Proxy to the app `Router#route()`
* Returns a new `Route` instance for the _path_.
*
* Routes are isolated middleware stacks for specific paths.
* See the Route api docs for details.
*
* @api public
*/
app.route = function(path){
this.lazyrouter();
return this._router.route(path);
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.jade" file Express will invoke the following internally:
*
* app.engine('jade', require('jade').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you dont need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.engine = function(ext, fn){
if ('function' != typeof fn) throw new Error('callback function required');
if ('.' != ext[0]) ext = '.' + ext;
this.engines[ext] = fn;
return this;
};
/**
* Proxy to `Router#param()` with one added api feature. The _name_ parameter
* can be an array of names.
*
* See the Router#param() docs for more details.
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.param = function(name, fn){
this.lazyrouter();
if (Array.isArray(name)) {
name.forEach(function(key) {
this.param(key, fn);
}, this);
return this;
}
this._router.param(name, fn);
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {*} [val]
* @return {Server} for chaining
* @api public
*/
app.set = function(setting, val){
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
debug('compile etag %s', val);
this.set('etag fn', compileETag(val));
break;
case 'query parser':
debug('compile query parser %s', val);
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
debug('compile trust proxy %s', val);
this.set('trust proxy fn', compileTrust(val));
break;
}
return this;
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @api private
*/
app.path = function(){
return this.parent
? this.parent.path() + this.mountpath
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.enabled = function(setting){
return !!this.set(setting);
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.disabled = function(setting){
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.enable = function(setting){
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.disable = function(setting){
return this.set(setting, false);
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if ('get' == method && 1 == arguments.length) return this.set(path);
this.lazyrouter();
var route = this._router.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @api public
*/
app.all = function(path){
this.lazyrouter();
var route = this._router.route(path);
var args = slice.call(arguments, 1);
methods.forEach(function(method){
route[method].apply(route, args);
});
return this;
};
// del -> delete alias
app.del = deprecate.function(app.d | wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/node_modules/rewire/node_modules/expect.js/node_modules/serve/node_modules/less-middleware/node_modules/express/lib/application.js | JavaScript | mit | 10,240 |
#!/usr/bin/env python
class PivotFilter(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'AutoFilter': 'AutoFilter',
'EvaluationOrder': 'int',
'FieldIndex': 'int',
'FilterType': 'str',
'MeasureFldIndex': 'int',
'MemberPropertyFieldIndex': 'int',
'Name': 'str',
'Value1': 'str',
'Value2': 'str'
}
self.attributeMap = {
'AutoFilter': 'AutoFilter','EvaluationOrder': 'EvaluationOrder','FieldIndex': 'FieldIndex','FilterType': 'FilterType','MeasureFldIndex': 'MeasureFldIndex','MemberPropertyFieldIndex': 'MemberPropertyFieldIndex','Name': 'Name','Value1': 'Value1','Value2': 'Value2'}
self.AutoFilter = None # AutoFilter
self.EvaluationOrder = None # int
self.FieldIndex = None # int
self.FilterType = None # str
self.MeasureFldIndex = None # int
self.MemberPropertyFieldIndex = None # int
self.Name = None # str
self.Value1 = None # str
self.Value2 = None # str
| aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-Python/asposecellscloud/models/PivotFilter.py | Python | mit | 1,456 |
class Service::Presently < Service
string :subdomain, :group_name, :username
password :password
white_list :subdomain, :group_name, :username
def receive_push
repository = payload['repository']['name']
prefix = (data['group_name'].nil? || data['group_name'] == '') ? '' : "b #{data['group_name']} "
payload['commits'].each do |commit|
status = "#{prefix}[#{repository}] #{commit['author']['name']} - #{commit['message']}"
status = status[0...137] + '...' if status.length > 140
paste = "\"Commit #{commit['id']}\":#{commit['url']}\n\n"
paste << "#{commit['message']}\n\n"
%w(added modified removed).each do |kind|
commit[kind].each do |filename|
paste << "* *#{kind.capitalize}* '#{filename}'\n"
end
end
http.url_prefix = "https://#{data['subdomain']}.presently.com"
http.basic_auth(data['username'], data['password'])
http_post "/api/twitter/statuses/update.xml",
'status' => status,
'source' => 'GitHub',
'paste_format' => 'textile',
'paste_text' => paste
end
end
end
| marko-asplund/github-services | services/presently.rb | Ruby | mit | 1,116 |
#include "ofApp.h"
#include "ofAppGlutWindow.h"
int main() {
ofAppGlutWindow window;
ofSetupOpenGL(&window, 512, 512, OF_WINDOW);
ofRunApp(new ofApp());
}
| Giladx/BlindSelfPortrait | EraserLine/src/main.cpp | C++ | mit | 159 |
'use strict';
var bitcore = require('bitcore-lib');
var $ = bitcore.util.preconditions;
var _ = bitcore.deps._;
var path = require('path');
var fs = require('fs');
var utils = require('../utils');
/**
* Will return the path and bitcore-node configuration
* @param {String} cwd - The absolute path to the current working directory
*/
function findConfig(cwd) {
$.checkArgument(_.isString(cwd), 'Argument should be a string');
$.checkArgument(utils.isAbsolutePath(cwd), 'Argument should be an absolute path');
var directory = String(cwd);
while (!fs.existsSync(path.resolve(directory, 'bitcore-node.json'))) {
directory = path.resolve(directory, '../');
if (directory === '/') {
return false;
}
}
return {
path: directory,
config: require(path.resolve(directory, 'bitcore-node.json'))
};
}
module.exports = findConfig;
| braydonf/bitcore-node | lib/scaffold/find-config.js | JavaScript | mit | 863 |
require_relative '../executor.rb'
require_relative '../../thumbnail_generator.rb'
class GenerateThumbnailJob < Tabula::Background::Job
# args: (:file, :output_dir, :thumbnail_sizes, :page_index_job_uuid)
def perform
file_id = options[:file_id]
upload_id = self.uuid
filepath = options[:filepath]
output_dir = options[:output_dir]
thumbnail_sizes = options[:thumbnail_sizes]
generator = JPedalThumbnailGenerator.new(filepath, output_dir, thumbnail_sizes)
generator.add_observer(self, :at)
generator.generate_thumbnails!
end
end
| mr-justin/tabula | lib/tabula_job_executor/jobs/generate_thumbnails.rb | Ruby | mit | 570 |
Experiment(description='No with centred periodic',
data_dir='../data/tsdlr/',
max_depth=8,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=4,
max_jobs=600,
verbose=False,
make_predictions=False,
skip_complete=True,
results_dir='../results/2013-09-07/',
iters=250,
base_kernels='StepTanh,CenPer,Cos,Lin,SE,Const,MT5,IMT3Lin',
zero_mean=True,
random_seed=1,
period_heuristic=5,
subset=True,
subset_size=250,
full_iters=0,
bundle_size=5)
| jamesrobertlloyd/gpss-research | experiments/2013-09-07.py | Python | mit | 710 |
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-dialog] {
display: flex;
flex-direction: column;
width: 100%;
margin-right: auto;
margin-left: auto;
outline: none;
background: white;
border-radius: var(--size-gap);
box-shadow: 0 var(--size-gap-half) var(--size-gap-double)
rgba(0, 0, 0, 0.25);
max-height: calc(100% - 56px);
overflow-y: hidden;
}
@media (max-height: 812px) {
[data-nextjs-dialog-overlay] {
max-height: calc(100% - 15px);
}
}
@media (min-width: 576px) {
[data-nextjs-dialog] {
max-width: 540px;
box-shadow: 0 var(--size-gap) var(--size-gap-quad) rgba(0, 0, 0, 0.25);
}
}
@media (min-width: 768px) {
[data-nextjs-dialog] {
max-width: 720px;
}
}
@media (min-width: 992px) {
[data-nextjs-dialog] {
max-width: 960px;
}
}
[data-nextjs-dialog-banner] {
position: relative;
}
[data-nextjs-dialog-banner].banner-warning {
border-color: var(--color-ansi-yellow);
}
[data-nextjs-dialog-banner].banner-error {
border-color: var(--color-ansi-red);
}
[data-nextjs-dialog-banner]::after {
z-index: 2;
content: '';
position: absolute;
top: 0;
right: 0;
width: 100%;
/* banner width: */
border-top-width: var(--size-gap-half);
border-bottom-width: 0;
border-top-style: solid;
border-bottom-style: solid;
border-top-color: inherit;
border-bottom-color: transparent;
}
[data-nextjs-dialog-content] {
overflow-y: auto;
border: none;
margin: 0;
/* calc(padding + banner width offset) */
padding: calc(var(--size-gap-double) + var(--size-gap-half))
var(--size-gap-double);
height: 100%;
display: flex;
flex-direction: column;
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-header] {
flex-shrink: 0;
margin-bottom: var(--size-gap-double);
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-body] {
position: relative;
flex: 1 1 auto;
}
`
export { styles }
| flybayer/next.js | packages/react-dev-overlay/src/internal/components/Dialog/styles.ts | TypeScript | mit | 2,088 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.Modules.ResourceManager.Services.Dto
{
using System.Runtime.Serialization;
/// <summary>
/// Represents a request for folder details.
/// </summary>
public class FolderDetailsRequest
{
/// <summary>
/// Gets or sets the id of the folder.
/// </summary>
[DataMember(Name = "folderId")]
public int FolderId { get; set; }
/// <summary>
/// Gets or sets the name of the folder.
/// </summary>
[DataMember(Name = "folderName")]
public string FolderName { get; set; }
/// <summary>
/// Gets or sets the <see cref="FolderPermissions"/>.
/// </summary>
[DataMember(Name = "permissions")]
public FolderPermissions Permissions { get; set; }
}
}
| dnnsoftware/Dnn.Platform | DNN Platform/Modules/ResourceManager/Services/Dto/FolderDetailsRequest.cs | C# | mit | 1,005 |
<div class="container-fluid">
<div class="row">
<div class="col-xs-6 col-xs-offset-3">
<div class="page-header" style="border:none;margin: 0px;">
<h1><?= $this->slogan ?></h1>
</div>
</div>
</div>
<div class="row" style="margin-bottom: 2em;">
<div class="col-xs-6 col-xs-offset-3">
<form action="/user/register_submit" method="post">
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="请您输入用户名">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="请您输入密码">
</div>
<button type="submit" class="col-xs-12 col-sm-12 btn btn-success">注册</button>
</form>
<br/> <br/> <br/>
<a href="/user/login" class="col-xs-4 col-sm-4 btn btn-link">登入</a>
<span class="col-xs-4 col-sm-4 "></span>
<a href="#" class="col-xs-4 col-sm-4 btn btn-link">忘记密码?</a>
</div>
</div>
</div> | tecshuttle/tiegan | application/views_dev/user/register.php | PHP | mit | 1,180 |
require 'ruboto/util/toast'
# Services are complicated and don't really make sense unless you
# show the interaction between the Service and other parts of your
# app.
# For now, just take a look at the explanation and example in
# online:
# http://developer.android.com/reference/android/app/Service.html
class SampleService
def onStartCommand(intent, flags, startId)
toast 'Hello from the service'
android.app.Service::START_NOT_STICKY
end
end
| lucasallan/ruboto | assets/samples/sample_service.rb | Ruby | mit | 459 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @namespace
*/
namespace Zend\Measure;
/**
* Class for handling torque conversions
*
* @uses Zend\Measure\Abstract
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Torque extends AbstractMeasure
{
const STANDARD = 'NEWTON_METER';
const DYNE_CENTIMETER = 'DYNE_CENTIMETER';
const GRAM_CENTIMETER = 'GRAM_CENTIMETER';
const KILOGRAM_CENTIMETER = 'KILOGRAM_CENTIMETER';
const KILOGRAM_METER = 'KILOGRAM_METER';
const KILONEWTON_METER = 'KILONEWTON_METER';
const KILOPOND_METER = 'KILOPOND_METER';
const MEGANEWTON_METER = 'MEGANEWTON_METER';
const MICRONEWTON_METER = 'MICRONEWTON_METER';
const MILLINEWTON_METER = 'MILLINEWTON_METER';
const NEWTON_CENTIMETER = 'NEWTON_CENTIMETER';
const NEWTON_METER = 'NEWTON_METER';
const OUNCE_FOOT = 'OUNCE_FOOT';
const OUNCE_INCH = 'OUNCE_INCH';
const POUND_FOOT = 'POUND_FOOT';
const POUNDAL_FOOT = 'POUNDAL_FOOT';
const POUND_INCH = 'POUND_INCH';
/**
* Calculations for all torque units
*
* @var array
*/
protected $_units = array(
'DYNE_CENTIMETER' => array('0.0000001', 'dyncm'),
'GRAM_CENTIMETER' => array('0.0000980665', 'gcm'),
'KILOGRAM_CENTIMETER' => array('0.0980665', 'kgcm'),
'KILOGRAM_METER' => array('9.80665', 'kgm'),
'KILONEWTON_METER' => array('1000', 'kNm'),
'KILOPOND_METER' => array('9.80665', 'kpm'),
'MEGANEWTON_METER' => array('1000000', 'MNm'),
'MICRONEWTON_METER' => array('0.000001', 'µNm'),
'MILLINEWTON_METER' => array('0.001', 'mNm'),
'NEWTON_CENTIMETER' => array('0.01', 'Ncm'),
'NEWTON_METER' => array('1', 'Nm'),
'OUNCE_FOOT' => array('0.084738622', 'ozft'),
'OUNCE_INCH' => array(array('' => '0.084738622', '/' => '12'), 'ozin'),
'POUND_FOOT' => array(array('' => '0.084738622', '*' => '16'), 'lbft'),
'POUNDAL_FOOT' => array('0.0421401099752144', 'plft'),
'POUND_INCH' => array(array('' => '0.084738622', '/' => '12', '*' => '16'), 'lbin'),
'STANDARD' => 'NEWTON_METER'
);
}
| dynamicguy/gpweb | src/vendor/zend/library/Zend/Measure/Torque.php | PHP | mit | 3,276 |
const DOUBLE_QUOTE_STRING_STATE = 'double-quote-string-state';
const SINGLE_QUOTE_STRING_STATE = 'single-quote-string-state';
const LINE_COMMENT_STATE = 'line-comment-state';
const BLOCK_COMMENT_STATE = 'block-comment-state';
const ETC_STATE = 'etc-state';
function extractComments(str) {
let state = ETC_STATE;
let i = 0;
const comments = [];
let currentComment = null;
while (i + 1 < str.length) {
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '/') {
state = LINE_COMMENT_STATE;
currentComment = {
type: 'LineComment',
range: [i]
};
i += 2;
continue;
}
if (state === LINE_COMMENT_STATE && str[i] === '\n') {
state = ETC_STATE;
currentComment.range.push(i);
comments.push(currentComment);
currentComment = null;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '*') {
state = BLOCK_COMMENT_STATE;
currentComment = {
type: 'BlockComment',
range: [i]
};
i += 2;
continue;
}
if (state === BLOCK_COMMENT_STATE && str[i] === '*' && str[i + 1] === '/') {
state = ETC_STATE;
currentComment.range.push(i + 2);
comments.push(currentComment);
currentComment = null;
i += 2;
continue;
}
if (state === ETC_STATE && str[i] === '"') {
state = DOUBLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === DOUBLE_QUOTE_STRING_STATE &&
str[i] === '"' &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === "'") {
state = SINGLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === SINGLE_QUOTE_STRING_STATE &&
str[i] === "'" &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
i += 1;
}
if (currentComment !== null && currentComment.type === 'LineComment') {
if (str[i] === '\n') {
currentComment.range.push(str.length - 1);
} else {
currentComment.range.push(str.length);
}
comments.push(currentComment);
}
return comments.map((comment) => {
const start = comment.range[0] + 2;
const end =
comment.type === 'LineComment' ? comment.range[1] : comment.range[1] - 2;
const raw = str.slice(start, end);
// removing the leading asterisks from the value is necessary for jsdoc-style comments
let value = raw;
if (comment.type === 'BlockComment') {
value = value
.split('\n')
.map((x) => x.replace(/^\s*\*/, ''))
.join('\n')
.trimRight();
}
return {
...comment,
raw,
value
};
});
}
module.exports = extractComments;
| glenngillen/dotfiles | .vscode/extensions/juanblanco.solidity-0.0.120/node_modules/solidity-comments-extractor/index.js | JavaScript | mit | 2,960 |
/*
* The MIT License
*
* Copyright (c) 2015 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.analysis;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.reference.ReferenceSequenceFileFactory;
import htsjdk.samtools.util.SequenceUtil;
import htsjdk.samtools.util.StringUtil;
import java.io.File;
/** Utilities to calculate GC Bias
* Created by kbergin on 9/23/15.
*/
public class GcBiasUtils {
/////////////////////////////////////////////////////////////////////////////
// Calculates GC as a number from 0 to 100 in the specified window.
// If the window includes more than five no-calls then -1 is returned.
/////////////////////////////////////////////////////////////////////////////
public static int calculateGc(final byte[] bases, final int startIndex, final int endIndex, final CalculateGcState state) {
if (state.init) {
state.init = false;
state.gcCount = 0;
state.nCount = 0;
for (int i = startIndex; i < endIndex; ++i) {
final byte base = bases[i];
if (SequenceUtil.basesEqual(base, (byte)'G') || SequenceUtil.basesEqual(base, (byte)'C')) ++state.gcCount;
else if (SequenceUtil.basesEqual(base, (byte)'N')) ++state.nCount;
}
} else {
final byte newBase = bases[endIndex - 1];
if (SequenceUtil.basesEqual(newBase, (byte)'G') || SequenceUtil.basesEqual(newBase, (byte)'C')) ++state.gcCount;
else if (newBase == 'N') ++state.nCount;
if (SequenceUtil.basesEqual(state.priorBase, (byte)'G') || SequenceUtil.basesEqual(state.priorBase, (byte)'C')) --state.gcCount;
else if (SequenceUtil.basesEqual(state.priorBase, (byte)'N')) --state.nCount;
}
state.priorBase = bases[startIndex];
if (state.nCount > 4) return -1;
else return (state.gcCount * 100) / (endIndex - startIndex);
}
/////////////////////////////////////////////////////////////////////////////
// Calculate number of 100bp windows in the refBases passed in that fall into
// each gc content bin (0-100% gc)
/////////////////////////////////////////////////////////////////////////////
public static int[] calculateRefWindowsByGc(final int windows, final File referenceSequence, final int windowSize) {
final ReferenceSequenceFile refFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(referenceSequence);
ReferenceSequence ref;
final int [] windowsByGc = new int [windows];
while ((ref = refFile.nextSequence()) != null) {
final byte[] refBases = ref.getBases();
StringUtil.toUpperCase(refBases);
final int refLength = refBases.length;
final int lastWindowStart = refLength - windowSize;
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int gcBin = calculateGc(refBases, i, windowEnd, state);
if (gcBin != -1) windowsByGc[gcBin]++;
}
}
return windowsByGc;
}
/////////////////////////////////////////////////////////////////////////////
// Calculate all the GC values for all windows
/////////////////////////////////////////////////////////////////////////////
public static byte [] calculateAllGcs(final byte[] refBases, final int lastWindowStart, final int windowSize) {
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
final int refLength = refBases.length;
final byte[] gc = new byte[refLength + 1];
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int windowGc = calculateGc(refBases, i, windowEnd, state);
gc[i] = (byte) windowGc;
}
return gc;
}
/////////////////////////////////////////////////////////////////////////////
// Keeps track of current GC calculation state
/////////////////////////////////////////////////////////////////////////////
class CalculateGcState {
boolean init = true;
int nCount;
int gcCount;
byte priorBase;
}
}
| annkupi/picard | src/main/java/picard/analysis/GcBiasUtils.java | Java | mit | 5,467 |
var util = require('util');
/**
* @class Recorder
* @param {{retention: <Number>}} [options]
*/
var Recorder = function(options) {
this._records = [];
this._options = _.defaults(options || {}, {
retention: 300, // seconds
recordMaxSize: 200, // nb records
jsonMaxSize: 50,
format: '[{date} {level}] {message}'
});
};
Recorder.prototype = {
/**
* @returns {String}
*/
getFormattedRecords: function() {
return _.map(this.getRecords(), function(record) {
return this._recordFormatter(record);
}, this).join('\n');
},
/**
* @returns {{date: {Date}, messages: *[], context: {Object}}[]}
*/
getRecords: function() {
return this._records;
},
/**
* @param {*[]} messages
* @param {Object} context
*/
addRecord: function(messages, context) {
var record = {
date: this._getDate(),
messages: messages,
context: context
};
this._records.push(record);
this._cleanupRecords();
},
flushRecords: function() {
this._records = [];
},
/**
* @private
*/
_cleanupRecords: function() {
var retention = this._options.retention;
var recordMaxSize = this._options.recordMaxSize;
if (retention > 0) {
var retentionTime = this._getDate() - (retention * 1000);
this._records = _.filter(this._records, function(record) {
return record.date > retentionTime;
});
}
if (recordMaxSize > 0 && this._records.length > recordMaxSize) {
this._records = this._records.slice(-recordMaxSize);
}
},
/**
* @param {{date: {Date}, messages: *[], context: {Object}}} record
* @returns {String}
* @private
*/
_recordFormatter: function(record) {
var log = this._options.format;
_.each({
date: record.date.toISOString(),
level: record.context.level.name,
message: this._messageFormatter(record.messages)
}, function(value, key) {
var pattern = new RegExp('{' + key + '}', 'g');
log = log.replace(pattern, value);
});
return log;
},
/**
* @param {*[]} messages
* @returns {String}
* @private
*/
_messageFormatter: function(messages) {
var clone = _.toArray(messages);
var index, value, encoded;
for (index = 0; index < clone.length; index++) {
encoded = value = clone[index];
if (_.isString(value) && 0 === index) {
// about console.log and util.format substitution,
// see https://developers.google.com/web/tools/chrome-devtools/debug/console/console-write#string-substitution-and-formatting
// and https://nodejs.org/api/util.html#util_util_format_format
value = value.replace(/%[idfoO]/g, '%s');
} else if (value instanceof RegExp) {
value = value.toString();
} else if (value instanceof Date) {
value = value.toISOString();
} else if (_.isObject(value) && value._class) {
value = '[' + value._class + (value._id && value._id.id ? ':' + value._id.id : '') + ']';
} else if (_.isObject(value) && /^\[object ((?!Object).)+\]$/.test(value.toString())) {
value = value.toString();
}
try {
if (_.isString(value) || _.isNumber(value)) {
encoded = value;
} else {
encoded = JSON.stringify(value);
if (encoded.length > this._options.jsonMaxSize) {
encoded = encoded.slice(0, this._options.jsonMaxSize - 4) + '…' + encoded[encoded.length - 1];
}
}
} catch (e) {
if (_.isUndefined(value)) {
encoded = 'undefined';
} else if (_.isNull(value)) {
encoded = 'null';
} else {
encoded = '[unknown]'
}
}
clone[index] = encoded;
}
return util.format.apply(util.format, clone);
},
/**
* @returns {Date}
* @private
*/
_getDate: function() {
return new Date();
}
};
module.exports = Recorder;
| njam/CM | client-vendor/source/logger/handlers/recorder.js | JavaScript | mit | 3,930 |
using ElectronicObserver.Utility.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicObserver.Data.ShipGroup
{
[DataContract(Name = "ExpressionManager")]
public sealed class ExpressionManager : DataStorage, ICloneable
{
[DataMember]
public List<ExpressionList> Expressions { get; set; }
[IgnoreDataMember]
private Expression<Func<ShipData, bool>> predicate;
[IgnoreDataMember]
private Expression expression;
public ExpressionManager() : base()
{
Initialize();
}
public override void Initialize()
{
Expressions = new List<ExpressionList>();
predicate = null;
expression = null;
}
public ExpressionList this[int index]
{
get { return Expressions[index]; }
set { Expressions[index] = value; }
}
public void Compile()
{
Expression ex = null;
var paramex = Expression.Parameter(typeof(ShipData), "ship");
foreach (var exlist in Expressions)
{
if (!exlist.Enabled)
continue;
if (ex == null)
{
ex = exlist.Compile(paramex);
}
else
{
if (exlist.ExternalAnd)
{
ex = Expression.AndAlso(ex, exlist.Compile(paramex));
}
else
{
ex = Expression.OrElse(ex, exlist.Compile(paramex));
}
}
}
if (ex == null)
{
ex = Expression.Constant(true, typeof(bool)); //:-P
}
predicate = Expression.Lambda<Func<ShipData, bool>>(ex, paramex);
expression = ex;
}
public IEnumerable<ShipData> GetResult(IEnumerable<ShipData> list)
{
if (predicate == null)
throw new InvalidOperationException("式がコンパイルされていません。");
return list.AsQueryable().Where(predicate).AsEnumerable();
}
public bool IsAvailable => predicate != null;
public override string ToString()
{
if (Expressions == null)
return "(なし)";
StringBuilder sb = new StringBuilder();
foreach (var ex in Expressions)
{
if (!ex.Enabled)
continue;
else if (sb.Length == 0)
sb.Append(ex.ToString());
else
sb.AppendFormat(" {0} {1}", ex.ExternalAnd ? "かつ" : "または", ex.ToString());
}
if (sb.Length == 0)
sb.Append("(なし)");
return sb.ToString();
}
public string ToExpressionString()
{
return expression.ToString();
}
public ExpressionManager Clone()
{
var clone = (ExpressionManager)MemberwiseClone();
clone.Expressions = Expressions?.Select(e => e.Clone()).ToList();
clone.predicate = null;
clone.expression = null;
return clone;
}
object ICloneable.Clone()
{
return Clone();
}
}
}
| CAWAS/ElectronicObserverExtended | ElectronicObserver/Data/ShipGroup/ExpressionManager.cs | C# | mit | 2,741 |
import pprint
import test.test_support
import unittest
import test.test_set
try:
uni = unicode
except NameError:
def uni(x):
return x
# list, tuple and dict subclasses that do or don't overwrite __repr__
class list2(list):
pass
class list3(list):
def __repr__(self):
return list.__repr__(self)
class tuple2(tuple):
pass
class tuple3(tuple):
def __repr__(self):
return tuple.__repr__(self)
class dict2(dict):
pass
class dict3(dict):
def __repr__(self):
return dict.__repr__(self)
class QueryTestCase(unittest.TestCase):
def setUp(self):
self.a = range(100)
self.b = range(200)
self.a[-12] = self.b
def test_basic(self):
# Verify .isrecursive() and .isreadable() w/o recursion
pp = pprint.PrettyPrinter()
for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"),
self.a, self.b):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_knotted(self):
# Verify .isrecursive() and .isreadable() w/ recursion
# Tie a knot.
self.b[67] = self.a
# Messy dict.
self.d = {}
self.d[0] = self.d[1] = self.d[2] = self.d
pp = pprint.PrettyPrinter()
for icky in self.a, self.b, self.d, (self.d, self.d):
self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
self.assertFalse(pp.isreadable(icky), "expected not isreadable")
# Break the cycles.
self.d.clear()
del self.a[:]
del self.b[:]
for safe in self.a, self.b, self.d, (self.d, self.d):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_unreadable(self):
# Not recursive but not readable anyway
pp = pprint.PrettyPrinter()
for unreadable in type(3), pprint, pprint.isrecursive:
# module-level convenience functions
self.assertFalse(pprint.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pprint.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pp.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
def test_same_as_repr(self):
# Simple objects, small containers and classes that overwrite __repr__
# For those the result should be the same as repr().
# Ahem. The docs don't say anything about that -- this appears to
# be testing an implementation quirk. Starting in Python 2.5, it's
# not true for dicts: pprint always sorts dicts by key now; before,
# it sorted a dict display if and only if the display required
# multiple lines. For that reason, dicts with more than one element
# aren't tested here.
for simple in (0, 0L, 0+0j, 0.0, "", uni(""),
(), tuple2(), tuple3(),
[], list2(), list3(),
{}, dict2(), dict3(),
self.assertTrue, pprint,
-6, -6L, -6-6j, -1.5, "x", uni("x"), (3,), [3], {3: 6},
(1,2), [3,4], {5: 6},
tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
[3,4], list2([3,4]), list3([3,4]), list3(range(100)),
dict2({5: 6}), dict3({5: 6}),
range(10, -11, -1)
):
native = repr(simple)
for function in "pformat", "saferepr":
f = getattr(pprint, function)
got = f(simple)
self.assertEqual(native, got,
"expected %s got %s from pprint.%s" %
(native, got, function))
def test_basic_line_wrap(self):
# verify basic line-wrapping operation
o = {'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}
exp = """\
{'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}"""
for type in [dict, dict2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = range(100)
exp = '[%s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = tuple(range(100))
exp = '(%s)' % ',\n '.join(map(str, o))
for type in [tuple, tuple2]:
self.assertEqual(pprint.pformat(type(o)), exp)
# indent parameter
o = range(100)
exp = '[ %s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o), indent=4), exp)
def test_nested_indentations(self):
o1 = list(range(10))
o2 = dict(first=1, second=2, third=3)
o = [o1, o2]
expected = """\
[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
{ 'first': 1,
'second': 2,
'third': 3}]"""
self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
def test_sorted_dict(self):
# Starting in Python 2.5, pprint sorts dict displays by key regardless
# of how small the dictionary may be.
# Before the change, on 32-bit Windows pformat() gave order
# 'a', 'c', 'b' here, so this test failed.
d = {'a': 1, 'b': 1, 'c': 1}
self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
self.assertEqual(pprint.pformat([d, d]),
"[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
# The next one is kind of goofy. The sorted order depends on the
# alphabetic order of type names: "int" < "str" < "tuple". Before
# Python 2.5, this was in the test_same_as_repr() test. It's worth
# keeping around for now because it's one of few tests of pprint
# against a crazy mix of types.
self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
def test_subclassing(self):
o = {'names with spaces': 'should be presented using repr()',
'others.should.not.be': 'like.this'}
exp = """\
{'names with spaces': 'should be presented using repr()',
others.should.not.be: like.this}"""
self.assertEqual(DottedPrettyPrinter().pformat(o), exp)
def test_set_reprs(self):
self.assertEqual(pprint.pformat(set()), 'set()')
self.assertEqual(pprint.pformat(set(range(3))), 'set([0, 1, 2])')
self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
self.assertEqual(pprint.pformat(frozenset(range(3))), 'frozenset([0, 1, 2])')
cube_repr_tgt = """\
{frozenset([]): frozenset([frozenset([2]), frozenset([0]), frozenset([1])]),
frozenset([0]): frozenset([frozenset(),
frozenset([0, 2]),
frozenset([0, 1])]),
frozenset([1]): frozenset([frozenset(),
frozenset([1, 2]),
frozenset([0, 1])]),
frozenset([2]): frozenset([frozenset(),
frozenset([1, 2]),
frozenset([0, 2])]),
frozenset([1, 2]): frozenset([frozenset([2]),
frozenset([1]),
frozenset([0, 1, 2])]),
frozenset([0, 2]): frozenset([frozenset([2]),
frozenset([0]),
frozenset([0, 1, 2])]),
frozenset([0, 1]): frozenset([frozenset([0]),
frozenset([1]),
frozenset([0, 1, 2])]),
frozenset([0, 1, 2]): frozenset([frozenset([1, 2]),
frozenset([0, 2]),
frozenset([0, 1])])}"""
cube = test.test_set.cube(3)
# XXX issues of dictionary order, and for the case below,
# order of items in the frozenset([...]) representation.
# Whether we get precisely cube_repr_tgt or not is open
# to implementation-dependent choices (this test probably
# fails horribly in CPython if we tweak the dict order too).
got = pprint.pformat(cube)
if test.test_support.check_impl_detail(cpython=True):
self.assertEqual(got, cube_repr_tgt)
else:
self.assertEqual(eval(got), cube)
cubo_repr_tgt = """\
{frozenset([frozenset([0, 2]), frozenset([0])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([0, 1]), frozenset([1])]): frozenset([frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([1])])]),
frozenset([frozenset([1, 2]), frozenset([1])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([1, 2]), frozenset([2])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset([2]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([]), frozenset([0])]): frozenset([frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([]), frozenset([1])]): frozenset([frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([2])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([2]), frozenset([])]): frozenset([frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([0, 1, 2]), frozenset([0, 1])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([0]), frozenset([0, 1])]): frozenset([frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([2]), frozenset([0, 2])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([0, 1, 2]), frozenset([0, 2])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([1, 2]), frozenset([0, 1, 2])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset([1]),
frozenset([1,
2])])])}"""
cubo = test.test_set.linegraph(cube)
got = pprint.pformat(cubo)
if test.test_support.check_impl_detail(cpython=True):
self.assertEqual(got, cubo_repr_tgt)
else:
self.assertEqual(eval(got), cubo)
def test_depth(self):
nested_tuple = (1, (2, (3, (4, (5, 6)))))
nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
lv1_tuple = '(1, (...))'
lv1_dict = '{1: {...}}'
lv1_list = '[1, [...]]'
self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
class DottedPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, str):
if ' ' in object:
return repr(object), 1, 0
else:
return object, 0, 0
else:
return pprint.PrettyPrinter.format(
self, object, context, maxlevels, level)
def test_main():
test.test_support.run_unittest(QueryTestCase)
if __name__ == "__main__":
test_main()
| bussiere/pypyjs | website/demo/home/rfk/repos/pypy/lib-python/2.7/test/test_pprint.py | Python | mit | 25,311 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as path from 'vs/base/common/path';
import { Workspace, toWorkspaceFolders, WorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { URI } from 'vs/base/common/uri';
import { IRawFileWorkspaceFolder } from 'vs/platform/workspaces/common/workspaces';
import { isWindows } from 'vs/base/common/platform';
suite('Workspace', () => {
const fileFolder = isWindows ? 'c:\\src' : '/src';
const abcFolder = isWindows ? 'c:\\abc' : '/abc';
const testFolderUri = URI.file(path.join(fileFolder, 'test'));
const mainFolderUri = URI.file(path.join(fileFolder, 'main'));
const test1FolderUri = URI.file(path.join(fileFolder, 'test1'));
const test2FolderUri = URI.file(path.join(fileFolder, 'test2'));
const test3FolderUri = URI.file(path.join(fileFolder, 'test3'));
const abcTest1FolderUri = URI.file(path.join(abcFolder, 'test1'));
const abcTest3FolderUri = URI.file(path.join(abcFolder, 'test3'));
const workspaceConfigUri = URI.file(path.join(fileFolder, 'test.code-workspace'));
test('getFolder returns the folder with given uri', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 });
let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), expected, new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 2 })]);
const actual = testObject.getFolder(expected.uri);
assert.equal(actual, expected);
});
test('getFolder returns the folder if the uri is sub', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 0 });
let testObject = new Workspace('', [expected, new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 1 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 2 })]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'test/a')));
assert.equal(actual, expected);
});
test('getFolder returns the closest folder if the uri is sub', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 });
let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 }), expected]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'test/a')));
assert.equal(actual, expected);
});
test('getFolder returns the folder even if the uri has query path', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 });
let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 }), expected]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'test/a')).with({ query: 'somequery' }));
assert.equal(actual, expected);
});
test('getFolder returns null if the uri is not sub', () => {
let testObject = new Workspace('', [new WorkspaceFolder({ uri: testFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 })]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'main/a')));
assert.equal(actual, undefined);
});
test('toWorkspaceFolders with single absolute folder', () => {
const actual = toWorkspaceFolders([{ path: '/src/test' }], workspaceConfigUri);
assert.equal(actual.length, 1);
assert.equal(actual[0].uri.fsPath, testFolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test');
});
test('toWorkspaceFolders with single relative folder', () => {
const actual = toWorkspaceFolders([{ path: './test' }], workspaceConfigUri);
assert.equal(actual.length, 1);
assert.equal(actual[0].uri.fsPath, testFolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, './test');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test');
});
test('toWorkspaceFolders with single absolute folder with name', () => {
const actual = toWorkspaceFolders([{ path: '/src/test', name: 'hello' }], workspaceConfigUri);
assert.equal(actual.length, 1);
assert.equal(actual[0].uri.fsPath, testFolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'hello');
});
test('toWorkspaceFolders with multiple unique absolute folders', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3' }, { path: '/src/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'test3');
assert.equal(actual[2].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/src/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple unique absolute folders with names', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3', name: 'noName' }, { path: '/src/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'noName');
assert.equal(actual[2].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/src/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple unique absolute and relative folders', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/abc/test3', name: 'noName' }, { path: './test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, abcTest3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/abc/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'noName');
assert.equal(actual[2].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, './test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple absolute folders with duplicates', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test2', name: 'noName' }, { path: '/src/test1' }], workspaceConfigUri);
assert.equal(actual.length, 2);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test1');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'test1');
});
test('toWorkspaceFolders with multiple absolute and relative folders with duplicates', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3', name: 'noName' }, { path: './test3' }, { path: '/abc/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'noName');
assert.equal(actual[2].uri.fsPath, abcTest1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/abc/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple absolute and relative folders with invalid paths', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '', name: 'noName' }, { path: './test3' }, { path: '/abc/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, './test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'test3');
assert.equal(actual[2].uri.fsPath, abcTest1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/abc/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
});
| the-ress/vscode | src/vs/platform/workspace/test/common/workspace.test.ts | TypeScript | mit | 10,178 |
# frozen_string_literal: true
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/string/filters"
require "concurrent/map"
require "set"
module ActiveRecord
module Core
extend ActiveSupport::Concern
FILTERED = "[FILTERED]" # :nodoc:
included do
##
# :singleton-method:
#
# Accepts a logger conforming to the interface of Log4r which is then
# passed on to any new database connections made and which can be
# retrieved on both a class and instance level by calling +logger+.
mattr_accessor :logger, instance_writer: false
##
# :singleton-method:
#
# Specifies if the methods calling database queries should be logged below
# their relevant queries. Defaults to false.
mattr_accessor :verbose_query_logs, instance_writer: false, default: false
##
# Contains the database configuration - as is typically stored in config/database.yml -
# as an ActiveRecord::DatabaseConfigurations object.
#
# For example, the following database.yml...
#
# development:
# adapter: sqlite3
# database: db/development.sqlite3
#
# production:
# adapter: sqlite3
# database: db/production.sqlite3
#
# ...would result in ActiveRecord::Base.configurations to look like this:
#
# #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
# @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>,
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="production",
# @spec_name="primary", @config={"adapter"=>"mysql2", "database"=>"db/production.sqlite3"}>
# ]>
def self.configurations=(config)
@@configurations = ActiveRecord::DatabaseConfigurations.new(config)
end
self.configurations = {}
# Returns fully resolved ActiveRecord::DatabaseConfigurations object
def self.configurations
@@configurations
end
##
# :singleton-method:
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
# dates and times from the database. This is set to :utc by default.
mattr_accessor :default_timezone, instance_writer: false, default: :utc
##
# :singleton-method:
# Specifies the format to use when dumping the database schema with Rails'
# Rakefile. If :sql, the schema is dumped as (potentially database-
# specific) SQL statements. If :ruby, the schema is dumped as an
# ActiveRecord::Schema file which can be loaded into any database that
# supports migrations. Use :ruby if you want to have different database
# adapters for, e.g., your development and test environments.
mattr_accessor :schema_format, instance_writer: false, default: :ruby
##
# :singleton-method:
# Specifies if an error should be raised if the query has an order being
# ignored when doing batch queries. Useful in applications where the
# scope being ignored is error-worthy, rather than a warning.
mattr_accessor :error_on_ignored_order, instance_writer: false, default: false
# :singleton-method:
# Specify the behavior for unsafe raw query methods. Values are as follows
# deprecated - Warnings are logged when unsafe raw SQL is passed to
# query methods.
# disabled - Unsafe raw SQL passed to query methods results in
# UnknownAttributeReference exception.
mattr_accessor :allow_unsafe_raw_sql, instance_writer: false, default: :deprecated
##
# :singleton-method:
# Specify whether or not to use timestamps for migration versions
mattr_accessor :timestamped_migrations, instance_writer: false, default: true
##
# :singleton-method:
# Specify whether schema dump should happen at the end of the
# db:migrate rails command. This is true by default, which is useful for the
# development environment. This should ideally be false in the production
# environment where dumping schema is rarely needed.
mattr_accessor :dump_schema_after_migration, instance_writer: false, default: true
##
# :singleton-method:
# Specifies which database schemas to dump when calling db:structure:dump.
# If the value is :schema_search_path (the default), any schemas listed in
# schema_search_path are dumped. Use :all to dump all schemas regardless
# of schema_search_path, or a string of comma separated schemas for a
# custom list.
mattr_accessor :dump_schemas, instance_writer: false, default: :schema_search_path
##
# :singleton-method:
# Specify a threshold for the size of query result sets. If the number of
# records in the set exceeds the threshold, a warning is logged. This can
# be used to identify queries which load thousands of records and
# potentially cause memory bloat.
mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false
mattr_accessor :maintain_test_schema, instance_accessor: false
mattr_accessor :belongs_to_required_by_default, instance_accessor: false
class_attribute :default_connection_handler, instance_writer: false
self.filter_attributes = []
def self.connection_handler
ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
end
def self.connection_handler=(handler)
ActiveRecord::RuntimeRegistry.connection_handler = handler
end
self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
end
module ClassMethods
def initialize_find_by_cache # :nodoc:
@find_by_statement_cache = { true => Concurrent::Map.new, false => Concurrent::Map.new }
end
def inherited(child_class) # :nodoc:
# initialize cache at class definition for thread safety
child_class.initialize_find_by_cache
super
end
def find(*ids) # :nodoc:
# We don't have cache keys for this stuff yet
return super unless ids.length == 1
return super if block_given? ||
primary_key.nil? ||
scope_attributes? ||
columns_hash.include?(inheritance_column)
id = ids.first
return super if StatementCache.unsupported_value?(id)
key = primary_key
statement = cached_find_by_statement(key) { |params|
where(key => params.bind).limit(1)
}
record = statement.execute([id], connection).first
unless record
raise RecordNotFound.new("Couldn't find #{name} with '#{primary_key}'=#{id}",
name, primary_key, id)
end
record
rescue ::RangeError
raise RecordNotFound.new("Couldn't find #{name} with an out of range value for '#{primary_key}'",
name, primary_key)
end
def find_by(*args) # :nodoc:
return super if scope_attributes? || reflect_on_all_aggregations.any?
hash = args.first
return super if !(Hash === hash) || hash.values.any? { |v|
StatementCache.unsupported_value?(v)
}
# We can't cache Post.find_by(author: david) ...yet
return super unless hash.keys.all? { |k| columns_hash.has_key?(k.to_s) }
keys = hash.keys
statement = cached_find_by_statement(keys) { |params|
wheres = keys.each_with_object({}) { |param, o|
o[param] = params.bind
}
where(wheres).limit(1)
}
begin
statement.execute(hash.values, connection).first
rescue TypeError
raise ActiveRecord::StatementInvalid
rescue ::RangeError
nil
end
end
def find_by!(*args) # :nodoc:
find_by(*args) || raise(RecordNotFound.new("Couldn't find #{name}", name))
end
def initialize_generated_modules # :nodoc:
generated_association_methods
end
def generated_association_methods # :nodoc:
@generated_association_methods ||= begin
mod = const_set(:GeneratedAssociationMethods, Module.new)
private_constant :GeneratedAssociationMethods
include mod
mod
end
end
# Returns columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes
if defined?(@filter_attributes)
@filter_attributes
else
superclass.filter_attributes
end
end
# Specifies columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes=(attributes_names)
@filter_attributes = attributes_names.map(&:to_s).to_set
end
# Returns a string like 'Post(id:integer, title:string, body:text)'
def inspect # :nodoc:
if self == Base
super
elsif abstract_class?
"#{super}(abstract)"
elsif !connected?
"#{super} (call '#{super}.connection' to establish a connection)"
elsif table_exists?
attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ", "
"#{super}(#{attr_list})"
else
"#{super}(Table doesn't exist)"
end
end
# Overwrite the default class equality method to provide support for decorated models.
def ===(object) # :nodoc:
object.is_a?(self)
end
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
#
# class Post < ActiveRecord::Base
# scope :published_and_commented, -> { published.and(arel_table[:comments_count].gt(0)) }
# end
def arel_table # :nodoc:
@arel_table ||= Arel::Table.new(table_name, type_caster: type_caster)
end
def arel_attribute(name, table = arel_table) # :nodoc:
name = attribute_alias(name) if attribute_alias?(name)
table[name]
end
def predicate_builder # :nodoc:
@predicate_builder ||= PredicateBuilder.new(table_metadata)
end
def type_caster # :nodoc:
TypeCaster::Map.new(self)
end
private
def cached_find_by_statement(key, &block)
cache = @find_by_statement_cache[connection.prepared_statements]
cache.compute_if_absent(key) { StatementCache.create(connection, &block) }
end
def relation
relation = Relation.create(self)
if finder_needs_type_condition? && !ignore_default_scope?
relation.where!(type_condition)
relation.create_with!(inheritance_column.to_s => sti_name)
else
relation
end
end
def table_metadata
TableMetadata.new(self, arel_table)
end
end
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
# In both instances, valid attribute keys are determined by the column names of the associated table --
# hence you can't have attributes that aren't part of the table columns.
#
# ==== Example:
# # Instantiates a single new object
# User.new(first_name: 'Jamie')
def initialize(attributes = nil)
self.class.define_attribute_methods
@attributes = self.class._default_attributes.deep_dup
init_internals
initialize_internals_callback
assign_attributes(attributes) if attributes
yield self if block_given?
_run_initialize_callbacks
end
# Initialize an empty model object from +coder+. +coder+ should be
# the result of previously encoding an Active Record model, using
# #encode_with.
#
# class Post < ActiveRecord::Base
# end
#
# old_post = Post.new(title: "hello world")
# coder = {}
# old_post.encode_with(coder)
#
# post = Post.allocate
# post.init_with(coder)
# post.title # => 'hello world'
def init_with(coder)
coder = LegacyYamlAdapter.convert(self.class, coder)
@attributes = self.class.yaml_encoder.decode(coder)
init_internals
@new_record = coder["new_record"]
self.class.define_attribute_methods
yield self if block_given?
_run_find_callbacks
_run_initialize_callbacks
self
end
##
# Initializer used for instantiating objects that have been read from the
# database. +attributes+ should be an attributes object, and unlike the
# `initialize` method, no assignment calls are made per attribute.
#
# :nodoc:
def init_from_db(attributes)
init_internals
@new_record = false
@attributes = attributes
self.class.define_attribute_methods
yield self if block_given?
_run_find_callbacks
_run_initialize_callbacks
self
end
##
# :method: clone
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
# That means that modifying attributes of the clone will modify the original, since they will both point to the
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
#
# user = User.first
# new_user = user.clone
# user.name # => "Bob"
# new_user.name = "Joe"
# user.name # => "Joe"
#
# user.object_id == new_user.object_id # => false
# user.name.object_id == new_user.name.object_id # => true
#
# user.name.object_id == user.dup.name.object_id # => false
##
# :method: dup
# Duped objects have no id assigned and are treated as new records. Note
# that this is a "shallow" copy as it copies the object's attributes
# only, not its associations. The extent of a "deep" copy is application
# specific and is therefore left to the application to implement according
# to its need.
# The dup method does not preserve the timestamps (created|updated)_(at|on).
##
def initialize_dup(other) # :nodoc:
@attributes = @attributes.deep_dup
@attributes.reset(self.class.primary_key)
_run_initialize_callbacks
@new_record = true
@destroyed = false
@_start_transaction_state = {}
@transaction_state = nil
super
end
# Populate +coder+ with attributes about this record that should be
# serialized. The structure of +coder+ defined in this method is
# guaranteed to match the structure of +coder+ passed to the #init_with
# method.
#
# Example:
#
# class Post < ActiveRecord::Base
# end
# coder = {}
# Post.new.encode_with(coder)
# coder # => {"attributes" => {"id" => nil, ... }}
def encode_with(coder)
self.class.yaml_encoder.encode(@attributes, coder)
coder["new_record"] = new_record?
coder["active_record_yaml_version"] = 2
end
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
#
# Note that new records are different from any other record by definition, unless the
# other record is the receiver itself. Besides, if you fetch existing records with
# +select+ and leave the ID out, you're on your own, this predicate will return false.
#
# Note also that destroying a record preserves its ID in the model instance, so deleted
# models are still comparable.
def ==(comparison_object)
super ||
comparison_object.instance_of?(self.class) &&
!id.nil? &&
comparison_object.id == id
end
alias :eql? :==
# Delegates to id in order to allow two records of the same type and id to work with something like:
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
def hash
if id
self.class.hash ^ id.hash
else
super
end
end
# Clone and freeze the attributes hash such that associations are still
# accessible, even on destroyed records, but cloned models will not be
# frozen.
def freeze
@attributes = @attributes.clone.freeze
self
end
# Returns +true+ if the attributes hash has been frozen.
def frozen?
@attributes.frozen?
end
# Allows sort on objects
def <=>(other_object)
if other_object.is_a?(self.class)
to_key <=> other_object.to_key
else
super
end
end
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
# attributes will be marked as read only since they cannot be saved.
def readonly?
@readonly
end
# Marks this record as read only.
def readonly!
@readonly = true
end
def connection_handler
self.class.connection_handler
end
# Returns the contents of the record as a nicely formatted string.
def inspect
# We check defined?(@attributes) not to issue warnings if the object is
# allocated but not initialized.
inspection = if defined?(@attributes) && @attributes
self.class.attribute_names.collect do |name|
if has_attribute?(name)
if filter_attribute?(name)
"#{name}: #{ActiveRecord::Core::FILTERED}"
else
"#{name}: #{attribute_for_inspect(name)}"
end
end
end.compact.join(", ")
else
"not initialized"
end
"#<#{self.class} #{inspection}>"
end
# Takes a PP and prettily prints this record to it, allowing you to get a nice result from <tt>pp record</tt>
# when pp is required.
def pretty_print(pp)
return super if custom_inspect_method_defined?
pp.object_address_group(self) do
if defined?(@attributes) && @attributes
column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? }
pp.seplist(column_names, proc { pp.text "," }) do |column_name|
pp.breakable " "
pp.group(1) do
pp.text column_name
pp.text ":"
pp.breakable
if filter_attribute?(column_name)
pp.text ActiveRecord::Core::FILTERED
else
pp.pp read_attribute(column_name)
end
end
end
else
pp.breakable " "
pp.text "not initialized"
end
end
end
# Returns a hash of the given methods with their names as keys and returned values as values.
def slice(*methods)
Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access
end
private
# +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of
# the array, and then rescues from the possible +NoMethodError+. If those elements are
# +ActiveRecord::Base+'s, then this triggers the various +method_missing+'s that we have,
# which significantly impacts upon performance.
#
# So we can avoid the +method_missing+ hit by explicitly defining +#to_ary+ as +nil+ here.
#
# See also https://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
def to_ary
nil
end
def init_internals
@readonly = false
@destroyed = false
@marked_for_destruction = false
@destroyed_by_association = nil
@new_record = true
@_start_transaction_state = {}
@transaction_state = nil
end
def initialize_internals_callback
end
def thaw
if frozen?
@attributes = @attributes.dup
end
end
def custom_inspect_method_defined?
self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner
end
def filter_attribute?(attribute_name)
self.class.filter_attributes.include?(attribute_name) && !read_attribute(attribute_name).nil?
end
end
end
| baerjam/rails | activerecord/lib/active_record/core.rb | Ruby | mit | 20,695 |
ReactDOM.render(React.createElement(
'div',
null,
React.createElement(Content, null)
), document.getElementById('content')); | azat-co/react-quickly | spare-parts/ch05-es5/logger/js/script.js | JavaScript | mit | 130 |
// Copyright 2019 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <boost/mp11/version.hpp>
#include <boost/version.hpp>
#include <boost/core/lightweight_test.hpp>
int main()
{
BOOST_TEST_EQ( BOOST_MP11_VERSION, BOOST_VERSION );
return boost::report_errors();
}
| davehorton/drachtio-server | deps/boost_1_77_0/libs/mp11/test/version.cpp | C++ | mit | 405 |
export * from './components/ajax-bar/index.js'
export * from './components/avatar/index.js'
export * from './components/badge/index.js'
export * from './components/banner/index.js'
export * from './components/bar/index.js'
export * from './components/breadcrumbs/index.js'
export * from './components/btn/index.js'
export * from './components/btn-dropdown/index.js'
export * from './components/btn-group/index.js'
export * from './components/btn-toggle/index.js'
export * from './components/card/index.js'
export * from './components/carousel/index.js'
export * from './components/chat/index.js'
export * from './components/checkbox/index.js'
export * from './components/chip/index.js'
export * from './components/circular-progress/index.js'
export * from './components/color/index.js'
export * from './components/date/index.js'
export * from './components/dialog/index.js'
export * from './components/drawer/index.js'
export * from './components/editor/index.js'
export * from './components/expansion-item/index.js'
export * from './components/fab/index.js'
export * from './components/field/index.js'
export * from './components/file/index.js'
export * from './components/footer/index.js'
export * from './components/form/index.js'
export * from './components/header/index.js'
export * from './components/icon/index.js'
export * from './components/img/index.js'
export * from './components/infinite-scroll/index.js'
export * from './components/inner-loading/index.js'
export * from './components/input/index.js'
export * from './components/intersection/index.js'
export * from './components/item/index.js'
export * from './components/knob/index.js'
export * from './components/layout/index.js'
export * from './components/markup-table/index.js'
export * from './components/menu/index.js'
export * from './components/no-ssr/index.js'
export * from './components/option-group/index.js'
export * from './components/page/index.js'
export * from './components/page-scroller/index.js'
export * from './components/page-sticky/index.js'
export * from './components/pagination/index.js'
export * from './components/parallax/index.js'
export * from './components/popup-edit/index.js'
export * from './components/popup-proxy/index.js'
export * from './components/linear-progress/index.js'
export * from './components/pull-to-refresh/index.js'
export * from './components/radio/index.js'
export * from './components/range/index.js'
export * from './components/rating/index.js'
export * from './components/resize-observer/index.js'
export * from './components/responsive/index.js'
export * from './components/scroll-area/index.js'
export * from './components/scroll-observer/index.js'
export * from './components/select/index.js'
export * from './components/separator/index.js'
export * from './components/skeleton/index.js'
export * from './components/slide-item/index.js'
export * from './components/slide-transition/index.js'
export * from './components/slider/index.js'
export * from './components/space/index.js'
export * from './components/spinner/index.js'
export * from './components/splitter/index.js'
export * from './components/stepper/index.js'
export * from './components/tab-panels/index.js'
export * from './components/table/index.js'
export * from './components/tabs/index.js'
export * from './components/time/index.js'
export * from './components/timeline/index.js'
export * from './components/toggle/index.js'
export * from './components/toolbar/index.js'
export * from './components/tooltip/index.js'
export * from './components/tree/index.js'
export * from './components/uploader/index.js'
export * from './components/video/index.js'
export * from './components/virtual-scroll/index.js'
| rstoenescu/quasar-framework | ui/src/components.js | JavaScript | mit | 3,696 |
# -*- coding: utf-8 -*-
"""IPython Test Suite Runner.
This module provides a main entry point to a user script to test IPython
itself from the command line. There are two ways of running this script:
1. With the syntax `iptest all`. This runs our entire test suite by
calling this script (with different arguments) recursively. This
causes modules and package to be tested in different processes, using nose
or trial where appropriate.
2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
the script simply calls nose, but with special command line flags and
plugins loaded.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
import glob
from io import BytesIO
import os
import os.path as path
import sys
from threading import Thread, Lock, Event
import warnings
import nose.plugins.builtin
from nose.plugins.xunit import Xunit
from nose import SkipTest
from nose.core import TestProgram
from nose.plugins import Plugin
from nose.util import safe_str
from IPython.utils.process import is_cmd_found
from IPython.utils.py3compat import bytes_to_str
from IPython.utils.importstring import import_item
from IPython.testing.plugin.ipdoctest import IPythonDoctest
from IPython.external.decorators import KnownFailure, knownfailureif
pjoin = path.join
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Warnings control
#-----------------------------------------------------------------------------
# Twisted generates annoying warnings with Python 2.6, as will do other code
# that imports 'sets' as of today
warnings.filterwarnings('ignore', 'the sets module is deprecated',
DeprecationWarning )
# This one also comes from Twisted
warnings.filterwarnings('ignore', 'the sha module is deprecated',
DeprecationWarning)
# Wx on Fedora11 spits these out
warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
UserWarning)
# ------------------------------------------------------------------------------
# Monkeypatch Xunit to count known failures as skipped.
# ------------------------------------------------------------------------------
def monkeypatch_xunit():
try:
knownfailureif(True)(lambda: None)()
except Exception as e:
KnownFailureTest = type(e)
def addError(self, test, err, capt=None):
if issubclass(err[0], KnownFailureTest):
err = (SkipTest,) + err[1:]
return self.orig_addError(test, err, capt)
Xunit.orig_addError = Xunit.addError
Xunit.addError = addError
#-----------------------------------------------------------------------------
# Check which dependencies are installed and greater than minimum version.
#-----------------------------------------------------------------------------
def extract_version(mod):
return mod.__version__
def test_for(item, min_version=None, callback=extract_version):
"""Test to see if item is importable, and optionally check against a minimum
version.
If min_version is given, the default behavior is to check against the
`__version__` attribute of the item, but specifying `callback` allows you to
extract the value you are interested in. e.g::
In [1]: import sys
In [2]: from IPython.testing.iptest import test_for
In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
Out[3]: True
"""
try:
check = import_item(item)
except (ImportError, RuntimeError):
# GTK reports Runtime error if it can't be initialized even if it's
# importable.
return False
else:
if min_version:
if callback:
# extra processing step to get version to compare
check = callback(check)
return check >= min_version
else:
return True
# Global dict where we can store information on what we have and what we don't
# have available at test run time
have = {}
have['curses'] = test_for('_curses')
have['matplotlib'] = test_for('matplotlib')
have['numpy'] = test_for('numpy')
have['pexpect'] = test_for('IPython.external.pexpect')
have['pymongo'] = test_for('pymongo')
have['pygments'] = test_for('pygments')
have['qt'] = test_for('IPython.external.qt')
have['sqlite3'] = test_for('sqlite3')
have['tornado'] = test_for('tornado.version_info', (4,0), callback=None)
have['jinja2'] = test_for('jinja2')
have['mistune'] = test_for('mistune')
have['requests'] = test_for('requests')
have['sphinx'] = test_for('sphinx')
have['jsonschema'] = test_for('jsonschema')
have['terminado'] = test_for('terminado')
have['casperjs'] = is_cmd_found('casperjs')
have['phantomjs'] = is_cmd_found('phantomjs')
have['slimerjs'] = is_cmd_found('slimerjs')
min_zmq = (13,)
have['zmq'] = test_for('zmq.pyzmq_version_info', min_zmq, callback=lambda x: x())
#-----------------------------------------------------------------------------
# Test suite definitions
#-----------------------------------------------------------------------------
test_group_names = ['parallel', 'kernel', 'kernel.inprocess', 'config', 'core',
'extensions', 'lib', 'terminal', 'testing', 'utils',
'nbformat', 'qt', 'html', 'nbconvert'
]
class TestSection(object):
def __init__(self, name, includes):
self.name = name
self.includes = includes
self.excludes = []
self.dependencies = []
self.enabled = True
def exclude(self, module):
if not module.startswith('IPython'):
module = self.includes[0] + "." + module
self.excludes.append(module.replace('.', os.sep))
def requires(self, *packages):
self.dependencies.extend(packages)
@property
def will_run(self):
return self.enabled and all(have[p] for p in self.dependencies)
# Name -> (include, exclude, dependencies_met)
test_sections = {n:TestSection(n, ['IPython.%s' % n]) for n in test_group_names}
# Exclusions and dependencies
# ---------------------------
# core:
sec = test_sections['core']
if not have['sqlite3']:
sec.exclude('tests.test_history')
sec.exclude('history')
if not have['matplotlib']:
sec.exclude('pylabtools'),
sec.exclude('tests.test_pylabtools')
# lib:
sec = test_sections['lib']
if not have['zmq']:
sec.exclude('kernel')
# We do this unconditionally, so that the test suite doesn't import
# gtk, changing the default encoding and masking some unicode bugs.
sec.exclude('inputhookgtk')
# We also do this unconditionally, because wx can interfere with Unix signals.
# There are currently no tests for it anyway.
sec.exclude('inputhookwx')
# Testing inputhook will need a lot of thought, to figure out
# how to have tests that don't lock up with the gui event
# loops in the picture
sec.exclude('inputhook')
# testing:
sec = test_sections['testing']
# These have to be skipped on win32 because they use echo, rm, cd, etc.
# See ticket https://github.com/ipython/ipython/issues/87
if sys.platform == 'win32':
sec.exclude('plugin.test_exampleip')
sec.exclude('plugin.dtexample')
# terminal:
if (not have['pexpect']) or (not have['zmq']):
test_sections['terminal'].exclude('console')
# parallel
sec = test_sections['parallel']
sec.requires('zmq')
if not have['pymongo']:
sec.exclude('controller.mongodb')
sec.exclude('tests.test_mongodb')
# kernel:
sec = test_sections['kernel']
sec.requires('zmq')
# The in-process kernel tests are done in a separate section
sec.exclude('inprocess')
# importing gtk sets the default encoding, which we want to avoid
sec.exclude('zmq.gui.gtkembed')
sec.exclude('zmq.gui.gtk3embed')
if not have['matplotlib']:
sec.exclude('zmq.pylab')
# kernel.inprocess:
test_sections['kernel.inprocess'].requires('zmq')
# extensions:
sec = test_sections['extensions']
# This is deprecated in favour of rpy2
sec.exclude('rmagic')
# autoreload does some strange stuff, so move it to its own test section
sec.exclude('autoreload')
sec.exclude('tests.test_autoreload')
test_sections['autoreload'] = TestSection('autoreload',
['IPython.extensions.autoreload', 'IPython.extensions.tests.test_autoreload'])
test_group_names.append('autoreload')
# qt:
test_sections['qt'].requires('zmq', 'qt', 'pygments')
# html:
sec = test_sections['html']
sec.requires('zmq', 'tornado', 'requests', 'sqlite3', 'jsonschema')
# The notebook 'static' directory contains JS, css and other
# files for web serving. Occasionally projects may put a .py
# file in there (MathJax ships a conf.py), so we might as
# well play it safe and skip the whole thing.
sec.exclude('static')
sec.exclude('tasks')
if not have['jinja2']:
sec.exclude('notebookapp')
if not have['pygments'] or not have['jinja2']:
sec.exclude('nbconvert')
if not have['terminado']:
sec.exclude('terminal')
# config:
# Config files aren't really importable stand-alone
test_sections['config'].exclude('profile')
# nbconvert:
sec = test_sections['nbconvert']
sec.requires('pygments', 'jinja2', 'jsonschema', 'mistune')
# Exclude nbconvert directories containing config files used to test.
# Executing the config files with iptest would cause an exception.
sec.exclude('tests.files')
sec.exclude('exporters.tests.files')
if not have['tornado']:
sec.exclude('nbconvert.post_processors.serve')
sec.exclude('nbconvert.post_processors.tests.test_serve')
# nbformat:
test_sections['nbformat'].requires('jsonschema')
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
def check_exclusions_exist():
from IPython.utils.path import get_ipython_package_dir
from IPython.utils.warn import warn
parent = os.path.dirname(get_ipython_package_dir())
for sec in test_sections:
for pattern in sec.exclusions:
fullpath = pjoin(parent, pattern)
if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
warn("Excluding nonexistent file: %r" % pattern)
class ExclusionPlugin(Plugin):
"""A nose plugin to effect our exclusions of files and directories.
"""
name = 'exclusions'
score = 3000 # Should come before any other plugins
def __init__(self, exclude_patterns=None):
"""
Parameters
----------
exclude_patterns : sequence of strings, optional
Filenames containing these patterns (as raw strings, not as regular
expressions) are excluded from the tests.
"""
self.exclude_patterns = exclude_patterns or []
super(ExclusionPlugin, self).__init__()
def options(self, parser, env=os.environ):
Plugin.options(self, parser, env)
def configure(self, options, config):
Plugin.configure(self, options, config)
# Override nose trying to disable plugin.
self.enabled = True
def wantFile(self, filename):
"""Return whether the given filename should be scanned for tests.
"""
if any(pat in filename for pat in self.exclude_patterns):
return False
return None
def wantDirectory(self, directory):
"""Return whether the given directory should be scanned for tests.
"""
if any(pat in directory for pat in self.exclude_patterns):
return False
return None
class StreamCapturer(Thread):
daemon = True # Don't hang if main thread crashes
started = False
def __init__(self, echo=False):
super(StreamCapturer, self).__init__()
self.echo = echo
self.streams = []
self.buffer = BytesIO()
self.readfd, self.writefd = os.pipe()
self.buffer_lock = Lock()
self.stop = Event()
def run(self):
self.started = True
while not self.stop.is_set():
chunk = os.read(self.readfd, 1024)
with self.buffer_lock:
self.buffer.write(chunk)
if self.echo:
sys.stdout.write(bytes_to_str(chunk))
os.close(self.readfd)
os.close(self.writefd)
def reset_buffer(self):
with self.buffer_lock:
self.buffer.truncate(0)
self.buffer.seek(0)
def get_buffer(self):
with self.buffer_lock:
return self.buffer.getvalue()
def ensure_started(self):
if not self.started:
self.start()
def halt(self):
"""Safely stop the thread."""
if not self.started:
return
self.stop.set()
os.write(self.writefd, b'\0') # Ensure we're not locked in a read()
self.join()
class SubprocessStreamCapturePlugin(Plugin):
name='subprocstreams'
def __init__(self):
Plugin.__init__(self)
self.stream_capturer = StreamCapturer()
self.destination = os.environ.get('IPTEST_SUBPROC_STREAMS', 'capture')
# This is ugly, but distant parts of the test machinery need to be able
# to redirect streams, so we make the object globally accessible.
nose.iptest_stdstreams_fileno = self.get_write_fileno
def get_write_fileno(self):
if self.destination == 'capture':
self.stream_capturer.ensure_started()
return self.stream_capturer.writefd
elif self.destination == 'discard':
return os.open(os.devnull, os.O_WRONLY)
else:
return sys.__stdout__.fileno()
def configure(self, options, config):
Plugin.configure(self, options, config)
# Override nose trying to disable plugin.
if self.destination == 'capture':
self.enabled = True
def startTest(self, test):
# Reset log capture
self.stream_capturer.reset_buffer()
def formatFailure(self, test, err):
# Show output
ec, ev, tb = err
captured = self.stream_capturer.get_buffer().decode('utf-8', 'replace')
if captured.strip():
ev = safe_str(ev)
out = [ev, '>> begin captured subprocess output <<',
captured,
'>> end captured subprocess output <<']
return ec, '\n'.join(out), tb
return err
formatError = formatFailure
def finalize(self, result):
self.stream_capturer.halt()
def run_iptest():
"""Run the IPython test suite using nose.
This function is called when this script is **not** called with the form
`iptest all`. It simply calls nose with appropriate command line flags
and accepts all of the standard nose arguments.
"""
# Apply our monkeypatch to Xunit
if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
monkeypatch_xunit()
warnings.filterwarnings('ignore',
'This will be removed soon. Use IPython.testing.util instead')
arg1 = sys.argv[1]
if arg1 in test_sections:
section = test_sections[arg1]
sys.argv[1:2] = section.includes
elif arg1.startswith('IPython.') and arg1[8:] in test_sections:
section = test_sections[arg1[8:]]
sys.argv[1:2] = section.includes
else:
section = TestSection(arg1, includes=[arg1])
argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
'--with-ipdoctest',
'--ipdoctest-tests','--ipdoctest-extension=txt',
# We add --exe because of setuptools' imbecility (it
# blindly does chmod +x on ALL files). Nose does the
# right thing and it tries to avoid executables,
# setuptools unfortunately forces our hand here. This
# has been discussed on the distutils list and the
# setuptools devs refuse to fix this problem!
'--exe',
]
if '-a' not in argv and '-A' not in argv:
argv = argv + ['-a', '!crash']
if nose.__version__ >= '0.11':
# I don't fully understand why we need this one, but depending on what
# directory the test suite is run from, if we don't give it, 0 tests
# get run. Specifically, if the test suite is run from the source dir
# with an argument (like 'iptest.py IPython.core', 0 tests are run,
# even if the same call done in this directory works fine). It appears
# that if the requested package is in the current dir, nose bails early
# by default. Since it's otherwise harmless, leave it in by default
# for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
argv.append('--traverse-namespace')
# use our plugin for doctesting. It will remove the standard doctest plugin
# if it finds it enabled
plugins = [ExclusionPlugin(section.excludes), IPythonDoctest(), KnownFailure(),
SubprocessStreamCapturePlugin() ]
# Use working directory set by parent process (see iptestcontroller)
if 'IPTEST_WORKING_DIR' in os.environ:
os.chdir(os.environ['IPTEST_WORKING_DIR'])
# We need a global ipython running in this process, but the special
# in-process group spawns its own IPython kernels, so for *that* group we
# must avoid also opening the global one (otherwise there's a conflict of
# singletons). Ultimately the solution to this problem is to refactor our
# assumptions about what needs to be a singleton and what doesn't (app
# objects should, individual shells shouldn't). But for now, this
# workaround allows the test suite for the inprocess module to complete.
if 'kernel.inprocess' not in section.name:
from IPython.testing import globalipapp
globalipapp.start_ipython()
# Now nose can run
TestProgram(argv=argv, addplugins=plugins)
if __name__ == '__main__':
run_iptest()
| wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/IPython/testing/iptest.py | Python | mit | 18,302 |
/* */
define(['exports', 'core-js', 'aurelia-pal', 'aurelia-history'], function (exports, _coreJs, _aureliaPal, _aureliaHistory) {
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports.configure = configure;
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var LinkHandler = (function () {
function LinkHandler() {
_classCallCheck(this, LinkHandler);
}
LinkHandler.prototype.activate = function activate(history) {};
LinkHandler.prototype.deactivate = function deactivate() {};
return LinkHandler;
})();
exports.LinkHandler = LinkHandler;
var DefaultLinkHandler = (function (_LinkHandler) {
_inherits(DefaultLinkHandler, _LinkHandler);
function DefaultLinkHandler() {
var _this = this;
_classCallCheck(this, DefaultLinkHandler);
_LinkHandler.call(this);
this.handler = function (e) {
var _DefaultLinkHandler$getEventInfo = DefaultLinkHandler.getEventInfo(e);
var shouldHandleEvent = _DefaultLinkHandler$getEventInfo.shouldHandleEvent;
var href = _DefaultLinkHandler$getEventInfo.href;
if (shouldHandleEvent) {
e.preventDefault();
_this.history.navigate(href);
}
};
}
DefaultLinkHandler.prototype.activate = function activate(history) {
if (history._hasPushState) {
this.history = history;
_aureliaPal.DOM.addEventListener('click', this.handler, true);
}
};
DefaultLinkHandler.prototype.deactivate = function deactivate() {
_aureliaPal.DOM.removeEventListener('click', this.handler);
};
DefaultLinkHandler.getEventInfo = function getEventInfo(event) {
var info = {
shouldHandleEvent: false,
href: null,
anchor: null
};
var target = DefaultLinkHandler.findClosestAnchor(event.target);
if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) {
return info;
}
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return info;
}
var href = target.getAttribute('href');
info.anchor = target;
info.href = href;
var hasModifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
var isRelative = href && !(href.charAt(0) === '#' || /^[a-z]+:/i.test(href));
info.shouldHandleEvent = !hasModifierKey && isRelative;
return info;
};
DefaultLinkHandler.findClosestAnchor = function findClosestAnchor(el) {
while (el) {
if (el.tagName === 'A') {
return el;
}
el = el.parentNode;
}
};
DefaultLinkHandler.targetIsThisWindow = function targetIsThisWindow(target) {
var targetWindow = target.getAttribute('target');
var win = _aureliaPal.PLATFORM.global;
return !targetWindow || targetWindow === win.name || targetWindow === '_self' || targetWindow === 'top' && win === win.top;
};
return DefaultLinkHandler;
})(LinkHandler);
exports.DefaultLinkHandler = DefaultLinkHandler;
function configure(config) {
config.singleton(_aureliaHistory.History, BrowserHistory);
config.transient(LinkHandler, DefaultLinkHandler);
}
var BrowserHistory = (function (_History) {
_inherits(BrowserHistory, _History);
_createClass(BrowserHistory, null, [{
key: 'inject',
value: [LinkHandler],
enumerable: true
}]);
function BrowserHistory(linkHandler) {
_classCallCheck(this, BrowserHistory);
_History.call(this);
this._isActive = false;
this._checkUrlCallback = this._checkUrl.bind(this);
this.location = _aureliaPal.PLATFORM.location;
this.history = _aureliaPal.PLATFORM.history;
this.linkHandler = linkHandler;
}
BrowserHistory.prototype.activate = function activate(options) {
if (this._isActive) {
throw new Error('History has already been activated.');
}
var wantsPushState = !!options.pushState;
this._isActive = true;
this.options = Object.assign({}, { root: '/' }, this.options, options);
this.root = ('/' + this.options.root + '/').replace(rootStripper, '/');
this._wantsHashChange = this.options.hashChange !== false;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var eventName = undefined;
if (this._hasPushState) {
eventName = 'popstate';
} else if (this._wantsHashChange) {
eventName = 'hashchange';
}
_aureliaPal.PLATFORM.addEventListener(eventName, this._checkUrlCallback);
if (this._wantsHashChange && wantsPushState) {
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
if (!this._hasPushState && !atRoot) {
this.fragment = this._getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
return true;
} else if (this._hasPushState && atRoot && loc.hash) {
this.fragment = this._getHash().replace(routeStripper, '');
this.history.replaceState({}, _aureliaPal.DOM.title, this.root + this.fragment + loc.search);
}
}
if (!this.fragment) {
this.fragment = this._getFragment();
}
this.linkHandler.activate(this);
if (!this.options.silent) {
return this._loadUrl();
}
};
BrowserHistory.prototype.deactivate = function deactivate() {
_aureliaPal.PLATFORM.removeEventListener('popstate', this._checkUrlCallback);
_aureliaPal.PLATFORM.removeEventListener('hashchange', this._checkUrlCallback);
this._isActive = false;
this.linkHandler.deactivate();
};
BrowserHistory.prototype.navigate = function navigate(fragment) {
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref$trigger = _ref.trigger;
var trigger = _ref$trigger === undefined ? true : _ref$trigger;
var _ref$replace = _ref.replace;
var replace = _ref$replace === undefined ? false : _ref$replace;
if (fragment && absoluteUrl.test(fragment)) {
this.location.href = fragment;
return true;
}
if (!this._isActive) {
return false;
}
fragment = this._getFragment(fragment || '');
if (this.fragment === fragment && !replace) {
return false;
}
this.fragment = fragment;
var url = this.root + fragment;
if (fragment === '' && url !== '/') {
url = url.slice(0, -1);
}
if (this._hasPushState) {
url = url.replace('//', '/');
this.history[replace ? 'replaceState' : 'pushState']({}, _aureliaPal.DOM.title, url);
} else if (this._wantsHashChange) {
updateHash(this.location, fragment, replace);
} else {
return this.location.assign(url);
}
if (trigger) {
return this._loadUrl(fragment);
}
};
BrowserHistory.prototype.navigateBack = function navigateBack() {
this.history.back();
};
BrowserHistory.prototype.setTitle = function setTitle(title) {
_aureliaPal.DOM.title = title;
};
BrowserHistory.prototype._getHash = function _getHash() {
return this.location.hash.substr(1);
};
BrowserHistory.prototype._getFragment = function _getFragment(fragment, forcePushState) {
var root = undefined;
if (!fragment) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname + this.location.search;
root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) {
fragment = fragment.substr(root.length);
}
} else {
fragment = this._getHash();
}
}
return '/' + fragment.replace(routeStripper, '');
};
BrowserHistory.prototype._checkUrl = function _checkUrl() {
var current = this._getFragment();
if (current !== this.fragment) {
this._loadUrl();
}
};
BrowserHistory.prototype._loadUrl = function _loadUrl(fragmentOverride) {
var fragment = this.fragment = this._getFragment(fragmentOverride);
return this.options.routeHandler ? this.options.routeHandler(fragment) : false;
};
return BrowserHistory;
})(_aureliaHistory.History);
exports.BrowserHistory = BrowserHistory;
var routeStripper = /^#?\/*|\s+$/g;
var rootStripper = /^\/+|\/+$/g;
var trailingSlash = /\/$/;
var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;
function updateHash(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
location.hash = '#' + fragment;
}
}
}); | mbroadst/aurelia-plunker | jspm_packages/npm/aurelia-history-browser@1.0.0-beta.1/aurelia-history-browser.js | JavaScript | mit | 10,044 |
# CallableSignature
# ===
# A CallableSignature describes how something callable expects to be called.
# Different implementation of this class are used for different types of callables.
#
# @api public
#
class Puppet::Pops::Evaluator::CallableSignature
# Returns the names of the parameters as an array of strings. This does not include the name
# of an optional block parameter.
#
# All implementations are not required to supply names for parameters. They may be used if present,
# to provide user feedback in errors etc. but they are not authoritative about the number of
# required arguments, optional arguments, etc.
#
# A derived class must implement this method.
#
# @return [Array<String>] - an array of names (that may be empty if names are unavailable)
#
# @api public
#
def parameter_names
raise NotImplementedError.new
end
# Returns a PCallableType with the type information, required and optional count, and type information about
# an optional block.
#
# A derived class must implement this method.
#
# @return [Puppet::Pops::Types::PCallableType]
# @api public
#
def type
raise NotImplementedError.new
end
# Returns the expected type for an optional block. The type may be nil, which means that the callable does
# not accept a block. If a type is returned it is one of Callable, Optional[Callable], Variant[Callable,...],
# or Optional[Variant[Callable, ...]]. The Variant type is used when multiple signatures are acceptable.
# The Optional type is used when the block is optional.
#
# @return [Puppet::Pops::Types::PAbstractType, nil] the expected type of a block given as the last parameter in a call.
#
# @api public
#
def block_type
type.block_type
end
# Returns the name of the block parameter if the callable accepts a block.
# @return [String] the name of the block parameter
# A derived class must implement this method.
# @api public
#
def block_name
raise NotImplementedError.new
end
# Returns a range indicating the optionality of a block. One of [0,0] (does not accept block), [0,1] (optional
# block), and [1,1] (block required)
#
# @return [Array(Integer, Integer)] the range of the block parameter
#
def block_range
type.block_range
end
# Returns the range of required/optional argument values as an array of [min, max], where an infinite
# end is given as INFINITY. To test against infinity, use the infinity? method.
#
# @return [Array[Integer, Numeric]] - an Array with [min, max]
#
# @api public
#
def args_range
type.size_range
end
# Returns true if the last parameter captures the rest of the arguments, with a possible cap, as indicated
# by the `args_range` method.
# A derived class must implement this method.
#
# @return [Boolean] true if last parameter captures the rest of the given arguments (up to a possible cap)
# @api public
#
def last_captures_rest?
raise NotImplementedError.new
end
# Returns true if the given x is infinity
# @return [Boolean] true, if given value represents infinity
#
# @api public
#
def infinity?(x)
x == Puppet::Pops::Types::INFINITY
end
end
| jorgemancheno/boxen | vendor/bundle/ruby/2.0.0/gems/puppet-3.6.1/lib/puppet/pops/evaluator/callable_signature.rb | Ruby | mit | 3,208 |
/**
* Copyright (c) 2015-present, Alibaba Group Holding Limited.
* All rights reserved.
*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @providesModule ReactNavigatorNavigationBarStylesAndroid
*/
'use strict';
import buildStyleInterpolator from './polyfills/buildStyleInterpolator';
import merge from './polyfills/merge';
// Android Material Design
var NAV_BAR_HEIGHT = 56;
var TITLE_LEFT = 72;
var BUTTON_SIZE = 24;
var TOUCH_TARGT_SIZE = 48;
var BUTTON_HORIZONTAL_MARGIN = 16;
var BUTTON_EFFECTIVE_MARGIN = BUTTON_HORIZONTAL_MARGIN - (TOUCH_TARGT_SIZE - BUTTON_SIZE) / 2;
var NAV_ELEMENT_HEIGHT = NAV_BAR_HEIGHT;
var BASE_STYLES = {
Title: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
alignItems: 'flex-start',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
marginLeft: TITLE_LEFT,
},
LeftButton: {
position: 'absolute',
top: 0,
left: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
RightButton: {
position: 'absolute',
top: 0,
right: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
alignItems: 'flex-end',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
};
// There are 3 stages: left, center, right. All previous navigation
// items are in the left stage. The current navigation item is in the
// center stage. All upcoming navigation items are in the right stage.
// Another way to think of the stages is in terms of transitions. When
// we move forward in the navigation stack, we perform a
// right-to-center transition on the new navigation item and a
// center-to-left transition on the current navigation item.
var Stages = {
Left: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
Center: {
Title: merge(BASE_STYLES.Title, { opacity: 1 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 1 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 1 }),
},
Right: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
};
var opacityRatio = 100;
function buildSceneInterpolators(startStyles, endStyles) {
return {
Title: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.Title.opacity,
to: endStyles.Title.opacity,
min: 0,
max: 1,
},
left: {
type: 'linear',
from: startStyles.Title.left,
to: endStyles.Title.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
LeftButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.LeftButton.opacity,
to: endStyles.LeftButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.LeftButton.left,
to: endStyles.LeftButton.left,
min: 0,
max: 1,
},
}),
RightButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.RightButton.opacity,
to: endStyles.RightButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.RightButton.left,
to: endStyles.RightButton.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
};
}
var Interpolators = {
// Animating *into* the center stage from the right
RightToCenter: buildSceneInterpolators(Stages.Right, Stages.Center),
// Animating out of the center stage, to the left
CenterToLeft: buildSceneInterpolators(Stages.Center, Stages.Left),
// Both stages (animating *past* the center stage)
RightToLeft: buildSceneInterpolators(Stages.Right, Stages.Left),
};
module.exports = {
General: {
NavBarHeight: NAV_BAR_HEIGHT,
StatusBarHeight: 0,
TotalNavHeight: NAV_BAR_HEIGHT,
},
Interpolators,
Stages,
};
| typesettin/NativeCMS | node_modules/react-web/Libraries/Navigator/NavigatorNavigationBarStylesAndroid.js | JavaScript | mit | 4,250 |
package net.anotheria.moskito.webui.threads.api;
import net.anotheria.anoplass.api.APIFactory;
import net.anotheria.anoplass.api.APIFinder;
import net.anotheria.anoprise.metafactory.ServiceFactory;
/**
* TODO comment this class
*
* @author lrosenberg
* @since 14.02.13 11:46
*/
public class ThreadAPIFactory implements APIFactory<ThreadAPI>, ServiceFactory<ThreadAPI> {
@Override
public ThreadAPI createAPI() {
return new ThreadAPIImpl();
}
@Override
public ThreadAPI create() {
APIFinder.addAPIFactory(ThreadAPI.class, this);
return APIFinder.findAPI(ThreadAPI.class);
}
}
| esmakula/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/threads/api/ThreadAPIFactory.java | Java | mit | 594 |
require "spec_helper"
require "hamster/sorted_set"
describe Hamster::SortedSet do
describe "#disjoint?" do
[
[[], [], true],
[["A"], [], true],
[[], ["A"], true],
[["A"], ["A"], false],
[%w[A B C], ["B"], false],
[["B"], %w[A B C], false],
[%w[A B C], %w[D E], true],
[%w[F G H I], %w[A B C], true],
[%w[A B C], %w[A B C], false],
[%w[A B C], %w[A B C D], false],
[%w[D E F G], %w[A B C], true],
].each do |a, b, expected|
context "for #{a.inspect} and #{b.inspect}" do
it "returns #{expected}" do
Hamster.sorted_set(*a).disjoint?(Hamster.sorted_set(*b)).should be(expected)
end
end
end
end
end | dzjuck/hamster | spec/lib/hamster/sorted_set/disjoint_spec.rb | Ruby | mit | 715 |
require 'spec_helper'
describe Locomotive::Liquid::Tags::Extends do
before(:each) do
@home = FactoryGirl.build(:page, :raw_template => 'Hello world')
@home.send :serialize_template
@home.instance_variable_set(:@template, nil)
@site = FactoryGirl.build(:site)
@site.stubs(:pages).returns([@home])
end
it 'works' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('parent', page).render.should == 'Hello world'
end
it 'looks for the index with the right locale' do
::Mongoid::Fields::I18n.with_locale 'fr' do
@home.raw_template = 'Bonjour le monde'
@home.send :serialize_template
end
@site.pages.expects(:where).with('fullpath.fr' => 'index').returns([@home])
::Mongoid::Fields::I18n.with_locale 'fr' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('index', page).render.should == 'Bonjour le monde'
end
end
context '#errors' do
it 'raises an error if the source page does not exist' do
lambda {
@site.pages.expects(:where).with('fullpath.en' => 'foo').returns([])
parse('foo')
}.should raise_error(Locomotive::Liquid::PageNotFound, "Page with fullpath 'foo' was not found")
end
it 'raises an error if the source page is not translated' do
lambda {
::Mongoid::Fields::I18n.with_locale 'fr' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('parent', page)
end
}.should raise_error(Locomotive::Liquid::PageNotTranslated, "Page with fullpath 'parent' was not translated")
end
end
def parse(source = 'index', page = nil)
page ||= @home
Liquid::Template.parse("{% extends #{source} %}", { :site => @site, :page => page })
end
end
| Vinagility/engine_old | spec/lib/locomotive/liquid/tags/extends_spec.rb | Ruby | mit | 1,826 |
(function () {
'use strict';
/** This directive is used to render out the current variant tabs and properties and exposes an API for other directives to consume */
function tabbedContentDirective($timeout, $filter, contentEditingHelper, contentTypeHelper) {
function link($scope, $element) {
var appRootNode = $element[0];
// Directive for cached property groups.
var propertyGroupNodesDictionary = {};
var scrollableNode = appRootNode.closest(".umb-scrollable");
$scope.activeTabAlias = null;
$scope.tabs = [];
$scope.$watchCollection('content.tabs', (newValue) => {
contentTypeHelper.defineParentAliasOnGroups(newValue);
contentTypeHelper.relocateDisorientedGroups(newValue);
// make a collection with only tabs and not all groups
$scope.tabs = $filter("filter")(newValue, (tab) => {
return tab.type === contentTypeHelper.TYPE_TAB;
});
if ($scope.tabs.length > 0) {
// if we have tabs and some groups that doesn't belong to a tab we need to render those on an "Other" tab.
contentEditingHelper.registerGenericTab(newValue);
$scope.setActiveTab($scope.tabs[0]);
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
// only trigger anchor scroll when there are no tabs
} else {
scrollableNode.addEventListener("scroll", onScroll);
scrollableNode.addEventListener("mousewheel", cancelScrollTween);
}
});
function onScroll(event) {
var viewFocusY = scrollableNode.scrollTop + scrollableNode.clientHeight * .5;
for(var i in $scope.content.tabs) {
var group = $scope.content.tabs[i];
var node = propertyGroupNodesDictionary[group.id];
if (!node) {
return;
}
if (viewFocusY >= node.offsetTop && viewFocusY <= node.offsetTop + node.clientHeight) {
setActiveAnchor(group);
return;
}
}
}
function setActiveAnchor(tab) {
if (tab.active !== true) {
var i = $scope.content.tabs.length;
while(i--) {
$scope.content.tabs[i].active = false;
}
tab.active = true;
}
}
function getActiveAnchor() {
var i = $scope.content.tabs.length;
while(i--) {
if ($scope.content.tabs[i].active === true)
return $scope.content.tabs[i];
}
return false;
}
function getScrollPositionFor(id) {
if (propertyGroupNodesDictionary[id]) {
return propertyGroupNodesDictionary[id].offsetTop - 20;// currently only relative to closest relatively positioned parent
}
return null;
}
function scrollTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
var viewportHeight = scrollableNode.clientHeight;
var from = scrollableNode.scrollTop;
var to = Math.min(y, scrollableNode.scrollHeight - viewportHeight);
var animeObject = {_y: from};
$scope.scrollTween = anime({
targets: animeObject,
_y: to,
easing: 'easeOutExpo',
duration: 200 + Math.min(Math.abs(to-from)/viewportHeight*100, 400),
update: () => {
scrollableNode.scrollTo(0, animeObject._y);
}
});
}
}
function jumpTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
cancelScrollTween();
scrollableNode.scrollTo(0, y);
}
}
function cancelScrollTween() {
if($scope.scrollTween) {
$scope.scrollTween.pause();
}
}
$scope.registerPropertyGroup = function(element, appAnchor) {
propertyGroupNodesDictionary[appAnchor] = element;
};
$scope.setActiveTab = function(tab) {
$scope.activeTabAlias = tab.alias;
$scope.tabs.forEach(tab => tab.active = false);
tab.active = true;
};
$scope.$on("editors.apps.appChanged", function($event, $args) {
// if app changed to this app, then we want to scroll to the current anchor
if($args.app.alias === "umbContent" && $scope.tabs.length === 0) {
var activeAnchor = getActiveAnchor();
$timeout(jumpTo.bind(null, [activeAnchor.id]));
}
});
$scope.$on("editors.apps.appAnchorChanged", function($event, $args) {
if($args.app.alias === "umbContent") {
setActiveAnchor($args.anchor);
scrollTo($args.anchor.id);
}
});
//ensure to unregister from all dom-events
$scope.$on('$destroy', function () {
cancelScrollTween();
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
});
}
function controller($scope) {
//expose the property/methods for other directives to use
this.content = $scope.content;
if($scope.contentNodeModel) {
$scope.defaultVariant = _.find($scope.contentNodeModel.variants, variant => {
// defaultVariant will never have segment. Wether it has a language or not depends on the setup.
return !variant.segment && ((variant.language && variant.language.isDefault) || (!variant.language));
});
}
$scope.unlockInvariantValue = function(property) {
property.unlockInvariantValue = !property.unlockInvariantValue;
};
$scope.$watch("tabbedContentForm.$dirty",
function (newValue, oldValue) {
if (newValue === true) {
$scope.content.isDirty = true;
}
}
);
$scope.propertyEditorDisabled = function (property) {
if (property.unlockInvariantValue) {
return false;
}
var contentLanguage = $scope.content.language;
var canEditCulture = !contentLanguage ||
// If the property culture equals the content culture it can be edited
property.culture === contentLanguage.culture ||
// A culture-invariant property can only be edited by the default language variant
(property.culture == null && contentLanguage.isDefault);
var canEditSegment = property.segment === $scope.content.segment;
return !canEditCulture || !canEditSegment;
}
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/content/umb-tabbed-content.html',
controller: controller,
link: link,
scope: {
content: "=", // in this context the content is the variant model.
contentNodeModel: "=?", //contentNodeModel is the content model for the node,
contentApp: "=?" // contentApp is the origin app model for this view
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbTabbedContent', tabbedContentDirective);
})();
| umbraco/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbtabbedcontent.directive.js | JavaScript | mit | 8,522 |
#include "time_alias_reflection.h"
#include <bond/core/bond.h>
#include <bond/stream/output_buffer.h>
using namespace examples::time;
int main()
{
Example obj, obj2;
using namespace boost::gregorian;
using namespace boost::posix_time;
// In the generated code we use boost::posix_time_ptime::ptime to represent
// the type alias 'time' (see makefile.inc for code gen flags).
obj.when = ptime(date(2016, 1, 29));
obj.bdays["bill"] = ptime(from_string("1955/10/28"));
bond::OutputBuffer output;
bond::CompactBinaryWriter<bond::OutputBuffer> writer(output);
// Serialize the object
Serialize(obj, writer);
bond::CompactBinaryReader<bond::InputBuffer> reader(output.GetBuffer());
// De-serialize the object
Deserialize(reader, obj2);
std::string followingSunday = to_simple_string(
first_day_of_the_week_after(Sunday).get_date(obj2.when.date()));
BOOST_ASSERT(obj == obj2);
return 0;
}
| upsoft/bond | examples/cpp/core/time_alias/time_alias.cpp | C++ | mit | 971 |
<?php
/**
*
*/
namespace Mvc5\Plugin\Gem;
interface Copy
extends Gem
{
/**
* @return object
*/
function config();
}
| devosc/mvc5 | src/Plugin/Gem/Copy.php | PHP | mit | 142 |
<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
Loader::block('page_list');
$previewMode = true;
$nh = Loader::helper('navigation');
$controller = new PageListBlockController($b);
$_REQUEST['num'] = ($_REQUEST['num'] > 0) ? $_REQUEST['num'] : 0;
$_REQUEST['cThis'] = ($_REQUEST['cParentID'] == $controller->cID) ? '1' : '0';
$_REQUEST['cParentID'] = ($_REQUEST['cParentID'] == 'OTHER') ? $_REQUEST['cParentIDValue'] : $_REQUEST['cParentID'];
$controller->num = $_REQUEST['num'];
$controller->cParentID = $_REQUEST['cParentID'];
$controller->cThis = $_REQUEST['cThis'];
$controller->orderBy = $_REQUEST['orderBy'];
$controller->ctID = $_REQUEST['ctID'];
$controller->rss = $_REQUEST['rss'];
$controller->displayFeaturedOnly = $_REQUEST['displayFeaturedOnly'];
$cArray = $controller->getPages();
//echo var_dump($cArray);
require(dirname(__FILE__) . '/../view.php');
exit; | markdev/markandkitty | concrete/blocks/date_nav/tools/preview_pane.php | PHP | mit | 898 |
# frozen_string_literal: true
class AvatarUploader < GitlabUploader
include UploaderHelper
include RecordsUploads::Concern
include ObjectStorage::Concern
prepend ObjectStorage::Extension::RecordsUploads
MIME_WHITELIST = %w[image/png image/jpeg image/gif image/bmp image/tiff image/vnd.microsoft.icon].freeze
def exists?
model.avatar.file && model.avatar.file.present?
end
def move_to_store
false
end
def move_to_cache
false
end
def absolute_path
self.class.absolute_path(upload)
end
def mounted_as
super || 'avatar'
end
def content_type_whitelist
MIME_WHITELIST
end
private
def dynamic_segment
File.join(model.class.underscore, mounted_as.to_s, model.id.to_s)
end
end
| mmkassem/gitlabhq | app/uploaders/avatar_uploader.rb | Ruby | mit | 746 |
<?php
namespace Bolt\Tests\Controller\Backend;
use Bolt\Storage\Entity;
use Bolt\Tests\Controller\ControllerUnitTest;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Class to test correct operation of src/Controller/Backend/Users.
*
* @author Ross Riley <riley.ross@gmail.com>
* @author Gawain Lynch <gawain.lynch@gmail.com>
**/
class UsersTest extends ControllerUnitTest
{
public function testAdmin()
{
$this->setRequest(Request::create('/bolt/users'));
$response = $this->controller()->admin();
$context = $response->getContext();
$this->assertNotNull($context['context']['users']);
$this->assertNotNull($context['context']['sessions']);
}
public function testEdit()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$this->setRequest(Request::create('/bolt/users/edit/1'));
// This one should redirect because of permission failure
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now we allow the permsission check to return true
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
$response = $this->controller()->edit($this->getRequest(), 1);
$context = $response->getContext();
$this->assertEquals('edit', $context['context']['kind']);
$this->assertInstanceOf(FormView::class, $context['context']['form']);
$this->assertEquals('Admin', $context['context']['displayname']);
// Test that an empty user gives a create form
$this->setRequest(Request::create('/bolt/users/edit'));
$response = $this->controller()->edit($this->getRequest(), null);
$context = $response->getContext();
$this->assertEquals('create', $context['context']['kind']);
}
public function testUserEditPost()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
// Update the display name via a POST request
$this->setRequest(Request::create(
'/bolt/useredit/1',
'POST',
[
'user_edit' => [
'username' => $user['username'],
'email' => $user['email'],
'displayname' => 'Admin Test',
'_token' => 'xyz',
],
]
));
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testFirst()
{
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
// Because we have users in the database this should exit at first attempt
$this->setRequest(Request::create('/bolt/userfirst'));
$response = $this->controller()->first($this->getRequest());
$this->assertEquals('/bolt', $response->getTargetUrl());
// Now we delete the users
$this->getService('db')->executeQuery('DELETE FROM bolt_users;');
$this->getService('users')->users = [];
$this->setRequest(Request::create('/bolt/userfirst'));
$response = $this->controller()->first($this->getRequest());
$context = $response->getContext();
$this->assertEquals('create', $context['context']['kind']);
// This block attempts to create the user
$request = Request::create(
'/bolt/userfirst',
'POST',
[
'user_new' => [
'username' => 'admin',
'email' => 'test@example.com',
'displayname' => 'Admin',
'password' => [
'first' => 'password',
'second' => 'password',
],
'_token' => 'xyz',
],
]
);
$this->setRequest($request);
$this->getService('request_stack')->push($request);
$response = $this->controller()->first($this->getRequest());
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt', $response->getTargetUrl());
}
public function testModifyBadCsrf()
{
// First test should exit/redirect with no anti CSRF token
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 1);
$info = $this->getFlashBag()->get('error');
$this->assertRegExp('/Something went wrong/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testModifyValidCsrf()
{
// Now we mock the CSRF token to validate
$this->removeCSRF();
$currentuser = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($currentuser));
// This request should fail because the user doesnt exist.
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 42);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/No such user/', $err[0]);
// This check will fail because we are operating on the current user
$this->setRequest(Request::create('/bolt/user/disable/1'));
$response = $this->controller()->modify('disable', 1);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/yourself/', $err[0]);
// We add a new user that isn't the current user and now perform operations.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
$editor = $this->getService('users')->getUser('editor');
// And retry the operation that will work now
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is disabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now try to enable the user
$this->setRequest(Request::create('/bolt/user/enable/2'));
$response = $this->controller()->modify('enable', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is enabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Try a non-existent action, make sure we get an error
$this->setRequest(Request::create('/bolt/user/enhance/2'));
$response = $this->controller()->modify('enhance', $editor['id']);
$info = $this->getFlashBag()->get('error');
$this->assertRegExp('/No such action/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now we run a delete action
$this->setRequest(Request::create('/bolt/user/delete/2'));
$response = $this->controller()->modify('delete', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is deleted/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Finally we mock the permsission check to return false and check
// we get a priileges error.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
$editor = $this->getService('users')->getUser('editor');
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(false));
$this->setService('permissions', $perms);
$this->setRequest(Request::create('/bolt/user/disable/' . $editor['id']));
$response = $this->controller()->modify('disable', $editor['id']);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/right privileges/', $err[0]);
}
public function testModifyFailures()
{
// We add a new user that isn't the current user and now perform operations.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
// Now we mock the CSRF token to validate
$this->removeCSRF();
$users = $this->getMockUsers(['setEnabled', 'deleteUser']);
$users->expects($this->any())
->method('setEnabled')
->will($this->returnValue(false));
$users->expects($this->any())
->method('deleteUser')
->will($this->returnValue(false));
$this->setService('users', $users);
// Setup the current user
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
// This mocks a failure and ensures the error is reported
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be disabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$this->setRequest(Request::create('/bolt/user/enable/2'));
$response = $this->controller()->modify('enable', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be enabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$this->setRequest(Request::create('/bolt/user/delete/2'));
$response = $this->controller()->modify('delete', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be deleted/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testProfile()
{
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$this->setRequest(Request::create('/bolt/profile'));
$response = $this->controller()->profile($this->getRequest());
$context = $response->getContext();
$this->assertEquals('@bolt/edituser/edituser.twig', $response->getTemplate());
$this->assertEquals('profile', $context['context']['kind']);
// Now try a POST to update the profile
$this->setRequest(Request::create(
'/bolt/profile',
'POST',
[
'user_profile' => [
'email' => $user['email'],
'displayname' => 'Admin Test',
'_token' => 'xyz',
],
]
));
$this->controller()->profile($this->getRequest());
$this->assertNotEmpty($this->getFlashBag()->get('success'));
}
public function testUsernameEditKillsSession()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
// Update the display name via a POST request
$this->setRequest(Request::create(
'/bolt/users/edit/1',
'POST',
[
'user_edit' => [
'username' => 'admin2',
'email' => $user['email'],
'displayname' => $user['displayname'],
'_token' => 'xyz',
],
]
));
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt/login', $response->getTargetUrl());
}
public function testViewRoles()
{
$this->setRequest(Request::create('/bolt/roles'));
$response = $this->controller()->viewRoles();
$context = $response->getContext();
$this->assertEquals('@bolt/roles/roles.twig', $response->getTemplate());
$this->assertNotEmpty($context['context']['global_permissions']);
$this->assertNotEmpty($context['context']['effective_permissions']);
}
/**
* @return \Bolt\Controller\Backend\Users
*/
protected function controller()
{
return $this->getService('controller.backend.users');
}
}
| GawainLynch/bolt | tests/phpunit/unit/Controller/Backend/UsersTest.php | PHP | mit | 13,704 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript'; // used as value and is provided at runtime
import {locateSymbols} from './locate_symbol';
import {findTightestNode, getClassDeclFromDecoratorProp, getPropertyAssignmentFromValue} from './ts_utils';
import {AstResult, Span} from './types';
import {extractAbsoluteFilePath} from './utils';
/**
* Convert Angular Span to TypeScript TextSpan. Angular Span has 'start' and
* 'end' whereas TS TextSpan has 'start' and 'length'.
* @param span Angular Span
*/
function ngSpanToTsTextSpan(span: Span): ts.TextSpan {
return {
start: span.start,
length: span.end - span.start,
};
}
/**
* Attempts to get the definition of a file whose URL is specified in a property assignment in a
* directive decorator.
* Currently applies to `templateUrl` and `styleUrls` properties.
*/
function getUrlFromProperty(
urlNode: ts.StringLiteralLike,
tsLsHost: Readonly<ts.LanguageServiceHost>): ts.DefinitionInfoAndBoundSpan|undefined {
// Get the property assignment node corresponding to the `templateUrl` or `styleUrls` assignment.
// These assignments are specified differently; `templateUrl` is a string, and `styleUrls` is
// an array of strings:
// {
// templateUrl: './template.ng.html',
// styleUrls: ['./style.css', './other-style.css']
// }
// `templateUrl`'s property assignment can be found from the string literal node;
// `styleUrls`'s property assignment can be found from the array (parent) node.
//
// First search for `templateUrl`.
let asgn = getPropertyAssignmentFromValue(urlNode, 'templateUrl');
if (!asgn) {
// `templateUrl` assignment not found; search for `styleUrls` array assignment.
asgn = getPropertyAssignmentFromValue(urlNode.parent, 'styleUrls');
if (!asgn) {
// Nothing found, bail.
return;
}
}
// If the property assignment is not a property of a class decorator, don't generate definitions
// for it.
if (!getClassDeclFromDecoratorProp(asgn)) {
return;
}
// Extract url path specified by the url node, which is relative to the TypeScript source file
// the url node is defined in.
const url = extractAbsoluteFilePath(urlNode);
// If the file does not exist, bail. It is possible that the TypeScript language service host
// does not have a `fileExists` method, in which case optimistically assume the file exists.
if (tsLsHost.fileExists && !tsLsHost.fileExists(url)) return;
const templateDefinitions: ts.DefinitionInfo[] = [{
kind: ts.ScriptElementKind.externalModuleName,
name: url,
containerKind: ts.ScriptElementKind.unknown,
containerName: '',
// Reading the template is expensive, so don't provide a preview.
textSpan: {start: 0, length: 0},
fileName: url,
}];
return {
definitions: templateDefinitions,
textSpan: {
// Exclude opening and closing quotes in the url span.
start: urlNode.getStart() + 1,
length: urlNode.getWidth() - 2,
},
};
}
/**
* Traverse the template AST and look for the symbol located at `position`, then
* return its definition and span of bound text.
* @param info
* @param position
*/
export function getDefinitionAndBoundSpan(
info: AstResult, position: number): ts.DefinitionInfoAndBoundSpan|undefined {
const symbols = locateSymbols(info, position);
if (!symbols.length) {
return;
}
const seen = new Set<string>();
const definitions: ts.DefinitionInfo[] = [];
for (const symbolInfo of symbols) {
const {symbol} = symbolInfo;
// symbol.definition is really the locations of the symbol. There could be
// more than one. No meaningful info could be provided without any location.
const {kind, name, container, definition: locations} = symbol;
if (!locations || !locations.length) {
continue;
}
const containerKind =
container ? container.kind as ts.ScriptElementKind : ts.ScriptElementKind.unknown;
const containerName = container ? container.name : '';
for (const {fileName, span} of locations) {
const textSpan = ngSpanToTsTextSpan(span);
// In cases like two-way bindings, a request for the definitions of an expression may return
// two of the same definition:
// [(ngModel)]="prop"
// ^^^^ -- one definition for the property binding, one for the event binding
// To prune duplicate definitions, tag definitions with unique location signatures and ignore
// definitions whose locations have already been seen.
const signature = `${textSpan.start}:${textSpan.length}@${fileName}`;
if (seen.has(signature)) continue;
definitions.push({
kind: kind as ts.ScriptElementKind,
name,
containerKind,
containerName,
textSpan: ngSpanToTsTextSpan(span),
fileName: fileName,
});
seen.add(signature);
}
}
return {
definitions,
textSpan: symbols[0].span,
};
}
/**
* Gets an Angular-specific definition in a TypeScript source file.
*/
export function getTsDefinitionAndBoundSpan(
sf: ts.SourceFile, position: number,
tsLsHost: Readonly<ts.LanguageServiceHost>): ts.DefinitionInfoAndBoundSpan|undefined {
const node = findTightestNode(sf, position);
if (!node) return;
switch (node.kind) {
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
// Attempt to extract definition of a URL in a property assignment.
return getUrlFromProperty(node as ts.StringLiteralLike, tsLsHost);
default:
return undefined;
}
}
| blesh/angular | packages/language-service/src/definitions.ts | TypeScript | mit | 5,793 |
<?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*
* @defgroup Accounts Accounts
* @ingroup DolphinModules
*
* @{
*/
class BxAccntConfig extends BxBaseModGeneralConfig
{
protected $_oDb;
protected $_aHtmlIds;
/**
* Constructor
*/
public function __construct($aModule)
{
parent::__construct($aModule);
$this->CNF = array (
// page URIs
'URL_MANAGE_ADMINISTRATION' => 'page.php?i=accounts-administration',
// objects
'OBJECT_MENU_MANAGE_TOOLS' => 'bx_accounts_menu_manage_tools', //manage menu in content administration tools
'OBJECT_GRID_ADMINISTRATION' => 'bx_accounts_administration',
'OBJECT_GRID_MODERATION' => 'bx_accounts_moderation',
// some language keys
'T' => array (
'grid_action_err_delete' => '_bx_accnt_grid_action_err_delete',
'grid_action_err_perform' => '_bx_accnt_grid_action_err_perform',
'filter_item_active' => '_bx_accnt_grid_filter_item_title_adm_active',
'filter_item_pending' => '_bx_accnt_grid_filter_item_title_adm_pending',
'filter_item_suspended' => '_bx_accnt_grid_filter_item_title_adm_suspended',
'filter_item_select_one_filter1' => '_bx_accnt_grid_filter_item_title_adm_select_one_filter1',
)
);
$this->_aObjects = array(
'alert' => $this->_sName,
);
$this->_aJsClass = array(
'manage_tools' => 'BxAccntManageTools'
);
$this->_aJsObjects = array(
'manage_tools' => 'oBxAccntManageTools'
);
$this->_aGridObjects = array(
'moderation' => $this->CNF['OBJECT_GRID_MODERATION'],
'administration' => $this->CNF['OBJECT_GRID_ADMINISTRATION'],
);
$sHtmlPrefix = str_replace('_', '-', $this->_sName);
$this->_aHtmlIds = array(
'profile' => $sHtmlPrefix . '-profile-',
'profile_more_popup' => $sHtmlPrefix . '-profile-more-popup-',
);
}
public function init(&$oDb)
{
$this->_oDb = &$oDb;
}
public function getHtmlIds($sKey = '')
{
if(empty($sKey))
return $this->_aHtmlIds;
return isset($this->_aHtmlIds[$sKey]) ? $this->_aHtmlIds[$sKey] : '';
}
}
/** @} */
| camperjz/trident | modules/boonex/accounts/updates/8.0.1_8.0.2/source/classes/BxAccntConfig.php | PHP | mit | 2,465 |
<?php
use Automattic\Jetpack\Sync\Functions;
require_once dirname( __FILE__ ) . '/class.json-api-site-jetpack-base.php';
require_once dirname( __FILE__ ) . '/class.json-api-post-jetpack.php';
// this code runs on Jetpack (.org) sites
class Jetpack_Site extends Abstract_Jetpack_Site {
protected function get_mock_option( $name ) {
return get_option( 'jetpack_'.$name );
}
protected function get_constant( $name ) {
if ( defined( $name) ) {
return constant( $name );
}
return null;
}
protected function main_network_site() {
return network_site_url();
}
protected function wp_version() {
global $wp_version;
return $wp_version;
}
protected function max_upload_size() {
return wp_max_upload_size();
}
protected function wp_memory_limit() {
return wp_convert_hr_to_bytes( WP_MEMORY_LIMIT );
}
protected function wp_max_memory_limit() {
return wp_convert_hr_to_bytes( WP_MAX_MEMORY_LIMIT );
}
protected function is_main_network() {
return Jetpack::is_multi_network();
}
public function is_multisite() {
return (bool) is_multisite();
}
public function is_single_user_site() {
return (bool) Jetpack::is_single_user_site();
}
protected function is_version_controlled() {
return Functions::is_version_controlled();
}
protected function file_system_write_access() {
return Functions::file_system_write_access();
}
protected function current_theme_supports( $feature_name ) {
return current_theme_supports( $feature_name );
}
protected function get_theme_support( $feature_name ) {
return get_theme_support( $feature_name );
}
public function get_updates() {
return (array) Jetpack::get_updates();
}
function get_id() {
return $this->platform->token->blog_id;
}
function has_videopress() {
// TODO - this only works on wporg site - need to detect videopress option for remote Jetpack site on WPCOM
$videopress = Jetpack_Options::get_option( 'videopress', array() );
if ( isset( $videopress['blog_id'] ) && $videopress['blog_id'] > 0 ) {
return true;
}
return false;
}
function upgraded_filetypes_enabled() {
return true;
}
function is_mapped_domain() {
return true;
}
function get_unmapped_url() {
// Fallback to the home URL since all Jetpack sites don't have an unmapped *.wordpress.com domain.
return $this->get_url();
}
function is_redirect() {
return false;
}
function is_following() {
return false;
}
function has_wordads() {
return Jetpack::is_module_active( 'wordads' );
}
function get_frame_nonce() {
return false;
}
function get_jetpack_frame_nonce() {
return false;
}
function is_headstart_fresh() {
return false;
}
function allowed_file_types() {
$allowed_file_types = array();
// https://codex.wordpress.org/Uploading_Files
$mime_types = get_allowed_mime_types();
foreach ( $mime_types as $type => $mime_type ) {
$extras = explode( '|', $type );
foreach ( $extras as $extra ) {
$allowed_file_types[] = $extra;
}
}
return $allowed_file_types;
}
/**
* Return site's privacy status.
*
* @return boolean Is site private?
*/
function is_private() {
return (int) $this->get_atomic_cloud_site_option( 'blog_public' ) === -1;
}
/**
* Return site's coming soon status.
*
* @return boolean Is site "Coming soon"?
*/
function is_coming_soon() {
return $this->is_private() && (int) $this->get_atomic_cloud_site_option( 'wpcom_coming_soon' ) === 1;
}
/**
* Return site's launch status.
*
* @return string|boolean Launch status ('launched', 'unlaunched', or false).
*/
function get_launch_status() {
return $this->get_atomic_cloud_site_option( 'launch-status' );
}
function get_atomic_cloud_site_option( $option ) {
if ( ! jetpack_is_atomic_site() ) {
return false;
}
$jetpack = Jetpack::init();
if ( ! method_exists( $jetpack, 'get_cloud_site_options' ) ) {
return false;
}
$result = $jetpack->get_cloud_site_options( [ $option ] );
if ( ! array_key_exists( $option, $result ) ) {
return false;
}
return $result[ $option ];
}
function get_plan() {
return false;
}
function get_subscribers_count() {
return 0; // special magic fills this in on the WPCOM side
}
function get_capabilities() {
return false;
}
function get_locale() {
return get_bloginfo( 'language' );
}
/**
* The flag indicates that the site has Jetpack installed
*
* @return bool
*/
public function is_jetpack() {
return true;
}
/**
* The flag indicates that the site is connected to WP.com via Jetpack Connection
*
* @return bool
*/
public function is_jetpack_connection() {
return true;
}
public function get_jetpack_version() {
return JETPACK__VERSION;
}
function get_ak_vp_bundle_enabled() {}
function get_jetpack_seo_front_page_description() {
return Jetpack_SEO_Utils::get_front_page_meta_description();
}
function get_jetpack_seo_title_formats() {
return Jetpack_SEO_Titles::get_custom_title_formats();
}
function get_verification_services_codes() {
return get_option( 'verification_services_codes', null );
}
function get_podcasting_archive() {
return null;
}
function is_connected_site() {
return true;
}
function is_wpforteams_site() {
return false;
}
function current_user_can( $role ) {
return current_user_can( $role );
}
/**
* Check if full site editing should be considered as currently active. Full site editing
* requires the FSE plugin to be installed and activated, as well the current
* theme to be FSE compatible. The plugin can also be explicitly disabled via the
* a8c_disable_full_site_editing filter.
*
* @since 7.7.0
*
* @return bool true if full site editing is currently active.
*/
function is_fse_active() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_full_site_editing_active' ) && \A8C\FSE\is_full_site_editing_active();
}
/**
* Check if site should be considered as eligible for full site editing. Full site editing
* requires the FSE plugin to be installed and activated. For this method to return true
* the current theme does not need to be FSE compatible. The plugin can also be explicitly
* disabled via the a8c_disable_full_site_editing filter.
*
* @since 8.1.0
*
* @return bool true if site is eligible for full site editing
*/
public function is_fse_eligible() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_site_eligible_for_full_site_editing' ) && \A8C\FSE\is_site_eligible_for_full_site_editing();
}
/**
* Check if site should be considered as eligible for use of the core Site Editor.
* The Site Editor requires the FSE plugin to be installed and activated.
* The plugin can be explicitly enabled via the a8c_enable_core_site_editor filter.
*
* @return bool true if site is eligible for the Site Editor
*/
public function is_core_site_editor_enabled() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_site_editor_active' ) && \A8C\FSE\is_site_editor_active();
}
/**
* Return the last engine used for an import on the site.
*
* This option is not used in Jetpack.
*/
function get_import_engine() {
return null;
}
/**
* Post functions
*/
function wrap_post( $post, $context ) {
return new Jetpack_Post( $this, $post, $context );
}
}
| pjhooker/monferratopaesaggi | trunk/wp-content/plugins/jetpack/sal/class.json-api-site-jetpack.php | PHP | mit | 7,587 |
# Copyright (c) 2005 Zed A. Shaw
# You can redistribute it and/or modify it under the same terms as Ruby.
#
# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
# for more information.
require 'test/testhelp'
include Mongrel
class URIClassifierTest < Test::Unit::TestCase
def test_uri_finding
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/test", script_name
end
def test_root_handler_only
uri_classifier = URIClassifier.new
uri_classifier.register("/", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/", script_name
assert_equal "/test", path_info
end
def test_uri_prefix_ops
test = "/pre/fix/test"
prefix = "/pre"
uri_classifier = URIClassifier.new
uri_classifier.register(prefix,1)
script_name, path_info, value = uri_classifier.resolve(prefix)
script_name, path_info, value = uri_classifier.resolve(test)
assert_equal 1, value
assert_equal prefix, script_name
assert_equal test[script_name.length .. -1], path_info
assert uri_classifier.inspect
assert_equal prefix, uri_classifier.uris[0]
end
def test_not_finding
test = "/cant/find/me"
uri_classifier = URIClassifier.new
uri_classifier.register(test, 1)
script_name, path_info, value = uri_classifier.resolve("/nope/not/here")
assert_nil script_name
assert_nil path_info
assert_nil value
end
def test_exceptions
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
failed = false
begin
uri_classifier.register("/test", 1)
rescue => e
failed = true
end
assert failed
failed = false
begin
uri_classifier.register("", 1)
rescue => e
failed = true
end
assert failed
end
def test_register_unregister
uri_classifier = URIClassifier.new
100.times do
uri_classifier.register("/stuff", 1)
value = uri_classifier.unregister("/stuff")
assert_equal 1, value
end
uri_classifier.register("/things",1)
script_name, path_info, value = uri_classifier.resolve("/things")
assert_equal 1, value
uri_classifier.unregister("/things")
script_name, path_info, value = uri_classifier.resolve("/things")
assert_nil value
end
def test_uri_branching
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
uri_classifier.register("/test/this",2)
script_name, path_info, handler = uri_classifier.resolve("/test")
script_name, path_info, handler = uri_classifier.resolve("/test/that")
assert_equal "/test", script_name, "failed to properly find script off branch portion of uri"
assert_equal "/that", path_info
assert_equal 1, handler, "wrong result for branching uri"
end
def test_all_prefixing
tests = ["/test","/test/that","/test/this"]
uri = "/test/this/that"
uri_classifier = URIClassifier.new
current = ""
uri.each_byte do |c|
current << c.chr
uri_classifier.register(current, c)
end
# Try to resolve everything with no asserts as a fuzzing
tests.each do |prefix|
current = ""
prefix.each_byte do |c|
current << c.chr
script_name, path_info, handler = uri_classifier.resolve(current)
assert script_name
assert path_info
assert handler
end
end
# Assert that we find stuff
tests.each do |t|
script_name, path_info, handler = uri_classifier.resolve(t)
assert handler
end
# Assert we don't find stuff
script_name, path_info, handler = uri_classifier.resolve("chicken")
assert_nil handler
assert_nil script_name
assert_nil path_info
end
# Verifies that a root mounted ("/") handler resolves
# such that path info matches the original URI.
# This is needed to accommodate real usage of handlers.
def test_root_mounted
uri_classifier = URIClassifier.new
root = "/"
path = "/this/is/a/test"
uri_classifier.register(root, 1)
script_name, path_info, handler = uri_classifier.resolve(root)
assert_equal 1, handler
assert_equal root, path_info
assert_equal root, script_name
script_name, path_info, handler = uri_classifier.resolve(path)
assert_equal path, path_info
assert_equal root, script_name
assert_equal 1, handler
end
# Verifies that a root mounted ("/") handler
# is the default point, doesn't matter the order we use
# to register the URIs
def test_classifier_order
tests = ["/before", "/way_past"]
root = "/"
path = "/path"
uri_classifier = URIClassifier.new
uri_classifier.register(path, 1)
uri_classifier.register(root, 2)
tests.each do |uri|
script_name, path_info, handler = uri_classifier.resolve(uri)
assert_equal root, script_name, "#{uri} did not resolve to #{root}"
assert_equal uri, path_info
assert_equal 2, handler
end
end
if ENV['BENCHMARK']
# Eventually we will have a suite of benchmarks instead of lamely installing a test
def test_benchmark
# This URI set should favor a TST. Both versions increase linearly until you hit 14
# URIs, then the TST flattens out.
@uris = %w(
/
/dag /dig /digbark /dog /dogbark /dog/bark /dug /dugbarking /puppy
/c /cat /cat/tree /cat/tree/mulberry /cats /cot /cot/tree/mulberry /kitty /kittycat
# /eag /eig /eigbark /eog /eogbark /eog/bark /eug /eugbarking /iuppy
# /f /fat /fat/tree /fat/tree/mulberry /fats /fot /fot/tree/mulberry /jitty /jittyfat
# /gag /gig /gigbark /gog /gogbark /gog/bark /gug /gugbarking /kuppy
# /h /hat /hat/tree /hat/tree/mulberry /hats /hot /hot/tree/mulberry /litty /littyhat
# /ceag /ceig /ceigbark /ceog /ceogbark /ceog/cbark /ceug /ceugbarking /ciuppy
# /cf /cfat /cfat/ctree /cfat/ctree/cmulberry /cfats /cfot /cfot/ctree/cmulberry /cjitty /cjittyfat
# /cgag /cgig /cgigbark /cgog /cgogbark /cgog/cbark /cgug /cgugbarking /ckuppy
# /ch /chat /chat/ctree /chat/ctree/cmulberry /chats /chot /chot/ctree/cmulberry /citty /cittyhat
)
@requests = %w(
/
/dig
/digging
/dogging
/dogbarking/
/puppy/barking
/c
/cat
/cat/shrub
/cat/tree
/cat/tree/maple
/cat/tree/mulberry/tree
/cat/tree/oak
/cats/
/cats/tree
/cod
/zebra
)
@classifier = URIClassifier.new
@uris.each do |uri|
@classifier.register(uri, 1)
end
puts "#{@uris.size} URIs / #{@requests.size * 10000} requests"
Benchmark.bm do |x|
x.report do
# require 'ruby-prof'
# profile = RubyProf.profile do
10000.times do
@requests.each do |request|
@classifier.resolve(request)
end
end
# end
# File.open("profile.html", 'w') { |file| RubyProf::GraphHtmlPrinter.new(profile).print(file, 0) }
end
end
end
end
end
| claudiobm/ClockingIT-In-CapellaDesign | vendor/gems/mongrel-1.1.5/test/test_uriclassifier.rb | Ruby | mit | 7,361 |
require 'uri'
module Idobata::Hook
class PivotalTracker
module Helper
filters = [
::HTML::Pipeline::MarkdownFilter
]
filters << ::HTML::Pipeline::SyntaxHighlightFilter if defined?(Linguist) # This filter doesn't work on heroku
Pipeline = ::HTML::Pipeline.new(filters, gfm: true, base_url: 'https://www.pivotaltracker.com/')
def md(source)
result = Pipeline.call(source)
result[:output].to_s.html_safe
end
def new_value(kind)
new_values(kind).first
end
def new_values(kind)
payload.changes.select {|change| change.kind == kind.to_s }.map(&:new_values).compact
end
def download_url(attachment)
download_url = URI.parse(attachment.download_url)
# XXX Current API returns only path info.
unless download_url.host
download_url.scheme = 'https'
download_url.host = 'www.pivotaltracker.com'
end
download_url.query = {inline: true}.to_param unless download_url.query
download_url.to_s
end
end
end
end
| SuzukiMasashi/idobata-hooks | lib/hooks/pivotal_tracker/helper.rb | Ruby | mit | 1,098 |
import { __decorate } from 'tslib';
import { NgModule } from '@angular/core';
import { ANGULARTICS2_TOKEN, RouterlessTracking, Angulartics2, Angulartics2OnModule } from 'angulartics2';
var Angulartics2RouterlessModule_1;
let Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = class Angulartics2RouterlessModule {
static forRoot(settings = {}) {
return {
ngModule: Angulartics2RouterlessModule_1,
providers: [
{ provide: ANGULARTICS2_TOKEN, useValue: { settings } },
RouterlessTracking,
Angulartics2,
],
};
}
};
Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = __decorate([
NgModule({
imports: [Angulartics2OnModule],
})
], Angulartics2RouterlessModule);
export { Angulartics2RouterlessModule };
//# sourceMappingURL=angulartics2-routerlessmodule.js.map
| cdnjs/cdnjs | ajax/libs/angulartics2/8.3.0/routerlessmodule/fesm2015/angulartics2-routerlessmodule.js | JavaScript | mit | 907 |
/*******************************************************************************
* Copyright (c) 2010, 2011 Sean Muir
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sean Muir (JKM Software) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.uml.cda.builder.test;
import org.junit.Assert;
import org.junit.Test;
import org.openhealthtools.mdht.uml.cda.ClinicalDocument;
import org.openhealthtools.mdht.uml.cda.Section;
import org.openhealthtools.mdht.uml.cda.builder.CDABuilderFactory;
import org.openhealthtools.mdht.uml.cda.builder.DocumentBuilder;
import org.openhealthtools.mdht.uml.cda.builder.SectionBuilder;
import org.openhealthtools.mdht.uml.cda.util.CDAUtil;
public class TestCDABuilderFactory {
@Test
public void testCreateClinicalDocumentBuilder() throws Exception {
DocumentBuilder<ClinicalDocument> clinicalDocumentBuilder = CDABuilderFactory.createClinicalDocumentBuilder();
ClinicalDocument clinicalDocument = clinicalDocumentBuilder.buildDocument();
Assert.assertNotNull(clinicalDocument);
CDAUtil.save(clinicalDocument, System.out);
}
@Test
public void testCreateSectionBuilder() throws Exception {
DocumentBuilder<ClinicalDocument> clinicalDocumentBuilder = CDABuilderFactory.createClinicalDocumentBuilder();
SectionBuilder<Section> sectionBuilder = CDABuilderFactory.createSectionBuilder();
Section section = sectionBuilder.buildSection();
Assert.assertNotNull(section);
CDAUtil.save(clinicalDocumentBuilder.with(section).buildDocument(), System.out);
}
}
| drbgfc/mdht | cda/examples/org.openhealthtools.mdht.cda.builder/src/org/openhealthtools/mdht/uml/cda/builder/test/TestCDABuilderFactory.java | Java | epl-1.0 | 1,871 |
/*******************************************************************************
* Copyright (c) 2012 David A Carlson.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.cts2.codesystem.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryDirectory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryList;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryListEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryMsg;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntrySummary;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemFactory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemPackage;
import org.openhealthtools.mdht.cts2.codesystem.DocumentRoot;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
*
* @generated
*/
public class CodeSystemFactoryImpl extends EFactoryImpl implements CodeSystemFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public static CodeSystemFactory init() {
try {
CodeSystemFactory theCodeSystemFactory = (CodeSystemFactory) EPackage.Registry.INSTANCE.getEFactory("http://schema.omg.org/spec/CTS2/1.0/CodeSystem");
if (theCodeSystemFactory != null) {
return theCodeSystemFactory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new CodeSystemFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY:
return createCodeSystemCatalogEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_DIRECTORY:
return createCodeSystemCatalogEntryDirectory();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST:
return createCodeSystemCatalogEntryList();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST_ENTRY:
return createCodeSystemCatalogEntryListEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_MSG:
return createCodeSystemCatalogEntryMsg();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_SUMMARY:
return createCodeSystemCatalogEntrySummary();
case CodeSystemPackage.DOCUMENT_ROOT:
return createDocumentRoot();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntry createCodeSystemCatalogEntry() {
CodeSystemCatalogEntryImpl codeSystemCatalogEntry = new CodeSystemCatalogEntryImpl();
return codeSystemCatalogEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryDirectory createCodeSystemCatalogEntryDirectory() {
CodeSystemCatalogEntryDirectoryImpl codeSystemCatalogEntryDirectory = new CodeSystemCatalogEntryDirectoryImpl();
return codeSystemCatalogEntryDirectory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryList createCodeSystemCatalogEntryList() {
CodeSystemCatalogEntryListImpl codeSystemCatalogEntryList = new CodeSystemCatalogEntryListImpl();
return codeSystemCatalogEntryList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryListEntry createCodeSystemCatalogEntryListEntry() {
CodeSystemCatalogEntryListEntryImpl codeSystemCatalogEntryListEntry = new CodeSystemCatalogEntryListEntryImpl();
return codeSystemCatalogEntryListEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryMsg createCodeSystemCatalogEntryMsg() {
CodeSystemCatalogEntryMsgImpl codeSystemCatalogEntryMsg = new CodeSystemCatalogEntryMsgImpl();
return codeSystemCatalogEntryMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntrySummary createCodeSystemCatalogEntrySummary() {
CodeSystemCatalogEntrySummaryImpl codeSystemCatalogEntrySummary = new CodeSystemCatalogEntrySummaryImpl();
return codeSystemCatalogEntrySummary;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemPackage getCodeSystemPackage() {
return (CodeSystemPackage) getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @deprecated
* @generated
*/
@Deprecated
public static CodeSystemPackage getPackage() {
return CodeSystemPackage.eINSTANCE;
}
} // CodeSystemFactoryImpl
| drbgfc/mdht | cts2/plugins/org.openhealthtools.mdht.cts2.core/src/org/openhealthtools/mdht/cts2/codesystem/impl/CodeSystemFactoryImpl.java | Java | epl-1.0 | 5,866 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.concepts.lang;
public interface Acceptor<I> {
/**
*
* @param input
* @return true if input is accepted.
*/
boolean isAcceptable(I input);
}
| xiaohanz/softcontroller | opendaylight/sal/yang-prototype/concepts-lang/src/main/java/org/opendaylight/controller/concepts/lang/Acceptor.java | Java | epl-1.0 | 516 |
/*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.git.exception;
/**
* @author Yossi Balan (yossi.balan@sap.com)
*/
public class GitInvalidRefNameException extends GitException {
/**
* Construct a new GitInvalidRefNameException based on message
*
* @param message
* error message
*/
public GitInvalidRefNameException(String message) {
super(message);
}
/**
* Construct a new GitInvalidRefNameException based on cause
*
* @param cause
* cause exception
*/
public GitInvalidRefNameException(Throwable cause) {
super(cause);
}
/**
* Construct a new GitInvalidRefNameException based on message and cause
*
* @param message
* error message
* @param cause
* cause exception
*/
public GitInvalidRefNameException(String message, Throwable cause) {
super(message, cause);
}
}
| kaloyan-raev/che | wsagent/che-core-api-git/src/main/java/org/eclipse/che/api/git/exception/GitInvalidRefNameException.java | Java | epl-1.0 | 1,446 |
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.jaxws;
import org.jboss.forge.addon.javaee.JavaEEFacet;
import org.jboss.forge.addon.projects.Project;
/**
* If installed, this {@link Project} supports features from the JAX-WS specification.
*
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public interface JAXWSFacet extends JavaEEFacet
{
}
| agoncal/core | javaee/api/src/main/java/org/jboss/forge/addon/javaee/jaxws/JAXWSFacet.java | Java | epl-1.0 | 550 |
package io.liveoak.scripts.resourcetriggered.interceptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import io.liveoak.common.DefaultResourceErrorResponse;
import io.liveoak.scripts.objects.Util;
import io.liveoak.scripts.objects.impl.exception.LiveOakException;
import io.liveoak.scripts.resourcetriggered.manager.ResourceScriptManager;
import io.liveoak.spi.Application;
import io.liveoak.spi.ResourceErrorResponse;
import io.liveoak.spi.ResourcePath;
import io.liveoak.spi.ResourceRequest;
import io.liveoak.spi.ResourceResponse;
import io.liveoak.spi.container.interceptor.DefaultInterceptor;
import io.liveoak.spi.container.interceptor.InboundInterceptorContext;
import io.liveoak.spi.container.interceptor.OutboundInterceptorContext;
import org.dynjs.exception.ThrowException;
/**
* @author <a href="mailto:mwringe@redhat.com">Matt Wringe</a>
*/
public class ScriptInterceptor extends DefaultInterceptor {
Map<String, ResourceScriptManager> managers;
private static final String DYNJS_ERROR_PREFIX = "Error: ";
public ScriptInterceptor() {
managers = new HashMap<>();
}
@Override
public void onInbound(InboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.request());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.request());
if (reply instanceof ResourceRequest) {
context.forward((ResourceRequest) reply);
} else if (reply instanceof ResourceResponse) {
context.replyWith((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing request";
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, message));
return;
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.replyWith(Util.getErrorResponse(context.request(), (LiveOakException)value));
return;
}
}
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onOutbound(OutboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.response().inReplyTo());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.response());
if (reply instanceof ResourceResponse) {
context.forward((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing response";
//TODO: remove the "Error: " check here, its because DynJS for some reason uses a crappy empty error message.
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.forward(Util.getErrorResponse(context.response().inReplyTo(), (LiveOakException)value));
return;
}
}
context.forward(new DefaultResourceErrorResponse(context.response().inReplyTo(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onComplete(UUID requestId) {
//currently do nothing.
}
private String getApplicationName(ResourceRequest request) {
//TODO: once we have the application actually being added to the requestContext remove getting the name from the ResourcePath
List<ResourcePath.Segment> resourcePaths = request.resourcePath().segments();
String applicationName = "/";
if (resourcePaths.size() > 0) {
applicationName = resourcePaths.get(0).name();
}
// TODO: This is proper way to check, but application is currently not set
Application application = request.requestContext().application();
if (application != null) {
applicationName = application.id();
}
return applicationName;
}
public void addManager(String applicationName, ResourceScriptManager manager) {
managers.put(applicationName, manager);
}
public void removeManager(String applicationName) {
managers.remove(applicationName);
}
}
| liveoak-io/liveoak | modules/scripts/src/main/java/io/liveoak/scripts/resourcetriggered/interceptor/ScriptInterceptor.java | Java | epl-1.0 | 5,830 |
define(['events', 'libraryBrowser', 'imageLoader', 'listView', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, listView) {
return function (view, params, tabContent) {
var self = this;
var data = {};
function getPageData(context) {
var key = getSavedQueryKey(context);
var pageData = data[key];
if (!pageData) {
pageData = data[key] = {
query: {
SortBy: "Album,SortName",
SortOrder: "Ascending",
IncludeItemTypes: "Audio",
Recursive: true,
Fields: "AudioInfo,ParentId",
Limit: 100,
StartIndex: 0,
ImageTypeLimit: 1,
EnableImageTypes: "Primary"
}
};
pageData.query.ParentId = params.topParentId;
libraryBrowser.loadSavedQueryValues(key, pageData.query);
}
return pageData;
}
function getQuery(context) {
return getPageData(context).query;
}
function getSavedQueryKey(context) {
if (!context.savedQueryKey) {
context.savedQueryKey = libraryBrowser.getSavedQueryKey('songs');
}
return context.savedQueryKey;
}
function reloadItems(page) {
Dashboard.showLoadingMsg();
var query = getQuery(page);
ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) {
// Scroll back up so they can see the results from the beginning
window.scrollTo(0, 0);
updateFilterControls(page);
var pagingHtml = LibraryBrowser.getQueryPagingHtml({
startIndex: query.StartIndex,
limit: query.Limit,
totalRecordCount: result.TotalRecordCount,
showLimit: false,
updatePageSizeSetting: false,
addLayoutButton: false,
sortButton: false,
filterButton: false
});
var html = listView.getListViewHtml({
items: result.Items,
action: 'playallfromhere',
smallIcon: true
});
var i, length;
var elems = tabContent.querySelectorAll('.paging');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].innerHTML = pagingHtml;
}
function onNextPageClick() {
query.StartIndex += query.Limit;
reloadItems(tabContent);
}
function onPreviousPageClick() {
query.StartIndex -= query.Limit;
reloadItems(tabContent);
}
elems = tabContent.querySelectorAll('.btnNextPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onNextPageClick);
}
elems = tabContent.querySelectorAll('.btnPreviousPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onPreviousPageClick);
}
var itemsContainer = tabContent.querySelector('.itemsContainer');
itemsContainer.innerHTML = html;
imageLoader.lazyChildren(itemsContainer);
libraryBrowser.saveQueryValues(getSavedQueryKey(page), query);
Dashboard.hideLoadingMsg();
});
}
self.showFilterMenu = function () {
require(['components/filterdialog/filterdialog'], function (filterDialogFactory) {
var filterDialog = new filterDialogFactory({
query: getQuery(tabContent),
mode: 'songs'
});
Events.on(filterDialog, 'filterchange', function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
});
filterDialog.show();
});
}
function updateFilterControls(tabContent) {
}
function initPage(tabContent) {
tabContent.querySelector('.btnFilter').addEventListener('click', function () {
self.showFilterMenu();
});
tabContent.querySelector('.btnSort').addEventListener('click', function (e) {
libraryBrowser.showSortMenu({
items: [{
name: Globalize.translate('OptionTrackName'),
id: 'Name'
},
{
name: Globalize.translate('OptionAlbum'),
id: 'Album,SortName'
},
{
name: Globalize.translate('OptionAlbumArtist'),
id: 'AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionArtist'),
id: 'Artist,Album,SortName'
},
{
name: Globalize.translate('OptionDateAdded'),
id: 'DateCreated,SortName'
},
{
name: Globalize.translate('OptionDatePlayed'),
id: 'DatePlayed,SortName'
},
{
name: Globalize.translate('OptionPlayCount'),
id: 'PlayCount,SortName'
},
{
name: Globalize.translate('OptionReleaseDate'),
id: 'PremiereDate,AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionRuntime'),
id: 'Runtime,AlbumArtist,Album,SortName'
}],
callback: function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
},
query: getQuery(tabContent),
button: e.target
});
});
}
self.getCurrentViewStyle = function () {
return getPageData(tabContent).view;
};
initPage(tabContent);
self.renderTab = function () {
reloadItems(tabContent);
updateFilterControls(tabContent);
};
self.destroy = function () {
};
};
}); | 7illusions/Emby | MediaBrowser.WebDashboard/dashboard-ui/scripts/songs.js | JavaScript | gpl-2.0 | 7,309 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/config-manager.h"
#include "engines/advancedDetector.h"
#include "base/plugins.h"
#include "tucker/detection.h"
static const PlainGameDescriptor tuckerGames[] = {
{ "tucker", "Bud Tucker in Double Trouble" },
{ nullptr, nullptr }
};
static const ADGameDescription tuckerGameDescriptions[] = {
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "f1e42a95972643462b9c3c2ea79d6683", 543),
Common::FR_FRA,
Common::kPlatformDOS,
Tucker::kGameFlagNoSubtitles,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "9c1ddeafc5283b90d1a284bd0924831c", 462),
Common::EN_ANY,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "1b3ea79d8528ea3c7df83dd0ed345e37", 525),
Common::ES_ESP,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobrgr.txt", "4df9eb65722418d1a1723508115b146c", 552),
Common::DE_DEU,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "5f85285bbc23ce57cbc164021ee1f23c", 525),
Common::PL_POL,
Common::kPlatformDOS,
0,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "e548994877ff31ca304f6352ce022a8e", 497),
Common::CZ_CZE,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{ // Russian fan translation
"tucker",
"",
AD_ENTRY1s("infobrgr.txt", "4b5a315e449a7f9eaf2025ec87466cd8", 552),
Common::RU_RUS,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"Demo",
AD_ENTRY1s("infobar.txt", "010b055de42097b140d5bcb6e95a5c7c", 203),
Common::EN_ANY,
Common::kPlatformDOS,
ADGF_DEMO | Tucker::kGameFlagDemo,
GUIO1(GUIO_NOMIDI)
},
AD_TABLE_END_MARKER
};
static const ADGameDescription tuckerDemoGameDescription = {
"tucker",
"Non-Interactive Demo",
AD_ENTRY1(0, 0),
Common::EN_ANY,
Common::kPlatformDOS,
ADGF_DEMO | Tucker::kGameFlagDemo | Tucker::kGameFlagIntroOnly,
GUIO1(GUIO_NOMIDI)
};
class TuckerMetaEngineDetection : public AdvancedMetaEngineDetection {
public:
TuckerMetaEngineDetection() : AdvancedMetaEngineDetection(tuckerGameDescriptions, sizeof(ADGameDescription), tuckerGames) {
_md5Bytes = 512;
}
const char *getEngineId() const override {
return "tucker";
}
const char *getName() const override {
return "Bud Tucker in Double Trouble";
}
const char *getOriginalCopyright() const override {
return "Bud Tucker in Double Trouble (C) Merit Studios";
}
ADDetectedGame fallbackDetect(const FileMap &allFiles, const Common::FSList &fslist) const override {
for (Common::FSList::const_iterator d = fslist.begin(); d != fslist.end(); ++d) {
Common::FSList audiofslist;
if (d->isDirectory() && d->getName().equalsIgnoreCase("audio") && d->getChildren(audiofslist, Common::FSNode::kListFilesOnly)) {
for (Common::FSList::const_iterator f = audiofslist.begin(); f != audiofslist.end(); ++f) {
if (!f->isDirectory() && f->getName().equalsIgnoreCase("demorolc.raw")) {
return ADDetectedGame(&tuckerDemoGameDescription);
}
}
}
}
return ADDetectedGame();
}
};
REGISTER_PLUGIN_STATIC(TUCKER_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, TuckerMetaEngineDetection);
| somaen/scummvm | engines/tucker/detection.cpp | C++ | gpl-2.0 | 4,298 |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Lib.JSON
{
/// <summary>
/// Specifies the type of Json token.
/// </summary>
public enum JsonToken
{
/// <summary>
/// This is returned by the <see cref="JsonReader"/> if a <see cref="JsonReader.Read"/> method has not been called.
/// </summary>
None,
/// <summary>
/// An object start token.
/// </summary>
StartObject,
/// <summary>
/// An array start token.
/// </summary>
StartArray,
/// <summary>
/// A constructor start token.
/// </summary>
StartConstructor,
/// <summary>
/// An object property name.
/// </summary>
PropertyName,
/// <summary>
/// A comment.
/// </summary>
Comment,
/// <summary>
/// Raw JSON.
/// </summary>
Raw,
/// <summary>
/// An integer.
/// </summary>
Integer,
/// <summary>
/// A float.
/// </summary>
Float,
/// <summary>
/// A string.
/// </summary>
String,
/// <summary>
/// A boolean.
/// </summary>
Boolean,
/// <summary>
/// A null token.
/// </summary>
Null,
/// <summary>
/// An undefined token.
/// </summary>
Undefined,
/// <summary>
/// An object end token.
/// </summary>
EndObject,
/// <summary>
/// An array end token.
/// </summary>
EndArray,
/// <summary>
/// A constructor end token.
/// </summary>
EndConstructor,
/// <summary>
/// A Date.
/// </summary>
Date,
/// <summary>
/// Byte data.
/// </summary>
Bytes
}
} | MyvarHD/OpenIDE | OpenIDE/OpenIDE.Library/Base/JSON/JsonToken.cs | C# | gpl-2.0 | 2,797 |
var armorSetPvPSuperior = new armorSetObject("pvpsuperior");
armorSetPvPSuperior.slotsArray = new Array();
t = 0;
armorSetPvPSuperior.slotsArray[t] = "head"; t++;
armorSetPvPSuperior.slotsArray[t] = "shoulder"; t++;
armorSetPvPSuperior.slotsArray[t] = "chest"; t++;
armorSetPvPSuperior.slotsArray[t] = "hands"; t++;
armorSetPvPSuperior.slotsArray[t] = "legs"; t++;
armorSetPvPSuperior.slotsArray[t] = "feet"; t++;
armorSetPvPSuperior.slotsNumber = armorSetPvPSuperior.slotsArray.length;
armorSetPvPSuperior.statsArray = new Array();
armorSetPvPSuperior.itemNameArray = new Array();
armorSetPvPSuperior.setNameArray = new Array();
t = 0;
armorSetPvPSuperior.setNamesArray = new Array();
x = 0;
armorSetPvPSuperior.setNamesArray[x] = "Refuge"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Pursuance"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Arcanum"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Redoubt"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Investiture"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Guard"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Stormcaller"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Dreadgear"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Battlearmor"; x++;
classCounter = 0;
//DONT LOCALIZE ABOVE THIS COMMENT LINE
//LOCALIZE EVERYTHING BELOW THIS COMMENT LINE
//druid begin
var sanctuaryBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power<br>\
(4) Set: Increases your movement speed by 15% while in Bear, Cat, or Travel Form. Only active outdoors.<br>\
(6) Set: +20 Stamina\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dragonhide Shoulders<br>\
Lieutenant Commander\'s Dragonhide Headguard<br>\
Knight-Captain\'s Dragonhide Leggings<br>\
Knight-Captain\'s Dragonhide Chestpiece<br>\
Knight-Lieutenant\'s Dragonhide Treads<br>\
Knight-Lieutenant\'s Dragonhide Grips<br>\
</span>'+ sanctuaryBlue, '<span class = "myYellow">\
Champion\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dragonhide Treads<br>\
Blood Guard\'s Dragonhide Grips<br>\
Legionnaire\'s Dragonhide Chestpiece<br>\
Legionnaire\'s Dragonhide Leggings<br>\
Champion\'s Dragonhide Headguard<br>\
Champion\'s Dragonhide Shoulders<br>\
</span>'+ sanctuaryBlue];
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Headguard', '<span class = "myBlue">\
Champion\'s Dragonhide Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
198 Armor<br>\
+16 Strength<br>\
+12 Agility<br>\
+16 Stamina<br>\
+16 Intellect<br>\
+8 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Shoulders', '<span class = "myBlue">\
Champion\'s Dragonhide Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
206 Armor<br>\
+12 Strength<br>\
+6 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
218 Armor<br>\
+13 Strength<br>\
+12 Agility<br>\
+13 Stamina<br>\
+12 Intellect<br>\
Classes: Druid<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 15.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Grips', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
115 Armor<br>\
+13 Strength<br>\
+10 Agility<br>\
+12 Stamina<br>\
+9 Intellect<br>\
Classes: Druid<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Slightly increases your stealth detection.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Leggings', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
215 Armor<br>\
+12 Strength<br>\
+12 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+5 Spirit<br>\
Classes: Druid<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Treads', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Treads'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
126 Armor<br>\
+13 Strength<br>\
+6 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//druid end
classCounter++;
//hunter begin
var pursuitBlue = '<span class = "myGreen">\
(2) Set: +20 Agility.<br>\
(4) Set: Reduces the cooldown of your Concussive Shot by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Chain Shoulders<br>\
Lieutenant Commander\'s Chain Helm<br>\
Knight-Captain\'s Chain Legguards<br>\
Knight-Captain\'s Chain Hauberk<br>\
Knight-Lieutenant\'s Chain Greaves<br>\
Knight-Lieutenant\'s Chain Vices<br>\
</span>'+ pursuitBlue, '<span class = "myYellow">\
Champion\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Chain Greaves<br>\
Blood Guard\'s Chain Vices<br>\
Legionnaire\'s Chain Hauberk<br>\
Legionnaire\'s Chain Legguards<br>\
Champion\'s Chain Helm<br>\
Champion\'s Chain Shoulders<br>\
</span>'+ pursuitBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Helm', '<span class = "myBlue">\
Champion\'s Chain Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+18 Agility<br>\
+14 Stamina<br>\
+9 Intellect<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Shoulders', '<span class = "myBlue">\
Champion\'s Chain Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+18 Agility<br>\
+13 Stamina<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Hauberk', '<span class = "myBlue">\
Legionnaire\'s Chain Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Vices', '<span class = "myBlue">\
Blood Guard\'s Chain Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+18 Agility<br>\
+16 Stamina<br>\
Classes: Hunter<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage done by your Multi-Shot by 4%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Legguards', '<span class = "myBlue">\
Legionnaire\'s Chain Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Greaves', '<span class = "myBlue">\
Blood Guard\'s Chain Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+20 Agility<br>\
+19 Stamina<br>\
Classes: Hunter<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//hunter end
classCounter++;
//mage begin
var regaliaBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Blink spell by 1.5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Silk Mantle<br>\
Lieutenant Commander\'s Silk Cowl<br>\
Knight-Captain\'s Silk Legguards<br>\
Knight-Captain\'s Silk Tunic<br>\
Knight-Lieutenant\'s Silk Walkers<br>\
Knight-Lieutenant\'s Silk Handwraps<br>\
</span>'+ regaliaBlue, '<span class = "myYellow">\
Champion\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Silk Walkers<br>\
Blood Guard\'s Silk Handwraps<br>\
Legionnaire\'s Silk Tunic<br>\
Legionnaire\'s Silk Legguards<br>\
Champion\'s Silk Cowl<br>\
Champion\'s Silk Mantle<br>\
</span>'+ regaliaBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Cowl', '<span class = "myBlue">\
Champion\'s Silk Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
141 Armor<br>\
+19 Stamina<br>\
+18 Intellect<br>\
+6 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Mantle', '<span class = "myBlue">\
Champion\'s Silk Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
135 Armor<br>\
+14 Stamina<br>\
+11 Intellect<br>\
+4 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equp: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Tunic', '<span class = "myBlue">\
Legionnaires\'s Silk Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Handwraps', '<span class = "myBlue">\
Blood Guard\'s Silk Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage absorbed by your Mana Shield by 285.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Legguards', '<span class = "myBlue">\
Legionnaire\'s Silk Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Walkers', '<span class = "myBlue">\
Blood Guard\'s Silk Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
104 Armor<br>\
+15 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to hit with spells by 1%.</span>\
<p>';
//mage end
classCounter++;
//paladin begin
var aegisBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Hammer of Justice by 10 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Redoubt (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Lamellar Shoulders<br>\
Lieutenant Commander\'s Lamellar Headguard<br>\
Knight-Captain\'s Lamellar Leggings<br>\
Knight-Captain\'s Lamellar Breastplate<br>\
Knight-Lieutenant\'s Lamellar Sabatons<br>\
Knight-Lieutenant\'s Lamellar Gauntlets<br>\
</span>'+ aegisBlue, ''];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Headguard', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+18 Strength<br>\
+19 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Increases damage and healing done by magical spells and effects by up to 26.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Shoulders', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+14 Strength<br>\
+14 Stamina<br>\
+8 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 20.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Breastplate', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Gauntlets', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+12 Strength<br>\
+13 Stamina<br>\
Classes: Paladin<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the Holy damage bonus of your Judgement of the Crusader by 10.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Leggings', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+18 Strength<br>\
+17 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Sabatons', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+12 Strength<br>\
+12 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.\
</span>\
<p>';
//Paladin end
classCounter++;
//priest begin
var raimentBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Increases the duration of your Psychic Scream spell by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Satin Mantle<br>\
Lieutenant Commander\'s Satin Hood<br>\
Knight-Captain\'s Satin Legguards<br>\
Knight-Captain\'s Satin Tunic<br>\
Knight-Lieutenant\'s Satin Walkers<br>\
Knight-Lieutenant\'s Satin Handwraps<br>\
</span>'+ raimentBlue, '<span class = "myYellow">\
Champion\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Satin Walkers<br>\
Blood Guard\'s Satin Handwraps<br>\
Legionnaire\'s Satin Tunic<br>\
Legionnaire\'s Satin Legguards<br>\
Champion\'s Satin Hood<br>\
Champion\'s Satin Mantle<br>\
</span>'+ raimentBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Hood', '<span class = "myBlue">\
Champion\'s Satin Hood'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
131 Armor<br>\
+20 Stamina<br>\
+18 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Mantle', '<span class = "myBlue">\
Champion\'s Satin Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
115 Armor<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 16.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Tunic', '<span class = "myBlue">\
Legionnaire\'s Satin Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Handwraps', '<span class = "myBlue">\
Blood Guard\'s Satin Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+5 Intellect<br>\
Classes: Priest<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Gives you a 50% chance to avoid interruption caused by damage while casting Mind Blast.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Legguards', '<span class = "myBlue">\
Legionnaire\'s Satin Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Walkers', '<span class = "myBlue">\
Blood Guard\'s Satin Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//priest end
classCounter++;
//rogue begin
var vestmentsBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Gouge ability by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Leather Helm<br>\
Lieutenant Commander\'s Leather Shoulders<br>\
Knight-Captain\'s Leather Legguards<br>\
Knight-Captain\'s Leather Chestpiece<br>\
Knight-Lieutenant\'s Leather Walkers<br>\
Knight-Lieutenant\'s Leather Grips<br>\
</span>'+ vestmentsBlue, '<span class = "myYellow">\
Champion\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Leather Walkers<br>\
Blood Guard\'s Leather Grips<br>\
Legionnaire\'s Leather Chestpiece<br>\
Legionnaire\'s Leather Legguards<br>\
Champion\'s Leather Helm<br>\
Champion\'s Leather Shoulders<br>\
</span>'+ vestmentsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Helm', '<span class = "myBlue">\
Champion\'s Leather Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
238 Armor<br>\
+23 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: +36 Attack Power.<br>\
Equip: Improves your chance to hit by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Shoulders', '<span class = "myBlue">\
Champion\'s Leather Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
196 Armor<br>\
+17 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: +22 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Leather Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
248 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Grips', '<span class = "myBlue">\
Blood Guard\'s Leather Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
155 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: +20 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Legguards', '<span class = "myBlue">\
Legionnaire\'s Leather Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
225 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Walkers', '<span class = "myBlue">\
Blood Guard\'s Leather Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
166 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the duration of your Sprint ability by 3 sec.<br>\
Equip: +28 Attack Power.\
</span>\
<p>';
//Rogue end
classCounter++;
//shaman begin
var earthshakerBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Improves your chance to get a critical strike with all Shock spells by 2%.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['', '<span class = "myYellow">\
Champion\'s Stormcaller (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Mail Greaves<br>\
Blood Guard\'s Mail Vices<br>\
Legionnaire\'s Mail Hauberk<br>\
Legionnaire\'s Mail Legguards<br>\
Champion\'s Mail Headguard<br>\
Champion\'s Mail Pauldrons<br>\
</span>'+ earthshakerBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+6 Strength<br>\
+24 Stamina<br>\
+16 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Pauldrons'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+5 Strength<br>\
+16 Stamina<br>\
+10 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+18 Intellect<br>\
Classes: Shaman<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+15 Stamina<br>\
+9 Intellect<br>\
Classes: Shaman<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 13.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
Classes: Shaman<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+13 Strength<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Shaman<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the speed of your Ghost Wolf ability by 15%.</span>\
<p>';
//Shaman end
classCounter++;
//warlock begin
var threadsBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the casting time of your Immolate spell by 0.2 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dreadweave Spaulders<br>\
Lieutenant Commander\'s Dreadweave Cowl<br>\
Knight-Captain\'s Dreadweave Legguards<br>\
Knight-Captain\'s Dreadweave Tunic<br>\
Knight-Lieutenant\'s Dreadweave Walkers<br>\
Knight-Lieutenant\'s Dreadweave Handwraps<br>\
</span>'+ threadsBlue, '<span class = "myYellow">\
Champion\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dreadweave Walkers<br>\
Blood Guard\'s Dreadweave Handwraps<br>\
Legionnaire\'s Dreadweave Tunic<br>\
Legionnaire\'s Dreadweave Legguards<br>\
Champion\'s Dreadweave Cowl<br>\
Champion\'s Dreadweave Spaulders<br>\
</span>'+ threadsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Cowl', '<span class = "myBlue">\
Champion\'s Dreadweave Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
81 Armor<br>\
+21 Stamina<br>\
+18 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Spaulders', '<span class = "myBlue">\
Champion\'s Dreadweave Spaulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
75 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 12.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Tunic', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
96 Armor<br>\
+20 Stamina<br>\
+20 Intellect<br>\
Classes: Warlock<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Handwraps', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
58 Armor<br>\
+14 Stamina<br>\
+4 Intellect<br>\
Classes: Warlock<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage dealt and health regained by your Death Coil spell by 8%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Legguards', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
84 Armor<br>\
+21 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 28.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Walkers', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
//Warlock end
classCounter++;
//warrior begin
var battlegearBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Intercept ability by 5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Plate Shoulders<br>\
Lieutenant Commander\'s Plate Helm<br>\
Knight-Captain\'s Plate Leggings<br>\
Knight-Captain\'s Plate Hauberk<br>\
Knight-Lieutenant\'s Plate Greaves<br>\
Knight-Lieutenant\'s Plate Gauntlets<br>\
</span>'+ battlegearBlue, '<span class = "myYellow">\
Champion\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Plate Greaves<br>\
Blood Guard\'s Plate Gauntlets<br>\
Legionnaire\'s Plate Hauberk<br>\
Legionnaire\'s Plate Leggings<br>\
Champion\'s Plate Helm<br>\
Champion\'s Plate Shoulders<br>\
</span>'+ battlegearBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Helm', '<span class = "myBlue">\
Champion\'s Plate Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+21 Strength<br>\
+24 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Shoulders', '<span class = "myBlue">\
Champion\'s Plate Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Hauberk', '<span class = "myBlue">\
Legionnaire\'s Plate Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+21 Strength<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Plate Gauntlets', '<span class = "myBlue">\
Blood Guard\'s Plate Gauntlets'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+17 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Hamstring Rage cost reduced by 3.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Leggings', '<span class = "myBlue">\
Legionnaire\'s Plate Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+12 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant Plate Greaves', '<span class = "myBlue">\
Blood Guard\'s Plate Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+10 Strength<br>\
+9 Agility<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//Warrior end
armorSetsArray[theArmorSetCounter] = armorSetPvPSuperior;
armorSetsValues[theArmorSetCounter] = "pvpsuperior";
theArmorSetCounter++;
| borgotech/Infinity_MaNGOS | sql/Tools & Optional/Websites/I_CSwowd/pvpmini/shared/wow-com/includes-client/armorsets/en/pvpsuperior.js | JavaScript | gpl-2.0 | 49,796 |
<?php
/**
* The Footer widget areas.
*
* @package Pilcrow
* @since Pilcrow 1.0
*/
?>
<?php
/* The footer widget area is triggered if any of the areas
* have widgets. So let's check that first.
*
* If none of the sidebars have widgets, then let's bail early.
*/
if ( ! is_active_sidebar( 'sidebar-4' )
&& ! is_active_sidebar( 'sidebar-5' )
)
return;
// If we get this far, we have widgets. Let's do this.
?>
<div id="footer-widget-area" role="complementary">
<?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?>
<div id="first" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-4' ); ?>
</ul>
</div><!-- #first .widget-area -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'sidebar-5' ) ) : ?>
<div id="second" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-5' ); ?>
</ul>
</div><!-- #second .widget-area -->
<?php endif; ?>
</div><!-- #footer-widget-area -->
| mearleycf/boltgun2 | wp-content/themes/pilcrow/sidebar-footer.php | PHP | gpl-2.0 | 1,009 |
var _ = require('../util')
var config = require('../config')
var Dep = require('./dep')
var arrayMethods = require('./array')
var arrayKeys = Object.getOwnPropertyNames(arrayMethods)
require('./object')
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*
* @param {Array|Object} value
* @constructor
*/
function Observer (value) {
this.value = value
this.active = true
this.deps = []
_.define(value, '__ob__', this)
if (_.isArray(value)) {
var augment = config.proto && _.hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
// Static methods
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*
* @param {*} value
* @param {Vue} [vm]
* @return {Observer|undefined}
* @static
*/
Observer.create = function (value, vm) {
var ob
if (
value &&
value.hasOwnProperty('__ob__') &&
value.__ob__ instanceof Observer
) {
ob = value.__ob__
} else if (
_.isObject(value) &&
!Object.isFrozen(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (ob && vm) {
ob.addVm(vm)
}
return ob
}
/**
* Set the target watcher that is currently being evaluated.
*
* @param {Watcher} watcher
*/
Observer.setTarget = function (watcher) {
Dep.target = watcher
}
// Instance methods
var p = Observer.prototype
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object. Properties prefixed with `$` or `_`
* and accessor properties are ignored.
*
* @param {Object} obj
*/
p.walk = function (obj) {
var keys = Object.keys(obj)
var i = keys.length
var key, prefix
while (i--) {
key = keys[i]
prefix = key.charCodeAt(0)
if (prefix !== 0x24 && prefix !== 0x5F) { // skip $ or _
this.convert(key, obj[key])
}
}
}
/**
* Try to carete an observer for a child value,
* and if value is array, link dep to the array.
*
* @param {*} val
* @return {Dep|undefined}
*/
p.observe = function (val) {
return Observer.create(val)
}
/**
* Observe a list of Array items.
*
* @param {Array} items
*/
p.observeArray = function (items) {
var i = items.length
while (i--) {
this.observe(items[i])
}
}
/**
* Convert a property into getter/setter so we can emit
* the events when the property is accessed/changed.
*
* @param {String} key
* @param {*} val
*/
p.convert = function (key, val) {
var ob = this
var childOb = ob.observe(val)
var dep = new Dep()
if (childOb) {
childOb.deps.push(dep)
}
Object.defineProperty(ob.value, key, {
enumerable: true,
configurable: true,
get: function () {
if (ob.active) {
dep.depend()
}
return val
},
set: function (newVal) {
if (newVal === val) return
// remove dep from old value
var oldChildOb = val && val.__ob__
if (oldChildOb) {
oldChildOb.deps.$remove(dep)
}
val = newVal
// add dep to new value
var newChildOb = ob.observe(newVal)
if (newChildOb) {
newChildOb.deps.push(dep)
}
dep.notify()
}
})
}
/**
* Notify change on all self deps on an observer.
* This is called when a mutable value mutates. e.g.
* when an Array's mutating methods are called, or an
* Object's $add/$delete are called.
*/
p.notify = function () {
var deps = this.deps
for (var i = 0, l = deps.length; i < l; i++) {
deps[i].notify()
}
}
/**
* Add an owner vm, so that when $add/$delete mutations
* happen we can notify owner vms to proxy the keys and
* digest the watchers. This is only called when the object
* is observed as an instance's root $data.
*
* @param {Vue} vm
*/
p.addVm = function (vm) {
(this.vms || (this.vms = [])).push(vm)
}
/**
* Remove an owner vm. This is called when the object is
* swapped out as an instance's $data object.
*
* @param {Vue} vm
*/
p.removeVm = function (vm) {
this.vms.$remove(vm)
}
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*
* @param {Object|Array} target
* @param {Object} proto
*/
function protoAugment (target, src) {
target.__proto__ = src
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* @param {Object|Array} target
* @param {Object} proto
*/
function copyAugment (target, src, keys) {
var i = keys.length
var key
while (i--) {
key = keys[i]
_.define(target, key, src[key])
}
}
module.exports = Observer
| jumpcakes/plunkett | wp-content/themes/genesis-sample/assets/js/bower_components/vue/src/observer/index.js | JavaScript | gpl-2.0 | 4,867 |
/*
Copyright (C) 2009 Roy R. Rankin
This file is part of the libgpsim library of gpsim
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see
<http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//
// p12f6xx
//
// This file supports:
// PIC12F629
// PIC12F675
// PIC12F683
//
//Note: unlike most other 12F processors these have 14bit instructions
#include <stdio.h>
#include <iostream>
#include <string>
#include "../config.h"
#include "symbol.h"
#include "stimuli.h"
#include "eeprom.h"
#include "p12f6xx.h"
#include "pic-ioports.h"
#include "packages.h"
//#define DEBUG
#if defined(DEBUG)
#include "../config.h"
#define Dprintf(arg) {printf("%s:%d ",__FILE__,__LINE__); printf arg; }
#else
#define Dprintf(arg) {}
#endif
//========================================================================
//
// Configuration Memory for the 12F6XX devices.
class Config12F6 : public ConfigWord
{
public:
Config12F6(P12F629 *pCpu)
: ConfigWord("CONFIG12F6", 0x3fff, "Configuration Word", pCpu, 0x2007)
{
Dprintf(("Config12F6::Config12F6 %p\n", m_pCpu));
if (m_pCpu)
{
m_pCpu->set_config_word(0x2007, 0x3fff);
}
}
};
// Does not match any of 3 versions in pir.h, pir.cc
// If required by any other porcessors should be moved there
//
class PIR1v12f : public PIR
{
public:
enum {
TMR1IF = 1 << 0,
TMR2IF = 1 << 1, //For 12F683
CMIF = 1 << 3,
ADIF = 1 << 6,
EEIF = 1 << 7
};
//------------------------------------------------------------------------
PIR1v12f(Processor *pCpu, const char *pName, const char *pDesc,INTCON *_intcon, PIE *_pie)
: PIR(pCpu,pName,pDesc,_intcon, _pie,0)
{
valid_bits = TMR1IF | CMIF | ADIF | EEIF;
writable_bits = TMR1IF | CMIF | ADIF | EEIF;
}
virtual void set_tmr1if()
{
put(get() | TMR1IF);
}
virtual void set_tmr2if()
{
put(get() | TMR2IF);
}
virtual void set_cmif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | CMIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
virtual void set_c1if()
{
set_cmif();
}
virtual void set_eeif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | EEIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
virtual void set_adif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | ADIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
};
//========================================================================
void P12F629::create_config_memory()
{
m_configMemory = new ConfigMemory(this,1);
m_configMemory->addConfigWord(0,new Config12F6(this));
};
class MCLRPinMonitor;
bool P12F629::set_config_word(unsigned int address,unsigned int cfg_word)
{
enum {
FOSC0 = 1<<0,
FOSC1 = 1<<1,
FOSC2 = 1<<2,
WDTEN = 1<<3,
PWRTEN = 1<<4,
MCLRE = 1<<5,
BOREN = 1<<6,
CP = 1<<7,
CPD = 1<<8,
BG0 = 1<<12,
BG1 = 1<<13
};
if(address == config_word_address())
{
if ((cfg_word & MCLRE) == MCLRE)
assignMCLRPin(4); // package pin 4
else
unassignMCLRPin();
wdt.initialize((cfg_word & WDTEN) == WDTEN);
if ((cfg_word & (FOSC2 | FOSC1 )) == 0x04) // internal RC OSC
osccal.set_freq(4e6);
return(_14bit_processor::set_config_word(address, cfg_word));
}
return false;
}
P12F629::P12F629(const char *_name, const char *desc)
: _14bit_processor(_name,desc),
intcon_reg(this,"intcon","Interrupt Control"),
comparator(this),
pie1(this,"PIE1", "Peripheral Interrupt Enable"),
t1con(this, "t1con", "TMR1 Control"),
tmr1l(this, "tmr1l", "TMR1 Low"),
tmr1h(this, "tmr1h", "TMR1 High"),
pcon(this, "pcon", "pcon"),
osccal(this, "osccal", "Oscillator Calibration Register", 0xfc)
{
m_ioc = new IOC(this, "ioc", "Interrupt-On-Change GPIO Register");
m_gpio = new PicPortGRegister(this,"gpio","", &intcon_reg, m_ioc,8,0x3f);
m_trisio = new PicTrisRegister(this,"trisio","", m_gpio, false);
m_wpu = new WPU(this, "wpu", "Weak Pull-up Register", m_gpio, 0x37);
pir1 = new PIR1v12f(this,"pir1","Peripheral Interrupt Register",&intcon_reg, &pie1);
tmr0.set_cpu(this, m_gpio, 4, option_reg);
tmr0.start(0);
if(config_modes)
config_modes->valid_bits = ConfigMode::CM_FOSC0 | ConfigMode::CM_FOSC1 |
ConfigMode::CM_FOSC1x | ConfigMode::CM_WDTE | ConfigMode::CM_PWRTE;
}
P12F629::~P12F629()
{
delete_file_registers(0x20, ram_top);
remove_sfr_register(&tmr0);
remove_sfr_register(&tmr1l);
remove_sfr_register(&tmr1h);
remove_sfr_register(&pcon);
remove_sfr_register(&t1con);
remove_sfr_register(&intcon_reg);
remove_sfr_register(&pie1);
remove_sfr_register(&comparator.cmcon);
remove_sfr_register(&comparator.vrcon);
remove_sfr_register(get_eeprom()->get_reg_eedata());
remove_sfr_register(get_eeprom()->get_reg_eeadr());
remove_sfr_register(get_eeprom()->get_reg_eecon1());
remove_sfr_register(get_eeprom()->get_reg_eecon2());
remove_sfr_register(&osccal);
delete_sfr_register(m_gpio);
delete_sfr_register(m_trisio);
delete_sfr_register(m_wpu);
delete_sfr_register(m_ioc);
delete_sfr_register(pir1);
delete e;
}
Processor * P12F629::construct(const char *name)
{
P12F629 *p = new P12F629(name);
p->create(0x5f, 128);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
void P12F629::create_symbols()
{
pic_processor::create_symbols();
addSymbol(Wreg);
}
void P12F629::create_sfr_map()
{
pir_set_def.set_pir1(pir1);
add_sfr_register(indf, 0x00);
alias_file_registers(0x00,0x00,0x80);
add_sfr_register(&tmr0, 0x01, RegisterValue(0xff,0));
add_sfr_register(option_reg, 0x81, RegisterValue(0xff,0));
add_sfr_register(pcl, 0x02, RegisterValue(0,0));
add_sfr_register(status, 0x03, RegisterValue(0x18,0));
add_sfr_register(fsr, 0x04);
alias_file_registers(0x02,0x04,0x80);
add_sfr_register(&tmr1l, 0x0e, RegisterValue(0,0),"tmr1l");
add_sfr_register(&tmr1h, 0x0f, RegisterValue(0,0),"tmr1h");
add_sfr_register(&pcon, 0x8e, RegisterValue(0,0),"pcon");
add_sfr_register(&t1con, 0x10, RegisterValue(0,0));
add_sfr_register(m_gpio, 0x05);
add_sfr_register(m_trisio, 0x85, RegisterValue(0x3f,0));
add_sfr_register(pclath, 0x0a, RegisterValue(0,0));
add_sfr_register(&intcon_reg, 0x0b, RegisterValue(0,0));
alias_file_registers(0x0a,0x0b,0x80);
intcon = &intcon_reg;
intcon_reg.set_pir_set(get_pir_set());
add_sfr_register(pir1, 0x0c, RegisterValue(0,0),"pir1");
tmr1l.tmrh = &tmr1h;
tmr1l.t1con = &t1con;
tmr1l.setInterruptSource(new InterruptSource(pir1, PIR1v1::TMR1IF));
tmr1h.tmrl = &tmr1l;
t1con.tmrl = &tmr1l;
tmr1l.setIOpin(&(*m_gpio)[5]);
tmr1l.setGatepin(&(*m_gpio)[4]);
add_sfr_register(&pie1, 0x8c, RegisterValue(0,0));
if (pir1) {
pir1->set_intcon(&intcon_reg);
pir1->set_pie(&pie1);
}
pie1.setPir(pir1);
// Link the comparator and voltage ref to porta
comparator.initialize(get_pir_set(), NULL,
&(*m_gpio)[0], &(*m_gpio)[1],
NULL, NULL,
&(*m_gpio)[2], NULL);
comparator.cmcon.set_configuration(1, 0, AN0, AN1, AN0, AN1, ZERO);
comparator.cmcon.set_configuration(1, 1, AN0, AN1, AN0, AN1, OUT0);
comparator.cmcon.set_configuration(1, 2, AN0, AN1, AN0, AN1, NO_OUT);
comparator.cmcon.set_configuration(1, 3, AN1, VREF, AN1, VREF, OUT0);
comparator.cmcon.set_configuration(1, 4, AN1, VREF, AN1, VREF, NO_OUT);
comparator.cmcon.set_configuration(1, 5, AN1, VREF, AN0, VREF, OUT0);
comparator.cmcon.set_configuration(1, 6, AN1, VREF, AN0, VREF, NO_OUT);
comparator.cmcon.set_configuration(1, 7, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 0, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 1, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 2, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 3, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 4, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 5, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 6, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 7, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
add_sfr_register(&comparator.cmcon, 0x19, RegisterValue(0,0),"cmcon");
add_sfr_register(&comparator.vrcon, 0x99, RegisterValue(0,0),"cvrcon");
add_sfr_register(get_eeprom()->get_reg_eedata(), 0x9a);
add_sfr_register(get_eeprom()->get_reg_eeadr(), 0x9b);
add_sfr_register(get_eeprom()->get_reg_eecon1(), 0x9c, RegisterValue(0,0));
add_sfr_register(get_eeprom()->get_reg_eecon2(), 0x9d);
add_sfr_register(m_wpu, 0x95, RegisterValue(0x37,0),"wpu");
add_sfr_register(m_ioc, 0x96, RegisterValue(0,0),"ioc");
add_sfr_register(&osccal, 0x90, RegisterValue(0x80,0));
}
//-------------------------------------------------------------------
void P12F629::set_out_of_range_pm(unsigned int address, unsigned int value)
{
if( (address>= 0x2100) && (address < 0x2100 + get_eeprom()->get_rom_size()))
get_eeprom()->change_rom(address - 0x2100, value);
}
void P12F629::create_iopin_map()
{
package = new Package(8);
if(!package)
return;
// Now Create the package and place the I/O pins
package->assign_pin( 7, m_gpio->addPin(new IO_bi_directional_pu("gpio0"),0));
package->assign_pin( 6, m_gpio->addPin(new IO_bi_directional_pu("gpio1"),1));
package->assign_pin( 5, m_gpio->addPin(new IO_bi_directional_pu("gpio2"),2));
package->assign_pin( 4, m_gpio->addPin(new IOPIN("gpio3"),3));
package->assign_pin( 3, m_gpio->addPin(new IO_bi_directional_pu("gpio4"),4));
package->assign_pin( 2, m_gpio->addPin(new IO_bi_directional_pu("gpio5"),5));
package->assign_pin( 1, 0);
package->assign_pin( 8, 0);
}
void P12F629::create(int _ram_top, int eeprom_size)
{
ram_top = _ram_top;
create_iopin_map();
_14bit_processor::create();
e = new EEPROM_PIR(this, pir1);
e->initialize(eeprom_size);
e->set_intcon(&intcon_reg);
set_eeprom(e);
add_file_registers(0x20, ram_top, 0x80);
P12F629::create_sfr_map();
}
//-------------------------------------------------------------------
void P12F629::enter_sleep()
{
tmr1l.sleep();
_14bit_processor::enter_sleep();
}
//-------------------------------------------------------------------
void P12F629::exit_sleep()
{
tmr1l.wake();
_14bit_processor::exit_sleep();
}
//-------------------------------------------------------------------
void P12F629::option_new_bits_6_7(unsigned int bits)
{
Dprintf(("P12F629::option_new_bits_6_7 bits=%x\n", bits));
m_gpio->setIntEdge ( (bits & OPTION_REG::BIT6) == OPTION_REG::BIT6);
m_wpu->set_wpu_pu ( (bits & OPTION_REG::BIT7) != OPTION_REG::BIT7);
}
//========================================================================
//
// Pic 16F675
//
Processor * P12F675::construct(const char *name)
{
P12F675 *p = new P12F675(name);
p->create(0x5f, 128);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
P12F675::P12F675(const char *_name, const char *desc)
: P12F629(_name,desc),
ansel(this,"ansel", "Analog Select"),
adcon0(this,"adcon0", "A2D Control 0"),
adcon1(this,"adcon1", "A2D Control 1"),
adresh(this,"adresh", "A2D Result High"),
adresl(this,"adresl", "A2D Result Low")
{
}
P12F675::~P12F675()
{
remove_sfr_register(&adresl);
remove_sfr_register(&adresh);
remove_sfr_register(&adcon0);
remove_sfr_register(&ansel);
}
void P12F675::create(int ram_top, int eeprom_size)
{
P12F629::create(ram_top, eeprom_size);
create_sfr_map();
}
void P12F675::create_sfr_map()
{
//
// adcon1 is not a register on the 12f675, but it is used internally
// to perform the ADC conversions
//
add_sfr_register(&adresl, 0x9e, RegisterValue(0,0));
add_sfr_register(&adresh, 0x1e, RegisterValue(0,0));
add_sfr_register(&adcon0, 0x1f, RegisterValue(0,0));
add_sfr_register(&ansel, 0x9f, RegisterValue(0x0f,0));
ansel.setAdcon1(&adcon1);
ansel.setAdcon0(&adcon0);
adcon0.setAdresLow(&adresl);
adcon0.setAdres(&adresh);
adcon0.setAdcon1(&adcon1);
adcon0.setIntcon(&intcon_reg);
adcon0.setA2DBits(10);
adcon0.setPir(pir1);
adcon0.setChannel_Mask(3);
adcon0.setChannel_shift(2);
adcon1.setNumberOfChannels(4);
adcon1.setIOPin(0, &(*m_gpio)[0]);
adcon1.setIOPin(1, &(*m_gpio)[1]);
adcon1.setIOPin(2, &(*m_gpio)[2]);
adcon1.setIOPin(3, &(*m_gpio)[4]);
adcon1.setVrefHiConfiguration(2, 1);
/* Channel Configuration done dynamiclly based on ansel */
adcon1.setValidCfgBits(ADCON1::VCFG0 | ADCON1::VCFG1 , 4);
}
//========================================================================
//
// Pic 16F683
//
Processor * P12F683::construct(const char *name)
{
P12F683 *p = new P12F683(name);
p->create(0x7f, 256);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
P12F683::P12F683(const char *_name, const char *desc)
: P12F675(_name,desc),
t2con(this, "t2con", "TMR2 Control"),
pr2(this, "pr2", "TMR2 Period Register"),
tmr2(this, "tmr2", "TMR2 Register"),
ccp1con(this, "ccp1con", "Capture Compare Control"),
ccpr1l(this, "ccpr1l", "Capture Compare 1 Low"),
ccpr1h(this, "ccpr1h", "Capture Compare 1 High"),
wdtcon(this, "wdtcon", "WDT Control", 0x1f),
osccon(this, "osccon", "OSC Control"),
osctune(this, "osctune", "OSC Tune")
{
internal_osc = false;
pir1->valid_bits |= PIR1v12f::TMR2IF;
pir1->writable_bits |= PIR1v12f::TMR2IF;
}
P12F683::~P12F683()
{
delete_file_registers(0x20, 0x7f);
delete_file_registers(0xa0, 0xbf);
remove_sfr_register(&tmr2);
remove_sfr_register(&t2con);
remove_sfr_register(&pr2);
remove_sfr_register(&ccpr1l);
remove_sfr_register(&ccpr1h);
remove_sfr_register(&ccp1con);
remove_sfr_register(&wdtcon);
remove_sfr_register(&osccon);
remove_sfr_register(&osctune);
remove_sfr_register(&comparator.cmcon1);
}
void P12F683::create(int _ram_top, int eeprom_size)
{
P12F629::create(0, eeprom_size);
add_file_registers(0x20, 0x6f, 0);
add_file_registers(0xa0, 0xbf, 0);
add_file_registers(0x70, 0x7f, 0x80);
create_sfr_map();
}
void P12F683::create_sfr_map()
{
P12F675::create_sfr_map();
add_sfr_register(&tmr2, 0x11, RegisterValue(0,0));
add_sfr_register(&t2con, 0x12, RegisterValue(0,0));
add_sfr_register(&pr2, 0x92, RegisterValue(0xff,0));
add_sfr_register(&ccpr1l, 0x13, RegisterValue(0,0));
add_sfr_register(&ccpr1h, 0x14, RegisterValue(0,0));
add_sfr_register(&ccp1con, 0x15, RegisterValue(0,0));
add_sfr_register(&wdtcon, 0x18, RegisterValue(0x08,0),"wdtcon");
add_sfr_register(&osccon, 0x8f, RegisterValue(0,0),"osccon");
remove_sfr_register(&osccal);
add_sfr_register(&osctune, 0x90, RegisterValue(0,0),"osctune");
osccon.set_osctune(&osctune);
osctune.set_osccon(&osccon);
t2con.tmr2 = &tmr2;
tmr2.pir_set = get_pir_set();
tmr2.pr2 = &pr2;
tmr2.t2con = &t2con;
tmr2.add_ccp ( &ccp1con );
pr2.tmr2 = &tmr2;
ccp1con.setCrosslinks(&ccpr1l, pir1, PIR1v1::CCP1IF, &tmr2);
ccp1con.setIOpin(&((*m_gpio)[2]));
ccpr1l.ccprh = &ccpr1h;
ccpr1l.tmrl = &tmr1l;
ccpr1h.ccprl = &ccpr1l;
comparator.cmcon.new_name("cmcon0");
comparator.cmcon.set_tmrl(&tmr1l);
comparator.cmcon1.set_tmrl(&tmr1l);
add_sfr_register(&comparator.cmcon1, 0x1a, RegisterValue(2,0),"cmcon1");
wdt.set_timeout(1./31000.);
}
| WellDone/gpsim | src/src/p12f6xx.cc | C++ | gpl-2.0 | 16,139 |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace Eccube\Controller;
use Eccube\Application;
use Eccube\Entity\BlocPosition;
class BlockController
{
public function index(Application $app)
{
$position = $app['request']->get('position');
$blocks = array();
if ($app['eccube.layout']) {
foreach ($app['eccube.layout']->getBlocPositions() as $blocPositions) {
if ($blocPositions->getTargetId() == constant("Eccube\Entity\BlocPosition::" . $position)) {
$blocks[] = $blocPositions->getBloc();
}
}
}
return $app['twig']->render('block.twig', array(
'blocks' => $blocks,
));
}
}
| ohtacky/ECCUBE3 | src/Eccube/Controller/BlockController.php | PHP | gpl-2.0 | 1,549 |
<?php
/**
* @file quiz.api.php
* Hooks provided by Quiz module.
*
* These entity types provided by Quiz also have entity API hooks. There are a
* few additional Quiz specific hooks defined in this file.
*
* quiz (settings for quiz nodes)
* quiz_result (quiz attempt/result)
* quiz_result_answer (answer to a specific question in a quiz result)
* quiz_question (generic settings for question nodes)
* quiz_question_relationship (relationship from quiz to question)
*
* So for example
*
* hook_quiz_result_presave($quiz_result)
* - Runs before a result is saved to the DB.
* hook_quiz_question_relationship_insert($quiz_question_relationship)
* - Runs when a new question is added to a quiz.
*
* You can also use Rules to build conditional actions based off of these
* events.
*
* Enjoy :)
*/
/**
* Implements hook_quiz_begin().
*
* Fired when a new quiz result is created.
*
* @deprecated
*
* Use hook_quiz_result_insert().
*/
function hook_quiz_begin($quiz, $result_id) {
}
/**
* Implements hook_quiz_finished().
*
* Fired after the last question is submitted.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_finished($quiz, $score, $data) {
}
/**
* Implements hook_quiz_scored().
*
* Fired when a quiz is evaluated.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_scored($quiz, $score, $result_id) {
}
/**
* Implements hook_quiz_question_info().
*
* Define a new question type. The question provider must extend QuizQuestion,
* and the response provider must extend QuizQuestionResponse. See those classes
* for additional implementation details.
*/
function hook_quiz_question_info() {
return array(
'long_answer' => array(
'name' => t('Example question type'),
'description' => t('An example question type that does something.'),
'question provider' => 'ExampleAnswerQuestion',
'response provider' => 'ExampleAnswerResponse',
'module' => 'quiz_question',
),
);
}
/**
* Expose a feedback option to Quiz so that Quiz administrators can choose when
* to show it to Quiz takers.
*
* @return array
* An array of feedback options keyed by machine name.
*/
function hook_quiz_feedback_options() {
return array(
'percentile' => t('Percentile'),
);
}
/**
* Allow modules to alter the quiz feedback options.
*
* @param array $review_options
* An array of review options keyed by a machine name.
*/
function hook_quiz_feedback_options_alter(&$review_options) {
// Change label.
$review_options['quiz_feedback'] = t('General feedback from the Quiz.');
// Disable showing correct answer.
unset($review_options['solution']);
}
/**
* Allow modules to define feedback times.
*
* Feedback times are configurable by Rules.
*
* @return array
* An array of feedback times keyed by machine name.
*/
function hook_quiz_feedback_times() {
return array(
'2_weeks_later' => t('Two weeks after finishing'),
);
}
/**
* Allow modules to alter the feedback times.
*
* @param array $feedback_times
*/
function hook_quiz_feedback_times_alter(&$feedback_times) {
// Change label.
$feedback_times['end'] = t('At the end of a quiz');
// Do not allow question feedback.
unset($feedback_times['question']);
}
/**
* Allow modules to alter the feedback labels.
*
* These are the labels that are displayed to the user, so instead of
* "Answer feedback" you may want to display something more learner-friendly.
*
* @param $feedback_labels
* An array keyed by the feedback option. Default keys are the keys from
* quiz_get_feedback_options().
*/
function hook_quiz_feedback_labels_alter(&$feedback_labels) {
$feedback_labels['solution'] = t('The answer you should have chosen.');
}
/**
* Implements hook_quiz_access().
*
* Control access to Quizzes.
*
* @see quiz_quiz_access() for default access implementations.
*
* Modules may implement Quiz access control hooks to block access to a Quiz or
* display a non-blocking message. Blockers are keyed by a blocker name, and
* must be an array keyed by 'success' and 'message'.
*/
function hook_quiz_access($op, $quiz, $account) {
if ($op == 'take') {
$today = date('l');
if ($today == 'Monday') {
return array(
'monday' => array(
'success' => FALSE,
'message' => t('You cannot take quizzes on Monday.'),
),
);
}
else {
return array(
'not_monday' => array(
'success' => TRUE,
'message' => t('It is not Monday so you may take quizzes.'),
),
);
}
}
}
/**
* Implements hook_quiz_access_alter().
*
* Alter the access blockers for a Quiz.
*
*/
function hook_quiz_access_alter(&$hooks, $op, $quiz, $account) {
if ($op == 'take') {
unset($hooks['monday']);
}
}
| bondjimbond/bcelnapps | sites/all/modules/quiz/quiz.api.php | PHP | gpl-2.0 | 4,847 |
--TEST--
Bug #67215 (php-cgi work with opcache, may be segmentation fault happen)
--INI--
opcache.enable=1
opcache.enable_cli=1
opcache.file_update_protection=0
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
file_put_contents($file_c, "<?php require \"$file_p\"; class c extends p {} ?>");
file_put_contents($file_p, '<?php class p { protected $var = ""; } ?>');
require $file_c;
$a = new c();
require $file_c;
?>
--CLEAN--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
unlink($file_c);
unlink($file_p);
?>
--EXPECTF--
Fatal error: Cannot redeclare class c in %sbug67215.c.php on line %d
| neonatura/crotalus | php/ext/opcache/tests/bug67215.phpt | PHP | gpl-2.0 | 721 |
// Example taken from http://bl.ocks.org/mbostock/3883245
jQuery( document ).ready(function() {
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 620 - margin.left - margin.right,
height = 330 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select(".core-commits-vizualization").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv(Drupal.settings.ppcc.data, function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
});
| DmitryDrozdik/ppdorg | docroot/sites/all/modules/custom/ppgetstat/ppcc/plugins/content_types/ppcc_visualization.js | JavaScript | gpl-2.0 | 1,739 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
* $Id$
*
*/
class CRM_Report_Form_Event_ParticipantListing extends CRM_Report_Form_Event {
protected $_summary = NULL;
protected $_contribField = FALSE;
protected $_lineitemField = FALSE;
protected $_groupFilter = TRUE;
protected $_tagFilter = TRUE;
protected $_balance = FALSE;
protected $activeCampaigns;
protected $_customGroupExtends = array(
'Participant',
'Contact',
'Individual',
'Event',
);
public $_drilldownReport = array('event/income' => 'Link to Detail Report');
/**
*/
/**
*/
public function __construct() {
$this->_autoIncludeIndexedFieldsAsOrderBys = 1;
// Check if CiviCampaign is a) enabled and b) has active campaigns
$config = CRM_Core_Config::singleton();
$campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
if ($campaignEnabled) {
$getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
$this->activeCampaigns = $getCampaigns['campaigns'];
asort($this->activeCampaigns);
}
$this->_columns = array(
'civicrm_contact' => array(
'dao' => 'CRM_Contact_DAO_Contact',
'fields' => array_merge(array(
// CRM-17115 - to avoid changing report output at this stage re-instate
// old field name for sort name
'sort_name_linked' => array(
'title' => ts('Participant Name'),
'required' => TRUE,
'no_repeat' => TRUE,
'dbAlias' => 'contact_civireport.sort_name',
)),
$this->getBasicContactFields(),
array(
'age_at_event' => array(
'title' => ts('Age at Event'),
'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, event_civireport.start_date)',
),
)
),
'grouping' => 'contact-fields',
'order_bys' => array(
'sort_name' => array(
'title' => ts('Last Name, First Name'),
'default' => '1',
'default_weight' => '0',
'default_order' => 'ASC',
),
'first_name' => array(
'name' => 'first_name',
'title' => ts('First Name'),
),
'gender_id' => array(
'name' => 'gender_id',
'title' => ts('Gender'),
),
'birth_date' => array(
'name' => 'birth_date',
'title' => ts('Birth Date'),
),
'age_at_event' => array(
'name' => 'age_at_event',
'title' => ts('Age at Event'),
),
'contact_type' => array(
'title' => ts('Contact Type'),
),
'contact_sub_type' => array(
'title' => ts('Contact Subtype'),
),
),
'filters' => array(
'sort_name' => array(
'title' => ts('Participant Name'),
'operator' => 'like',
),
'gender_id' => array(
'title' => ts('Gender'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
),
'birth_date' => array(
'title' => ts('Birth Date'),
'operatorType' => CRM_Report_Form::OP_DATE,
),
'contact_type' => array(
'title' => ts('Contact Type'),
),
'contact_sub_type' => array(
'title' => ts('Contact Subtype'),
),
),
),
'civicrm_email' => array(
'dao' => 'CRM_Core_DAO_Email',
'fields' => array(
'email' => array(
'title' => ts('Email'),
'no_repeat' => TRUE,
),
),
'grouping' => 'contact-fields',
'filters' => array(
'email' => array(
'title' => ts('Participant E-mail'),
'operator' => 'like',
),
),
),
'civicrm_address' => array(
'dao' => 'CRM_Core_DAO_Address',
'fields' => array(
'street_address' => NULL,
'city' => NULL,
'postal_code' => NULL,
'state_province_id' => array(
'title' => ts('State/Province'),
),
'country_id' => array(
'title' => ts('Country'),
),
),
'grouping' => 'contact-fields',
),
'civicrm_participant' => array(
'dao' => 'CRM_Event_DAO_Participant',
'fields' => array(
'participant_id' => array('title' => 'Participant ID'),
'participant_record' => array(
'name' => 'id',
'no_display' => TRUE,
'required' => TRUE,
),
'event_id' => array(
'default' => TRUE,
'type' => CRM_Utils_Type::T_STRING,
),
'status_id' => array(
'title' => ts('Status'),
'default' => TRUE,
),
'role_id' => array(
'title' => ts('Role'),
'default' => TRUE,
),
'fee_currency' => array(
'required' => TRUE,
'no_display' => TRUE,
),
'participant_fee_level' => NULL,
'participant_fee_amount' => NULL,
'participant_register_date' => array('title' => ts('Registration Date')),
'total_paid' => array(
'title' => ts('Total Paid'),
'dbAlias' => 'SUM(ft.total_amount)',
'type' => 1024,
),
'balance' => array(
'title' => ts('Balance'),
'dbAlias' => 'participant_civireport.fee_amount - SUM(ft.total_amount)',
'type' => 1024,
),
),
'grouping' => 'event-fields',
'filters' => array(
'event_id' => array(
'name' => 'event_id',
'title' => ts('Event'),
'operatorType' => CRM_Report_Form::OP_ENTITYREF,
'type' => CRM_Utils_Type::T_INT,
'attributes' => array(
'entity' => 'event',
'select' => array('minimumInputLength' => 0),
),
),
'sid' => array(
'name' => 'status_id',
'title' => ts('Participant Status'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'),
),
'rid' => array(
'name' => 'role_id',
'title' => ts('Participant Role'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Event_PseudoConstant::participantRole(),
),
'participant_register_date' => array(
'title' => 'Registration Date',
'operatorType' => CRM_Report_Form::OP_DATE,
),
'fee_currency' => array(
'title' => ts('Fee Currency'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
'default' => NULL,
'type' => CRM_Utils_Type::T_STRING,
),
),
'order_bys' => array(
'participant_register_date' => array(
'title' => ts('Registration Date'),
'default_weight' => '1',
'default_order' => 'ASC',
),
'event_id' => array(
'title' => ts('Event'),
'default_weight' => '1',
'default_order' => 'ASC',
),
),
),
'civicrm_phone' => array(
'dao' => 'CRM_Core_DAO_Phone',
'fields' => array(
'phone' => array(
'title' => ts('Phone'),
'default' => TRUE,
'no_repeat' => TRUE,
),
),
'grouping' => 'contact-fields',
),
'civicrm_event' => array(
'dao' => 'CRM_Event_DAO_Event',
'fields' => array(
'event_type_id' => array('title' => ts('Event Type')),
'event_start_date' => array('title' => ts('Event Start Date')),
),
'grouping' => 'event-fields',
'filters' => array(
'eid' => array(
'name' => 'event_type_id',
'title' => ts('Event Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('event_type'),
),
'event_start_date' => array(
'title' => ts('Event Start Date'),
'operatorType' => CRM_Report_Form::OP_DATE,
),
),
'order_bys' => array(
'event_type_id' => array(
'title' => ts('Event Type'),
'default_weight' => '2',
'default_order' => 'ASC',
),
'event_start_date' => array(
'title' => ts('Event Start Date'),
),
),
),
'civicrm_contribution' => array(
'dao' => 'CRM_Contribute_DAO_Contribution',
'fields' => array(
'contribution_id' => array(
'name' => 'id',
'no_display' => TRUE,
'required' => TRUE,
'csv_display' => TRUE,
'title' => ts('Contribution ID'),
),
'financial_type_id' => array('title' => ts('Financial Type')),
'receive_date' => array('title' => ts('Payment Date')),
'contribution_status_id' => array('title' => ts('Contribution Status')),
'payment_instrument_id' => array('title' => ts('Payment Type')),
'contribution_source' => array(
'name' => 'source',
'title' => ts('Contribution Source'),
),
'currency' => array(
'required' => TRUE,
'no_display' => TRUE,
),
'trxn_id' => NULL,
'fee_amount' => array('title' => ts('Transaction Fee')),
'net_amount' => NULL,
),
'grouping' => 'contrib-fields',
'filters' => array(
'receive_date' => array(
'title' => 'Payment Date',
'operatorType' => CRM_Report_Form::OP_DATE,
),
'financial_type_id' => array(
'title' => ts('Financial Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::financialType(),
),
'currency' => array(
'title' => ts('Contribution Currency'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
'default' => NULL,
'type' => CRM_Utils_Type::T_STRING,
),
'payment_instrument_id' => array(
'title' => ts('Payment Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::paymentInstrument(),
),
'contribution_status_id' => array(
'title' => ts('Contribution Status'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
'default' => NULL,
),
),
),
'civicrm_line_item' => array(
'dao' => 'CRM_Price_DAO_LineItem',
'grouping' => 'priceset-fields',
'filters' => array(
'price_field_value_id' => array(
'name' => 'price_field_value_id',
'title' => ts('Fee Level'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->getPriceLevels(),
),
),
),
);
$this->_options = array(
'blank_column_begin' => array(
'title' => ts('Blank column at the Begining'),
'type' => 'checkbox',
),
'blank_column_end' => array(
'title' => ts('Blank column at the End'),
'type' => 'select',
'options' => array(
'' => '-select-',
1 => ts('One'),
2 => ts('Two'),
3 => ts('Three'),
),
),
);
// CRM-17115 avoid duplication of sort_name - would be better to standardise name
// & behaviour across reports but trying for no change at this point.
$this->_columns['civicrm_contact']['fields']['sort_name']['no_display'] = TRUE;
// If we have active campaigns add those elements to both the fields and filters
if ($campaignEnabled && !empty($this->activeCampaigns)) {
$this->_columns['civicrm_participant']['fields']['campaign_id'] = array(
'title' => ts('Campaign'),
'default' => 'false',
);
$this->_columns['civicrm_participant']['filters']['campaign_id'] = array(
'title' => ts('Campaign'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->activeCampaigns,
);
$this->_columns['civicrm_participant']['order_bys']['campaign_id'] = array(
'title' => ts('Campaign'),
);
}
$this->_currencyColumn = 'civicrm_participant_fee_currency';
parent::__construct();
}
/**
* Searches database for priceset values.
*
* @return array
*/
public function getPriceLevels() {
$query = "
SELECT CONCAT(cv.label, ' (', ps.title, ')') label, cv.id
FROM civicrm_price_field_value cv
LEFT JOIN civicrm_price_field cf
ON cv.price_field_id = cf.id
LEFT JOIN civicrm_price_set_entity ce
ON ce.price_set_id = cf.price_set_id
LEFT JOIN civicrm_price_set ps
ON ce.price_set_id = ps.id
WHERE ce.entity_table = 'civicrm_event'
ORDER BY cv.label
";
$dao = CRM_Core_DAO::executeQuery($query);
$elements = array();
while ($dao->fetch()) {
$elements[$dao->id] = "$dao->label\n";
}
return $elements;
}
public function preProcess() {
parent::preProcess();
}
public function select() {
$select = array();
$this->_columnHeaders = array();
//add blank column at the Start
if (array_key_exists('options', $this->_params) &&
!empty($this->_params['options']['blank_column_begin'])
) {
$select[] = " '' as blankColumnBegin";
$this->_columnHeaders['blankColumnBegin']['title'] = '_ _ _ _';
}
foreach ($this->_columns as $tableName => $table) {
if ($tableName == 'civicrm_line_item') {
$this->_lineitemField = TRUE;
}
if (array_key_exists('fields', $table)) {
foreach ($table['fields'] as $fieldName => $field) {
if (!empty($field['required']) ||
!empty($this->_params['fields'][$fieldName])
) {
if ($tableName == 'civicrm_contribution') {
$this->_contribField = TRUE;
}
if ($fieldName == 'total_paid' || $fieldName == 'balance') {
$this->_balance = TRUE;
}
$alias = "{$tableName}_{$fieldName}";
$select[] = "{$field['dbAlias']} as $alias";
$this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
$this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = CRM_Utils_Array::value('no_display', $field);
$this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
$this->_selectAliases[] = $alias;
}
}
}
}
//add blank column at the end
$blankcols = CRM_Utils_Array::value('blank_column_end', $this->_params);
if ($blankcols) {
for ($i = 1; $i <= $blankcols; $i++) {
$select[] = " '' as blankColumnEnd_{$i}";
$this->_columnHeaders["blank_{$i}"]['title'] = "_ _ _ _";
}
}
$this->_select = "SELECT " . implode(', ', $select) . " ";
}
/**
* @param $fields
* @param $files
* @param $self
*
* @return array
*/
public static function formRule($fields, $files, $self) {
$errors = $grouping = array();
return $errors;
}
public function from() {
$this->_from = "
FROM civicrm_participant {$this->_aliases['civicrm_participant']}
LEFT JOIN civicrm_event {$this->_aliases['civicrm_event']}
ON ({$this->_aliases['civicrm_event']}.id = {$this->_aliases['civicrm_participant']}.event_id ) AND
{$this->_aliases['civicrm_event']}.is_template = 0
LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
ON ({$this->_aliases['civicrm_participant']}.contact_id = {$this->_aliases['civicrm_contact']}.id )
{$this->_aclFrom}
LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
{$this->_aliases['civicrm_address']}.is_primary = 1
LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
{$this->_aliases['civicrm_email']}.is_primary = 1)
LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
{$this->_aliases['civicrm_phone']}.is_primary = 1
";
if ($this->_contribField) {
$this->_from .= "
LEFT JOIN civicrm_participant_payment pp
ON ({$this->_aliases['civicrm_participant']}.id = pp.participant_id)
LEFT JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
ON (pp.contribution_id = {$this->_aliases['civicrm_contribution']}.id)
";
}
if ($this->_lineitemField) {
$this->_from .= "
LEFT JOIN civicrm_line_item line_item_civireport
ON line_item_civireport.entity_table = 'civicrm_participant' AND
line_item_civireport.entity_id = {$this->_aliases['civicrm_participant']}.id AND
line_item_civireport.qty > 0
";
}
if ($this->_balance) {
$this->_from .= "
LEFT JOIN civicrm_entity_financial_trxn eft
ON (eft.entity_id = {$this->_aliases['civicrm_contribution']}.id)
LEFT JOIN civicrm_financial_account fa
ON (fa.account_type_code = 'AR')
LEFT JOIN civicrm_financial_trxn ft
ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution') AND
(ft.to_financial_account_id != fa.id)
";
}
}
public function where() {
$clauses = array();
foreach ($this->_columns as $tableName => $table) {
if (array_key_exists('filters', $table)) {
foreach ($table['filters'] as $fieldName => $field) {
$clause = NULL;
if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
$relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
$from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
$to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
if ($relative || $from || $to) {
$clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
}
}
else {
$op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
if ($fieldName == 'rid') {
$value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
if (!empty($value)) {
$operator = '';
if ($op == 'notin') {
$operator = 'NOT';
}
$regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', $value) . "[[:cntrl:]]*";
$clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
}
$op = NULL;
}
if ($op) {
$clause = $this->whereClause($field,
$op,
CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
);
}
}
if (!empty($clause)) {
$clauses[] = $clause;
}
}
}
}
if (empty($clauses)) {
$this->_where = "WHERE {$this->_aliases['civicrm_participant']}.is_test = 0 ";
}
else {
$this->_where = "WHERE {$this->_aliases['civicrm_participant']}.is_test = 0 AND " .
implode(' AND ', $clauses);
}
if ($this->_aclWhere) {
$this->_where .= " AND {$this->_aclWhere} ";
}
}
public function groupBy() {
$this->_groupBy = "GROUP BY {$this->_aliases['civicrm_participant']}.id";
}
public function postProcess() {
// get ready with post process params
$this->beginPostProcess();
// get the acl clauses built before we assemble the query
$this->buildACLClause($this->_aliases['civicrm_contact']);
// build query
$sql = $this->buildQuery(TRUE);
// build array of result based on column headers. This method also allows
// modifying column headers before using it to build result set i.e $rows.
$rows = array();
$this->buildRows($sql, $rows);
// format result set.
$this->formatDisplay($rows);
// assign variables to templates
$this->doTemplateAssignment($rows);
// do print / pdf / instance stuff if needed
$this->endPostProcess($rows);
}
/**
* @param $rows
* @param $entryFound
* @param $row
* @param int $rowId
* @param $rowNum
* @param $types
*
* @return bool
*/
private function _initBasicRow(&$rows, &$entryFound, $row, $rowId, $rowNum, $types) {
if (!array_key_exists($rowId, $row)) {
return FALSE;
}
$value = $row[$rowId];
if ($value) {
$rows[$rowNum][$rowId] = $types[$value];
}
$entryFound = TRUE;
}
/**
* Alter display of rows.
*
* Iterate through the rows retrieved via SQL and make changes for display purposes,
* such as rendering contacts as links.
*
* @param array $rows
* Rows generated by SQL, with an array for each row.
*/
public function alterDisplay(&$rows) {
$entryFound = FALSE;
$eventType = CRM_Core_OptionGroup::values('event_type');
$financialTypes = CRM_Contribute_PseudoConstant::financialType();
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
$paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
foreach ($rows as $rowNum => $row) {
// make count columns point to detail report
// convert display name to links
if (array_key_exists('civicrm_participant_event_id', $row)) {
$eventId = $row['civicrm_participant_event_id'];
if ($eventId) {
$rows[$rowNum]['civicrm_participant_event_id'] = CRM_Event_PseudoConstant::event($eventId, FALSE);
$url = CRM_Report_Utils_Report::getNextUrl('event/income',
'reset=1&force=1&id_op=in&id_value=' . $eventId,
$this->_absoluteUrl, $this->_id, $this->_drilldownReport
);
$rows[$rowNum]['civicrm_participant_event_id_link'] = $url;
$rows[$rowNum]['civicrm_participant_event_id_hover'] = ts("View Event Income Details for this Event");
}
$entryFound = TRUE;
}
// handle event type id
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_event_event_type_id', $rowNum, $eventType);
// handle participant status id
if (array_key_exists('civicrm_participant_status_id', $row)) {
$statusId = $row['civicrm_participant_status_id'];
if ($statusId) {
$rows[$rowNum]['civicrm_participant_status_id'] = CRM_Event_PseudoConstant::participantStatus($statusId, FALSE, 'label');
}
$entryFound = TRUE;
}
// handle participant role id
if (array_key_exists('civicrm_participant_role_id', $row)) {
$roleId = $row['civicrm_participant_role_id'];
if ($roleId) {
$roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $roleId);
$roleId = array();
foreach ($roles as $role) {
$roleId[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE);
}
$rows[$rowNum]['civicrm_participant_role_id'] = implode(', ', $roleId);
}
$entryFound = TRUE;
}
// Handel value seperator in Fee Level
if (array_key_exists('civicrm_participant_participant_fee_level', $row)) {
$feeLevel = $row['civicrm_participant_participant_fee_level'];
if ($feeLevel) {
CRM_Event_BAO_Participant::fixEventLevel($feeLevel);
$rows[$rowNum]['civicrm_participant_participant_fee_level'] = $feeLevel;
}
$entryFound = TRUE;
}
// Convert display name to link
$displayName = CRM_Utils_Array::value('civicrm_contact_sort_name_linked', $row);
$cid = CRM_Utils_Array::value('civicrm_contact_id', $row);
$id = CRM_Utils_Array::value('civicrm_participant_participant_record', $row);
if ($displayName && $cid && $id) {
$url = CRM_Report_Utils_Report::getNextUrl('contact/detail',
"reset=1&force=1&id_op=eq&id_value=$cid",
$this->_absoluteUrl, $this->_id, $this->_drilldownReport
);
$viewUrl = CRM_Utils_System::url("civicrm/contact/view/participant",
"reset=1&id=$id&cid=$cid&action=view&context=participant"
);
$contactTitle = ts('View Contact Details');
$participantTitle = ts('View Participant Record');
$rows[$rowNum]['civicrm_contact_sort_name_linked'] = "<a title='$contactTitle' href=$url>$displayName</a>";
if ($this->_outputMode !== 'csv') {
$rows[$rowNum]['civicrm_contact_sort_name_linked'] .=
"<span style='float: right;'><a title='$participantTitle' href=$viewUrl>" .
ts('View') . "</a></span>";
}
$entryFound = TRUE;
}
// Handle country id
if (array_key_exists('civicrm_address_country_id', $row)) {
$countryId = $row['civicrm_address_country_id'];
if ($countryId) {
$rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($countryId, TRUE);
}
$entryFound = TRUE;
}
// Handle state/province id
if (array_key_exists('civicrm_address_state_province_id', $row)) {
$provinceId = $row['civicrm_address_state_province_id'];
if ($provinceId) {
$rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($provinceId, TRUE);
}
$entryFound = TRUE;
}
// Handle employer id
if (array_key_exists('civicrm_contact_employer_id', $row)) {
$employerId = $row['civicrm_contact_employer_id'];
if ($employerId) {
$rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId);
$url = CRM_Utils_System::url('civicrm/contact/view',
'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
$rows[$rowNum]['civicrm_contact_employer_id_link'] = $url;
$rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for this Contact.');
}
}
// Convert campaign_id to campaign title
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_participant_campaign_id', $rowNum, $this->activeCampaigns);
// handle contribution status
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_contribution_status_id', $rowNum, $contributionStatus);
// handle payment instrument
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_payment_instrument_id', $rowNum, $paymentInstruments);
// handle financial type
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_financial_type_id', $rowNum, $financialTypes);
$entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'event/participantListing', 'View Event Income Details') ? TRUE : $entryFound;
// display birthday in the configured custom format
if (array_key_exists('civicrm_contact_birth_date', $row)) {
$birthDate = $row['civicrm_contact_birth_date'];
if ($birthDate) {
$rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
}
$entryFound = TRUE;
}
// skip looking further in rows, if first row itself doesn't
// have the column we need
if (!$entryFound) {
break;
}
}
}
}
| glocalcoop/activist-network | wp-content/plugins/civicrm/civicrm/CRM/Report/Form/Event/ParticipantListing.php | PHP | gpl-2.0 | 30,656 |
<?php
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// REPORTE: Formato de salida de Solicitud de Pago
// ORGANISMO: MINISTERIO DEL PODER POPULAR PARA LA INFRAESTRUCTURA.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
session_start();
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
if(!array_key_exists("la_logusr",$_SESSION))
{
print "<script language=JavaScript>";
print "close();";
print "opener.document.form1.submit();";
print "</script>";
}
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_insert_seguridad($as_titulo)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_insert_seguridad
// Access: private
// Arguments: as_titulo // Título del reporte
// Description: función que guarda la seguridad de quien generó el reporte
// Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang
// Fecha Creación: 11/03/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $io_fun_cxp;
$ls_descripcion="Generó el Reporte ".$as_titulo;
$lb_valido=$io_fun_cxp->uf_load_seguridad_reporte("CXP","sigesp_cxp_p_solicitudpago.php",$ls_descripcion);
return $lb_valido;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_encabezado_pagina($as_titulo,$as_numsol,$ad_fecregsol,&$io_pdf)
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_encabezado_pagina
// Access: private
// Arguments: as_titulo // Título del Reporte
// as_numsol // numero de la solicitud
// ad_fecregsol // fecha de registro de la solicitud
// io_pdf // Instancia de objeto pdf
// Description: Función que imprime los encabezados por página
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 11/03/2007
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_encabezado=$io_pdf->openObject();
$io_pdf->saveState();
$io_pdf->setStrokeColor(0,0,0);
$io_pdf->line(20,40,590,40);
$io_pdf->line(480,655,480,700);
$io_pdf->line(480,677,590,677);
$io_pdf->Rectangle(105,655,485,45);
$io_pdf->addJpegFromFile('../../shared/imagebank/banner_minfra.jpg',20,708,570,50); // Agregar Banner.
$io_pdf->addJpegFromFile('../../shared/imagebank/'.$_SESSION["ls_logo"],20,655,$_SESSION["ls_width"],$_SESSION["ls_height"]); // Agregar Logo
$li_tm=$io_pdf->getTextWidth(11,$as_titulo);
$tm=285-($li_tm/2);
$io_pdf->addText($tm,673,12,$as_titulo); // Agregar el título
$io_pdf->addText(485,685,9,"<b>No.</b> ".$as_numsol); // Agregar el título
$io_pdf->addText(485,663,9,"<b>Fecha</b> ".$ad_fecregsol); // Agregar el título
$io_pdf->addText(540,770,7,date("d/m/Y")); // Agregar la Fecha
$io_pdf->addText(546,764,6,date("h:i a")); // Agregar la Hora
// cuadro inferior
$io_pdf->Rectangle(20,60,570,70);
$io_pdf->line(20,73,590,73);
$io_pdf->line(20,117,590,117);
$io_pdf->line(130,60,130,130);
$io_pdf->line(240,60,240,130);
$io_pdf->line(380,60,380,130);
$io_pdf->addText(40,122,7,"ELABORADO POR"); // Agregar el título
$io_pdf->addText(42,63,7,"FIRMA / SELLO"); // Agregar el título
$io_pdf->addText(157,122,7,"VERIFICADO POR"); // Agregar el título
$io_pdf->addText(145,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->addText(275,122,7,"AUTORIZADO POR"); // Agregar el título
$io_pdf->addText(257,63,7,"ADMINISTRACIÓN Y FINANZAS"); // Agregar el título
$io_pdf->addText(440,122,7,"CONTRALORIA INTERNA"); // Agregar el título
$io_pdf->addText(445,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->restoreState();
$io_pdf->closeObject();
$io_pdf->addObject($io_encabezado,'all');
}// end function uf_print_encabezado_pagina
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_cabecera($as_numsol,$as_codigo,$as_nombre,$as_denfuefin,$ad_fecemisol,$as_consol,$as_obssol,
$ai_monsol,$as_monto,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_cabecera
// Access: private
// Arguments: as_numsol // Numero de la Solicitud de Pago
// as_codigo // Codigo del Proveedor / Beneficiario
// as_nombre // Nombre del Proveedor / Beneficiario
// as_denfuefin // Denominacion de la fuente de financiamiento
// ad_fecemisol // Fecha de Emision de la Solicitud
// as_consol // Concepto de la Solicitud
// as_obssol // Observaciones de la Solicitud
// ai_monsol // Monto de la Solicitud
// as_monto // Monto de la Solicitud en letras
// io_pdf // Instancia de objeto pdf
// Description: función que imprime la cabecera
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 17/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$la_data[1]=array('titulo'=>'<b>Beneficiario</b>');
$la_data[2]=array('titulo'=>" ".$as_nombre);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b> Concepto: </b>'.$as_consol);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b>Monto en Letras: </b>'.$as_monto,);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$la_data[1]=array('titulo'=>'<b>'.$ls_titulo.'</b>','contenido'=>$ai_monsol,);
$la_columnas=array('titulo'=>'',
'contenido'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>400), // Justificación y ancho de la columna
'contenido'=>array('justification'=>'center','width'=>170))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
}// end function uf_print_cabecera
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_recepcion($la_data,$ai_totsubtot,$ai_tottot,$ai_totcar,$ai_totded,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle
// Access: private
// Arguments: la_data // arreglo de información
// ai_totsubtot // acumulado del subtotal
// ai_tottot // acumulado del total
// ai_totcar // acumulado de los cargos
// ai_totded // acumulado de las deducciones
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 20/05/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datatit[1]=array('numrecdoc'=>'<b>Factura</b>','fecemisol'=>'<b>Fecha</b>','subtotdoc'=>'<b>Monto</b>',
'moncardoc'=>'<b>Cargos</b>','mondeddoc'=>'<b>Deducciones</b>','montotdoc'=>'<b>Total</b>');
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol2'=>array(0.9,0.9,0.9), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'center','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'center','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatit,$la_columnas,'<b>RECEPCIONES DE DOCUMENTOS</b>',$la_config);
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'left','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('numrecdoc'=>'<b>Totales '.$ls_titulo.'</b>','subtotdoc'=>$ai_totsubtot,
'moncardoc'=>$ai_totcar,'mondeddoc'=>$ai_totded,'montotdoc'=>$ai_tottot);
$la_columnas=array('numrecdoc'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'right','width'=>200), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_spg($aa_data,$ai_totpre,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// ai_totpre // monto total de presupuesto
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle presupuestario
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/04/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_estmodest;
global $ls_tiporeporte;
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datasercon= array(array('estpro'=>"<b>".$ls_titcuentas."</b>",
'spg_cuenta'=>"<b>Cuenta</b>",
'denominacion'=>"<b>Denominación</b>",
'monto'=>"<b>Total ".$ls_titulo."</b>"));
$la_columna=array('estpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los titulos
'showLines'=>1, // Mostrar Lineas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Minimo de la tabla
'xOrientation'=>'center', // Orientacion de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness'=>0.5,
'cols'=>array('estpro'=>array('justification'=>'center','width'=>165),
'spg_cuenta'=>array('justification'=>'center','width'=>84),
'denominacion'=>array('justification'=>'center','width'=>236),
'monto'=>array('justification'=>'center','width'=>85))); // Justificacion y ancho de la columna
$io_pdf->ezTable($la_datasercon,$la_columna,'<b>DETALLE PRESUPUESTARIO</b>',$la_config);
unset($la_datasercon);
unset($la_columna);
unset($la_config);
$la_columnas=array('codestpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('codestpro'=>array('justification'=>'center','width'=>165), // Justificación y ancho de la columna
'spg_cuenta'=>array('justification'=>'center','width'=>84), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>236), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totpre'=>$ai_totpre);
$la_columnas=array('titulo'=>'','totpre'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>485), // Justificación y ancho de la columna
'totpre'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_scg($aa_data,$ai_totdeb,$ai_tothab,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// si_totdeb // total monto debe
// si_tothab // total monto haber
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle contable
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_data[1]=array('sc_cuenta'=>'<b>Cuenta</b>','denominacion'=>'<b>Denominacion</b>','mondeb'=>'<b>Debe</b>','monhab'=>'<b>Haber</b>');
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'center','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'center','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'<b>DETALLE CONTABLE</b>',$la_config);
unset($la_datatit);
unset($la_columnas);
unset($la_config);
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre lineas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totdeb'=>$ai_totdeb,'tothab'=>$ai_tothab);
$la_columnas=array('titulo'=>'','totdeb'=>'','tothab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>390), // Justificación y ancho de la columna
'totdeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'tothab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_total_bsf($ai_monsolaux,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: ai_monsolaux // Monto Auxiliar en Bs.F.
// io_pdf // Instancia de objeto pdf
// Description: Funcion que imprime el monto total de la solicitud en Bs.F.
// Creado Por: Ing. Luis Anibal Lang
// Fecha Creación: 26/09/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
$la_datatot[1]=array('titulo'=>'<b>Total Bs.F.</b>','monto'=>$ai_monsolaux);
$la_columnas=array('titulo'=>'<b>Factura</b>',
'monto'=>'<b>Total</b>');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>0, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>480), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_total_bsf
//-----------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------- Instancia de las clases ------------------------------------------------
require_once("../../shared/ezpdf/class.ezpdf.php");
require_once("../../shared/class_folder/class_funciones.php");
$io_funciones=new class_funciones();
require_once("../class_folder/class_funciones_cxp.php");
$io_fun_cxp=new class_funciones_cxp();
$ls_estmodest=$_SESSION["la_empresa"]["estmodest"];
//Instancio a la clase de conversión de numeros a letras.
include("../../shared/class_folder/class_numero_a_letra.php");
$numalet= new class_numero_a_letra();
//imprime numero con los valore por defecto
//cambia a minusculas
$numalet->setMayusculas(1);
//cambia a femenino
$numalet->setGenero(1);
//cambia moneda
$numalet->setMoneda("Bolivares");
//cambia prefijo
$numalet->setPrefijo("***");
//cambia sufijo
$numalet->setSufijo("***");
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
//---------------------------------------------------- Parámetros del encabezado -----------------------------------------------
$ls_titulo="<b>SOLICITUD DE ORDEN DE PAGO</b>";
//-------------------------------------------------- Parámetros para Filtar el Reporte -----------------------------------------
$ls_numsol=$io_fun_cxp->uf_obtenervalor_get("numsol","");
$ls_tiporeporte=$io_fun_cxp->uf_obtenervalor_get("tiporeporte",0);
global $ls_tiporeporte;
require_once("../../shared/ezpdf/class.ezpdf.php");
if($ls_tiporeporte==1)
{
require_once("sigesp_cxp_class_reportbsf.php");
$io_report=new sigesp_cxp_class_reportbsf();
}
else
{
require_once("sigesp_cxp_class_report.php");
$io_report=new sigesp_cxp_class_report();
}
//--------------------------------------------------------------------------------------------------------------------------------
$lb_valido=uf_insert_seguridad($ls_titulo); // Seguridad de Reporte
if($lb_valido)
{
$lb_valido=$io_report->uf_select_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido==false) // Existe algún error ó no hay registros
{
print("<script language=JavaScript>");
print(" alert('No hay nada que Reportar');");
print(" close();");
print("</script>");
}
else // Imprimimos el reporte
{
error_reporting(E_ALL);
set_time_limit(1800);
$io_pdf=new Cezpdf('LETTER','portrait'); // Instancia de la clase PDF
$io_pdf->selectFont('../../shared/ezpdf/fonts/Helvetica.afm'); // Seleccionamos el tipo de letra
$io_pdf->ezSetCmMargins(5,5,3.3,3); // Configuración de los margenes en centímetros
$io_pdf->ezStartPageNumbers(570,47,8,'','',1); // Insertar el número de página
$li_totrow=$io_report->DS->getRowCount("numsol");
for($li_i=1;$li_i<=$li_totrow;$li_i++)
{
$ls_numsol=$io_report->DS->data["numsol"][$li_i];
$ls_codpro=$io_report->DS->data["cod_pro"][$li_i];
$ls_cedbene=$io_report->DS->data["ced_bene"][$li_i];
$ls_denfuefin=$io_report->DS->data["denfuefin"][$li_i];
$ls_nombre=$io_report->DS->data["nombre"][$li_i];
$ld_fecemisol=$io_report->DS->data["fecemisol"][$li_i];
$ls_consol=$io_report->DS->data["consol"][$li_i];
$ls_obssol=$io_report->DS->data["obssol"][$li_i];
$li_monsol=$io_report->DS->data["monsol"][$li_i];
$numalet->setNumero($li_monsol);
$ls_monto= $numalet->letra();
$li_monsol=number_format($li_monsol,2,",",".");
$ld_fecemisol=$io_funciones->uf_convertirfecmostrar($ld_fecemisol);
if($ls_codpro!="----------")
{
$ls_codigo=$ls_codpro;
}
else
{
$ls_codigo=$ls_cedbene;
}
/* if($ls_tiporeporte==0)
{
$li_monsolaux=$io_report->DS->data["monsolaux"][$li_i];
$li_monsolaux=number_format($li_monsolaux,2,",",".");
}
*/ uf_print_encabezado_pagina($ls_titulo,$ls_numsol,$ld_fecemisol,&$io_pdf);
uf_print_cabecera($ls_numsol,$ls_codigo,$ls_nombre,$ls_denfuefin,$ld_fecemisol,$ls_consol,$ls_obssol,$li_monsol,$ls_monto,&$io_pdf);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
$io_report->ds_detalle->reset_ds();
$lb_valido=$io_report->uf_select_rec_doc_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowdet=$io_report->ds_detalle_rec->getRowCount("numrecdoc");
$la_data="";
$li_totsubtot=0;
$li_tottot=0;
$li_totcar=0;
$li_totded=0;
for($li_s=1;$li_s<=$li_totrowdet;$li_s++)
{
$ls_numrecdoc=trim($io_report->ds_detalle_rec->data["numrecdoc"][$li_s]);
$ld_fecemidoc=trim($io_report->ds_detalle_rec->data["fecemidoc"][$li_s]);
$ls_numdoccomspg=$io_report->ds_detalle_rec->data["numdoccomspg"][$li_s];
$li_mondeddoc=$io_report->ds_detalle_rec->data["mondeddoc"][$li_s];
$li_moncardoc=$io_report->ds_detalle_rec->data["moncardoc"][$li_s];
$li_montotdoc=$io_report->ds_detalle_rec->data["montotdoc"][$li_s];
$li_subtotdoc=($li_montotdoc-$li_moncardoc+$li_mondeddoc);
$li_totsubtot=$li_totsubtot + $li_subtotdoc;
$li_tottot=$li_tottot + $li_montotdoc;
$li_totcar=$li_totcar + $li_moncardoc;
$li_totded=$li_totded + $li_mondeddoc;
$ld_fecemidoc=$io_funciones->uf_convertirfecmostrar($ld_fecemidoc);
$li_mondeddoc=number_format($li_mondeddoc,2,",",".");
$li_moncardoc=number_format($li_moncardoc,2,",",".");
$li_montotdoc=number_format($li_montotdoc,2,",",".");
$li_subtotdoc=number_format($li_subtotdoc,2,",",".");
$la_data[$li_s]=array('numrecdoc'=>$ls_numrecdoc,'fecemisol'=>$ld_fecemidoc,'mondeddoc'=>$li_mondeddoc,
'moncardoc'=>$li_moncardoc,'montotdoc'=>$li_montotdoc,'subtotdoc'=>$li_subtotdoc);
}
$li_totsubtot=number_format($li_totsubtot,2,",",".");
$li_tottot=number_format($li_tottot,2,",",".");
$li_totcar=number_format($li_totcar,2,",",".");
$li_totded=number_format($li_totded,2,",",".");
uf_print_detalle_recepcion($la_data,$li_totsubtot,$li_tottot,$li_totcar,$li_totded,&$io_pdf);
unset($la_data);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_spg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowspg=$io_report->ds_detalle_spg->getRowCount("codestpro");
$la_data="";
$li_totpre=0;
for($li_s=1;$li_s<=$li_totrowspg;$li_s++)
{
$ls_codestpro = trim($io_report->ds_detalle_spg->data["codestpro"][$li_s]);
$ls_spgcuenta = trim($io_report->ds_detalle_spg->data["spg_cuenta"][$li_s]);
$ls_denominacion = $io_report->ds_detalle_spg->data["denominacion"][$li_s];
$li_monto = $io_report->ds_detalle_spg->data["monto"][$li_s];
$li_totpre = $li_totpre+$li_monto;
$li_monto=number_format($li_monto,2,",",".");
$io_fun_cxp->uf_formatoprogramatica($ls_codestpro,&$ls_programatica);
$la_data[$li_s]=array('codestpro'=>$ls_programatica,'spg_cuenta'=>$ls_spgcuenta,
'denominacion'=>$ls_denominacion,'monto'=>$li_monto);
}
$li_totpre=number_format($li_totpre,2,",",".");
uf_print_detalle_spg($la_data,$li_totpre,&$io_pdf);
unset($la_data);
}
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
////////////////////////// GRID DETALLE CONTABLE //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_scg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowscg=$io_report->ds_detalle_scg->getRowCount("sc_cuenta");
$la_data="";
$li_totdeb=0;
$li_tothab=0;
for($li_s=1;$li_s<=$li_totrowscg;$li_s++)
{
$ls_sccuenta=trim($io_report->ds_detalle_scg->data["sc_cuenta"][$li_s]);
$ls_debhab=trim($io_report->ds_detalle_scg->data["debhab"][$li_s]);
$ls_denominacion=trim($io_report->ds_detalle_scg->data["denominacion"][$li_s]);
$li_monto=$io_report->ds_detalle_scg->data["monto"][$li_s];
if($ls_debhab=="D")
{
$li_montodebe=$li_monto;
$li_montohab="";
$li_totdeb=$li_totdeb+$li_montodebe;
$li_montodebe=number_format($li_montodebe,2,",",".");
}
else
{
$li_montodebe="";
$li_montohab=$li_monto;
$li_tothab=$li_tothab+$li_montohab;
$li_montohab=number_format($li_montohab,2,",",".");
}
$la_data[$li_s]=array('sc_cuenta'=>$ls_sccuenta,'denominacion'=>$ls_denominacion,
'mondeb'=>$li_montodebe,'monhab'=>$li_montohab);
}
$li_totdeb=number_format($li_totdeb,2,",",".");
$li_tothab=number_format($li_tothab,2,",",".");
uf_print_detalle_scg($la_data,$li_totdeb,$li_tothab,&$io_pdf);
unset($la_data);
}
}
}
}
/* if($ls_tiporeporte==0)
{
uf_print_total_bsf($li_monsolaux,&$io_pdf);
}
*/ if($lb_valido) // Si no ocurrio ningún error
{
$io_pdf->ezStopPageNumbers(1,1); // Detenemos la impresión de los números de página
$io_pdf->ezStream(); // Mostramos el reporte
}
else // Si hubo algún error
{
print("<script language=JavaScript>");
print(" alert('Ocurrio un error al generar el reporte. Intente de Nuevo');");
print(" close();");
print("</script>");
}
}
?>
| ArrozAlba/huayra | cxp/reportes/sigesp_cxp_rfs_solicitudes_minfra.php | PHP | gpl-2.0 | 37,861 |
/*
This file is part of Warzone 2100.
Copyright (C) 2007 Giel van Schijndel
Copyright (C) 2007-2015 Warzone 2100 Project
Warzone 2100 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.
Warzone 2100 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
$Revision$
$Id$
$HeadURL$
*/
/** \file
* Functions to convert between different Unicode Transformation Formats (UTF for short)
*/
#include "utf.h"
#include <assert.h>
#include <stdlib.h>
#if defined(LIB_COMPILE)
# define ASSERT(expr, ...) (assert(expr))
# define debug(part, ...) ((void)0)
#else
# include "debug.h"
#endif
// Assert that non-starting octets are of the form 10xxxxxx
#define ASSERT_NON_START_OCTET(octet) \
assert((octet & 0xC0) == 0x80 && "invalid non-start UTF-8 octet")
// Assert that starting octets are either of the form 0xxxxxxx (ASCII) or 11xxxxxx
#define ASSERT_START_OCTECT(octet) \
assert((octet & 0x80) == 0x00 || (octet & 0xC0) == 0xC0 || !"invalid starting UTF-8 octet")
// Assert that hexadect (16bit sequence) 1 of UTF-16 surrogate pair sequences are of the form 110110XXXXXXXXXX
#define ASSERT_START_HEXADECT(hexadect) \
assert(((hexadect) & 0xD800) == 0xD800 && "invalid first UTF-16 hexadect")
// Assert that hexadect (16bit sequence) 2 of UTF-16 surrogate pair sequences are of the form 110111XXXXXXXXXX
#define ASSERT_FINAL_HEXADECT(hexadect) \
assert(((hexadect) & 0xDC00) == 0xDC00 && "invalid first UTF-16 hexadect")
utf_32_char UTF8DecodeChar(const char *utf8_char, const char **next_char)
{
utf_32_char decoded = '\0';
*next_char = utf8_char;
ASSERT_START_OCTECT(*utf8_char);
// first octect: 0xxxxxxx: 7 bit (ASCII)
if ((*utf8_char & 0x80) == 0x00)
{
// 1 byte long encoding
decoded = *((*next_char)++);
}
// first octect: 110xxxxx: 11 bit
else if ((*utf8_char & 0xe0) == 0xc0)
{
// 2 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
decoded = (*((*next_char)++) & 0x1f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
// first octect: 1110xxxx: 16 bit
else if ((*utf8_char & 0xf0) == 0xe0)
{
// 3 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
ASSERT_NON_START_OCTET(utf8_char[2]);
decoded = (*((*next_char)++) & 0x0f) << 12;
decoded |= (*((*next_char)++) & 0x3f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
// first octect: 11110xxx: 21 bit
else if ((*utf8_char & 0xf8) == 0xf0)
{
// 4 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
ASSERT_NON_START_OCTET(utf8_char[2]);
ASSERT_NON_START_OCTET(utf8_char[3]);
decoded = (*((*next_char)++) & 0x07) << 18;
decoded |= (*((*next_char)++) & 0x3f) << 12;
decoded |= (*((*next_char)++) & 0x3f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
else
{
// apparently this character uses more than 21 bit
// this decoder is not developed to cope with those
// characters so error out
ASSERT(!"out-of-range UTF-8 character", "this UTF-8 character is too large (> 21bits) for this UTF-8 decoder and too large to be a valid Unicode codepoint");
}
return decoded;
}
size_t UTF8CharacterCount(const char *utf8_string)
{
size_t length = 0;
while (*utf8_string != '\0')
{
UTF8DecodeChar(utf8_string, &utf8_string);
++length;
}
return length;
}
size_t UTF16CharacterCount(const uint16_t *utf16)
{
size_t length = 0;
while (*utf16)
{
UTF16DecodeChar(utf16, &utf16);
++length;
}
return length;
}
static size_t unicode_utf8_char_length(const utf_32_char unicode_char)
{
// an ASCII character, which uses 7 bit at most, which is one byte in UTF-8
if (unicode_char < 0x00000080)
{
return 1; // stores 7 bits
}
else if (unicode_char < 0x00000800)
{
return 2; // stores 11 bits
}
else if (unicode_char < 0x00010000)
{
return 3; // stores 16 bits
}
/* This encoder can deal with < 0x00200000, but Unicode only ranges
* from 0x0 to 0x10FFFF. Thus we don't accept anything else.
*/
else if (unicode_char < 0x00110000)
{
return 4; // stores 21 bits
}
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, so don't accept it.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
// Dummy value to prevent warnings about missing return from function
return 0;
}
char *UTF8CharacterAtOffset(const char *utf8_string, size_t index)
{
while (*utf8_string != '\0'
&& index != 0)
{
// Move to the next character
UTF8DecodeChar(utf8_string, &utf8_string);
--index;
}
if (*utf8_string == '\0')
{
return NULL;
}
return (char *)utf8_string;
}
/** Encodes a single Unicode character to a UTF-8 encoded string.
*
* \param unicode_char A UTF-32 encoded Unicode codepoint that will be encoded
* into UTF-8. This should be a valid Unicode codepoint
* (i.e. ranging from 0x0 to 0x10FFFF inclusive).
* \param out_char Points to the position in a buffer where the UTF-8
* encoded character can be stored.
*
* \return A pointer pointing to the first byte <em>after</em> the encoded
* UTF-8 sequence. This can be used as the \c out_char parameter for a
* next invocation of encode_utf8_char().
*/
static char *encode_utf8_char(const utf_32_char unicode_char, char *out_char)
{
char *next_char = out_char;
// 7 bits
if (unicode_char < 0x00000080)
{
*(next_char++) = unicode_char;
}
// 11 bits
else if (unicode_char < 0x00000800)
{
// 0xc0 provides the counting bits: 110
// then append the 5 most significant bits
*(next_char++) = 0xc0 | (unicode_char >> 6);
// Put the next 6 bits in a byte of their own
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
// 16 bits
else if (unicode_char < 0x00010000)
{
// 0xe0 provides the counting bits: 1110
// then append the 4 most significant bits
*(next_char++) = 0xe0 | (unicode_char >> 12);
// Put the next 12 bits in two bytes of their own
*(next_char++) = 0x80 | ((unicode_char >> 6) & 0x3f);
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
// 21 bits
/* This encoder can deal with < 0x00200000, but Unicode only ranges
* from 0x0 to 0x10FFFF. Thus we don't accept anything else.
*/
else if (unicode_char < 0x00110000)
{
// 0xf0 provides the counting bits: 11110
// then append the 3 most significant bits
*(next_char++) = 0xf0 | (unicode_char >> 18);
// Put the next 18 bits in three bytes of their own
*(next_char++) = 0x80 | ((unicode_char >> 12) & 0x3f);
*(next_char++) = 0x80 | ((unicode_char >> 6) & 0x3f);
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, so don't accept it.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
}
return next_char;
}
utf_32_char UTF16DecodeChar(const utf_16_char *utf16_char, const utf_16_char **next_char)
{
utf_32_char decoded;
*next_char = utf16_char;
// Are we dealing with a surrogate pair
if (*utf16_char >= 0xD800
&& *utf16_char <= 0xDFFF)
{
ASSERT_START_HEXADECT(utf16_char[0]);
ASSERT_FINAL_HEXADECT(utf16_char[1]);
decoded = (*((*next_char)++) & 0x3ff) << 10;
decoded |= *((*next_char)++) & 0x3ff;
decoded += 0x10000;
}
// Not a surrogate pair, so it's a valid Unicode codepoint right away
else
{
decoded = *((*next_char)++);
}
return decoded;
}
/** Encodes a single Unicode character to a UTF-16 encoded string.
*
* \param unicode_char A UTF-32 encoded Unicode codepoint that will be encoded
* into UTF-16. This should be a valid Unicode codepoint
* (i.e. ranging from 0x0 to 0x10FFFF inclusive).
* \param out_char Points to the position in a buffer where the UTF-16
* encoded character can be stored.
*
* \return A pointer pointing to the first byte <em>after</em> the encoded
* UTF-16 sequence. This can be used as the \c out_char parameter for a
* next invocation of encode_utf16_char().
*/
static utf_16_char *encode_utf16_char(const utf_32_char unicode_char, utf_16_char *out_char)
{
utf_16_char *next_char = out_char;
// 16 bits
if (unicode_char < 0x10000)
{
*(next_char++) = unicode_char;
}
else if (unicode_char < 0x110000)
{
const utf_16_char v = unicode_char - 0x10000;
*(next_char++) = 0xD800 | (v >> 10);
*(next_char++) = 0xDC00 | (v & 0x3ff);
ASSERT_START_HEXADECT(out_char[0]);
ASSERT_FINAL_HEXADECT(out_char[1]);
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, and UTF-16 cannot cope with that, so error
* out.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
}
return next_char;
}
static size_t utf16_utf8_buffer_length(const utf_16_char *unicode_string)
{
const utf_16_char *curChar = unicode_string;
// Determine length of string (in octets) when encoded in UTF-8
size_t length = 0;
while (*curChar)
{
length += unicode_utf8_char_length(UTF16DecodeChar(curChar, &curChar));
}
return length;
}
char *UTF16toUTF8(const utf_16_char *unicode_string, size_t *nbytes)
{
const utf_16_char *curChar;
const size_t utf8_length = utf16_utf8_buffer_length(unicode_string);
// Allocate memory to hold the UTF-8 encoded string (plus a terminating nul char)
char *utf8_string = (char *)malloc(utf8_length + 1);
char *curOutPos = utf8_string;
if (utf8_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
curChar = unicode_string;
while (*curChar)
{
curOutPos = encode_utf8_char(UTF16DecodeChar(curChar, &curChar), curOutPos);
}
// Terminate the string with a nul character
utf8_string[utf8_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = utf8_length + 1;
}
return utf8_string;
}
static size_t utf8_as_utf16_buf_size(const char *utf8_string)
{
const char *curChar = utf8_string;
size_t length = 0;
while (*curChar != '\0')
{
const utf_32_char unicode_char = UTF8DecodeChar(curChar, &curChar);
if (unicode_char < 0x10000)
{
length += 1;
}
else if (unicode_char < 0x110000)
{
length += 2;
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, and UTF-16 cannot cope with that, so error
* out.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint too large (%u > 0x10FFFF) for the UTF-16 encoding", (unsigned int)unicode_char);
}
}
return length;
}
utf_16_char *UTF8toUTF16(const char *utf8_string, size_t *nbytes)
{
const char *curChar = utf8_string;
const size_t unicode_length = utf8_as_utf16_buf_size(utf8_string);
// Allocate memory to hold the UTF-16 encoded string (plus a terminating nul)
utf_16_char *unicode_string = (utf_16_char *)malloc(sizeof(utf_16_char) * (unicode_length + 1));
utf_16_char *curOutPos = unicode_string;
if (unicode_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
while (*curChar != '\0')
{
curOutPos = encode_utf16_char(UTF8DecodeChar(curChar, &curChar), curOutPos);
}
// Terminate the string with a nul
unicode_string[unicode_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = sizeof(utf_16_char) * (unicode_length + 1);
}
return unicode_string;
}
utf_16_char *UTF16CharacterAtOffset(const utf_16_char *utf16_string, size_t index)
{
while (*utf16_string != '\0'
&& index != 0)
{
// Move to the next character
UTF16DecodeChar(utf16_string, &utf16_string);
--index;
}
if (*utf16_string == '\0')
{
return NULL;
}
return (utf_16_char *)utf16_string;
}
static size_t utf32_utf8_buffer_length(const utf_32_char *unicode_string)
{
const utf_32_char *curChar;
// Determine length of string (in octets) when encoded in UTF-8
size_t length = 0;
for (curChar = unicode_string; *curChar != '\0'; ++curChar)
{
length += unicode_utf8_char_length(*curChar);
}
return length;
}
char *UTF32toUTF8(const utf_32_char *unicode_string, size_t *nbytes)
{
const utf_32_char *curChar;
const size_t utf8_length = utf32_utf8_buffer_length(unicode_string);
// Allocate memory to hold the UTF-8 encoded string (plus a terminating nul char)
char *utf8_string = (char *)malloc(utf8_length + 1);
char *curOutPos = utf8_string;
if (utf8_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
for (curChar = unicode_string; *curChar != 0; ++curChar)
{
curOutPos = encode_utf8_char(*curChar, curOutPos);
}
// Terminate the string with a nul character
utf8_string[utf8_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = utf8_length + 1;
}
return utf8_string;
}
utf_32_char *UTF8toUTF32(const char *utf8_string, size_t *nbytes)
{
const char *curChar = utf8_string;
const size_t unicode_length = UTF8CharacterCount(utf8_string);
// Allocate memory to hold the UTF-32 encoded string (plus a terminating nul)
utf_32_char *unicode_string = (utf_32_char *)malloc(sizeof(utf_32_char) * (unicode_length + 1));
utf_32_char *curOutPos = unicode_string;
if (unicode_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
while (*curChar != '\0')
{
*(curOutPos++) = UTF8DecodeChar(curChar, &curChar);
}
// Terminate the string with a nul
unicode_string[unicode_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = sizeof(utf_32_char) * (unicode_length + 1);
}
return unicode_string;
}
| skiz/warzone2100 | lib/framework/utf.cpp | C++ | gpl-2.0 | 14,247 |
--TEST--
Bug #66141 (mysqlnd quote function is wrong with NO_BACKSLASH_ESCAPES after failed query)
--SKIPIF--
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'skipif.inc');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mysql_pdo_test.inc');
MySQLPDOTest::skip();
?>
--FILE--
<?php
include __DIR__ . DIRECTORY_SEPARATOR . 'mysql_pdo_test.inc';
$db = MySQLPDOTest::factory();
$input = 'Something\', 1 as one, 2 as two FROM dual; -- f';
$quotedInput0 = $db->quote($input);
$db->query('set session sql_mode="NO_BACKSLASH_ESCAPES"');
// injection text from some user input
$quotedInput1 = $db->quote($input);
$db->query('something that throws an exception');
$quotedInput2 = $db->quote($input);
var_dump($quotedInput0);
var_dump($quotedInput1);
var_dump($quotedInput2);
?>
done
--EXPECTF--
Warning: PDO::query(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your %s server version for the right syntax to use near 'something that throws an exception' at line %d in %s on line %d
string(50) "'Something\', 1 as one, 2 as two FROM dual; -- f'"
string(50) "'Something'', 1 as one, 2 as two FROM dual; -- f'"
string(50) "'Something'', 1 as one, 2 as two FROM dual; -- f'"
done | neonatura/crotalus | php/ext/pdo_mysql/tests/bug66141.phpt | PHP | gpl-2.0 | 1,288 |
// PR c++/39866
// { dg-options "-std=c++0x" }
struct A {
A& operator=(const A&) = delete; // { dg-bogus "" }
void operator=(int) {} // { dg-message "" }
void operator=(char) {} // { dg-message "" }
};
struct B {};
int main()
{
A a;
a = B(); // { dg-error "no match" }
a = 1.0; // { dg-error "ambiguous" }
}
| ccompiler4pic32/pic32-gcc | gcc/testsuite/g++.dg/cpp0x/defaulted14.C | C++ | gpl-2.0 | 326 |
/**
* \file InsetMathFontOld.cpp
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* \author André Pönitz
*
* Full author contact details are available in file CREDITS.
*/
#include <config.h>
#include "InsetMathFontOld.h"
#include "MathData.h"
#include "MathParser.h"
#include "MathStream.h"
#include "MathSupport.h"
#include "MetricsInfo.h"
#include "support/gettext.h"
#include "support/lstrings.h"
#include <ostream>
using namespace lyx::support;
namespace lyx {
InsetMathFontOld::InsetMathFontOld(Buffer * buf, latexkeys const * key)
: InsetMathNest(buf, 1), key_(key), current_mode_(TEXT_MODE)
{
//lock(true);
}
Inset * InsetMathFontOld::clone() const
{
return new InsetMathFontOld(*this);
}
void InsetMathFontOld::metrics(MetricsInfo & mi, Dimension & dim) const
{
current_mode_ = isTextFont(from_ascii(mi.base.fontname))
? TEXT_MODE : MATH_MODE;
docstring const font = current_mode_ == MATH_MODE
? "math" + key_->name : "text" + key_->name;
// When \cal is used in text mode, the font is not changed
bool really_change_font = font != "textcal";
FontSetChanger dummy(mi.base, font, really_change_font);
cell(0).metrics(mi, dim);
metricsMarkers(dim);
}
void InsetMathFontOld::draw(PainterInfo & pi, int x, int y) const
{
current_mode_ = isTextFont(from_ascii(pi.base.fontname))
? TEXT_MODE : MATH_MODE;
docstring const font = current_mode_ == MATH_MODE
? "math" + key_->name : "text" + key_->name;
// When \cal is used in text mode, the font is not changed
bool really_change_font = font != "textcal";
FontSetChanger dummy(pi.base, font, really_change_font);
cell(0).draw(pi, x + 1, y);
drawMarkers(pi, x, y);
}
void InsetMathFontOld::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
{
cell(0).metricsT(mi, dim);
}
void InsetMathFontOld::drawT(TextPainter & pain, int x, int y) const
{
cell(0).drawT(pain, x, y);
}
void InsetMathFontOld::write(WriteStream & os) const
{
os << "{\\" << key_->name << ' ' << cell(0) << '}';
}
void InsetMathFontOld::normalize(NormalStream & os) const
{
os << "[font " << key_->name << ' ' << cell(0) << ']';
}
void InsetMathFontOld::infoize(odocstream & os) const
{
os << bformat(_("Font: %1$s"), key_->name);
}
} // namespace lyx
| xavierm02/lyx-mathpartir | src/mathed/InsetMathFontOld.cpp | C++ | gpl-2.0 | 2,314 |
<?php return array('dependencies' => array(), 'version' => 'a8dca9f7d5fd098db5af94613d2a8ec0'); | tstephen/srp-digital | wp-content/plugins/jetpack/_inc/build/shortcodes/js/recipes.min.asset.php | PHP | gpl-2.0 | 95 |
using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using CmsData;
using CmsWeb.Models;
using UtilityExtensions;
using Query = CmsData.Query;
namespace CmsWeb.Areas.Search.Models
{
public class SavedQueryModel : PagedTableModel<Query, SavedQueryInfo>
{
public bool admin { get; set; }
public bool OnlyMine { get; set; }
public bool PublicOnly { get; set; }
public string SearchQuery { get; set; }
public bool ScratchPadsOnly { get; set; }
public bool StatusFlagsOnly { get; set; }
public SavedQueryModel() : base("Last Run", "desc", true)
{
admin = Roles.IsUserInRole("Admin");
}
public override IQueryable<Query> DefineModelList()
{
var q = from c in DbUtil.Db.Queries
where !PublicOnly || c.Ispublic
where c.Name.Contains(SearchQuery) || c.Owner == SearchQuery || !SearchQuery.HasValue()
select c;
if (ScratchPadsOnly)
q = from c in q
where c.Name == Util.ScratchPad2
select c;
else
q = from c in q
where c.Name != Util.ScratchPad2
select c;
if (StatusFlagsOnly)
q = from c in q
where StatusFlagsOnly == false || SqlMethods.Like(c.Name, "F[0-9][0-9]%")
select c;
DbUtil.Db.SetUserPreference("SavedQueryOnlyMine", OnlyMine);
if (OnlyMine)
q = from c in q
where c.Owner == Util.UserName
select c;
else if (!admin)
q = from c in q
where c.Owner == Util.UserName || c.Ispublic
select c;
return q;
}
public override IQueryable<Query> DefineModelSort(IQueryable<Query> q)
{
switch (SortExpression)
{
case "Public":
return from c in q
orderby c.Ispublic, c.Owner, c.Name
select c;
case "Description":
return from c in q
orderby c.Name
select c;
case "Last Run":
return from c in q
orderby c.LastRun ?? c.Created
select c;
case "Owner":
return from c in q
orderby c.Owner, c.Name
select c;
case "Count":
return from c in q
orderby c.RunCount, c.Name
select c;
case "Public desc":
return from c in q
orderby c.Ispublic descending, c.Owner, c.Name
select c;
case "Description desc":
return from c in q
orderby c.Name descending
select c;
case "Last Run desc":
return from c in q
let dt = c.LastRun ?? c.Created
orderby dt descending
select c;
case "Owner desc":
return from c in q
orderby c.Owner descending, c.Name
select c;
case "Count desc":
return from c in q
orderby c.RunCount descending, c.Name
select c;
}
return q;
}
public override IEnumerable<SavedQueryInfo> DefineViewList(IQueryable<Query> q)
{
var user = Util.UserName;
return from c in q
select new SavedQueryInfo
{
QueryId = c.QueryId,
Name = c.Name,
Ispublic = c.Ispublic,
LastRun = c.LastRun ?? c.Created,
Owner = c.Owner,
CanDelete = admin || c.Owner == user,
RunCount = c.RunCount,
};
}
}
} | RGray1959/MyParish | CmsWeb/Areas/Search/Models/SavedQuery/SavedQueryModel.cs | C# | gpl-2.0 | 4,459 |
import sys
if __name__ == "__main__":
if len(sys.argv) < 2:
print "need input file"
sys.exit(1)
fin = open(sys.argv[1], "r")
lines = fin.readlines()
fin.close()
fout = open("bootloader.h", "w")
fout.write("/* File automatically generated by hex2header.py */\n\n")
fout.write("const unsigned int bootloader_data[] = {");
mem = {}
eAddr = 0
addr = 0
for line in lines:
line = line.strip()
if line[0] != ":":
continue
lType = int(line[7:9], 16)
lAddr = int(line[3:7], 16)
dLen = int(line[1:3], 16)
if lType == 2:
eAddr = int(line[9:13], 16) << 8;
continue
if lType == 4:
eAddr = int(line[9:13], 16) << 16;
continue
if lType == 1:
break
if lType == 0:
idx = 0
data = line[9:-2]
dataLen = len(data)
#print "data = ", data
for idx in range(dataLen / 4):
word = int(data[idx*4:(idx*4)+2], 16)
word |= int(data[(idx*4)+2:(idx*4)+4], 16) << 8;
addr = (lAddr + eAddr + idx*2) >> 1
#print hex(addr), "=", hex(word)
mem[addr] = word
output = []
for addr in range(0x800, 0xfff):
if mem.has_key(addr):
output.append(mem[addr])
else:
output.append(0xffff)
output.reverse()
idx = 0
for word in output:
if word != 0xffff:
break
output = output[1:]
output.reverse()
left = len(output) % 8
if left != 0:
output += [0xffff] * (8-left)
while (idx < len(output)):
fout.write("\n ")
for i in range(8):
fout.write("0x%04x, " % output[idx])
idx += 1
fout.write("\n};\n");
fout.close()
| diydrones/alceosd | firmware/bootloader_updater.X/hex2header.py | Python | gpl-2.0 | 1,513 |
/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information
** to ensure GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
****************************************************************************/
#include "qfontengine_p.h"
#include "qtextengine_p.h"
#include <qglobal.h>
#include "qt_windows.h"
#include <private/qapplication_p.h>
#include <qlibrary.h>
#include <qpaintdevice.h>
#include <qpainter.h>
#include <qlibrary.h>
#include <limits.h>
#include <qendian.h>
#include <qmath.h>
#include <qthreadstorage.h>
#include <private/qunicodetables_p.h>
#include <qbitmap.h>
#include <private/qpainter_p.h>
#include <private/qpdf_p.h>
#include "qpaintengine.h"
#include "qvarlengtharray.h"
#include <private/qpaintengine_raster_p.h>
#if defined(Q_OS_WINCE)
#include "qguifunctions_wince.h"
#endif
//### mingw needed define
#ifndef TT_PRIM_CSPLINE
#define TT_PRIM_CSPLINE 3
#endif
#ifdef MAKE_TAG
#undef MAKE_TAG
#endif
// GetFontData expects the tags in little endian ;(
#define MAKE_TAG(ch1, ch2, ch3, ch4) (\
(((quint32)(ch4)) << 24) | \
(((quint32)(ch3)) << 16) | \
(((quint32)(ch2)) << 8) | \
((quint32)(ch1)) \
)
typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT);
// common DC for all fonts
QT_BEGIN_NAMESPACE
class QtHDC
{
HDC _hdc;
public:
QtHDC()
{
HDC displayDC = GetDC(0);
_hdc = CreateCompatibleDC(displayDC);
ReleaseDC(0, displayDC);
}
~QtHDC()
{
if (_hdc)
DeleteDC(_hdc);
}
HDC hdc() const
{
return _hdc;
}
};
#ifndef QT_NO_THREAD
Q_GLOBAL_STATIC(QThreadStorage<QtHDC *>, local_shared_dc)
HDC shared_dc()
{
QtHDC *&hdc = local_shared_dc()->localData();
if (!hdc)
hdc = new QtHDC;
return hdc->hdc();
}
#else
HDC shared_dc()
{
return 0;
}
#endif
static HFONT stock_sysfont = 0;
static PtrGetCharWidthI ptrGetCharWidthI = 0;
static bool resolvedGetCharWidthI = false;
static void resolveGetCharWidthI()
{
if (resolvedGetCharWidthI)
return;
resolvedGetCharWidthI = true;
ptrGetCharWidthI = (PtrGetCharWidthI)QLibrary::resolve(QLatin1String("gdi32"), "GetCharWidthI");
}
// Copy a LOGFONTW struct into a LOGFONTA by converting the face name to an 8 bit value.
// This is needed when calling CreateFontIndirect on non-unicode windowses.
inline static void wa_copy_logfont(LOGFONTW *lfw, LOGFONTA *lfa)
{
lfa->lfHeight = lfw->lfHeight;
lfa->lfWidth = lfw->lfWidth;
lfa->lfEscapement = lfw->lfEscapement;
lfa->lfOrientation = lfw->lfOrientation;
lfa->lfWeight = lfw->lfWeight;
lfa->lfItalic = lfw->lfItalic;
lfa->lfUnderline = lfw->lfUnderline;
lfa->lfCharSet = lfw->lfCharSet;
lfa->lfOutPrecision = lfw->lfOutPrecision;
lfa->lfClipPrecision = lfw->lfClipPrecision;
lfa->lfQuality = lfw->lfQuality;
lfa->lfPitchAndFamily = lfw->lfPitchAndFamily;
QString fam = QString::fromUtf16((const ushort*)lfw->lfFaceName);
memcpy(lfa->lfFaceName, fam.toLocal8Bit().constData(), fam.length() + 1);
}
// defined in qtextengine_win.cpp
typedef void *SCRIPT_CACHE;
typedef HRESULT (WINAPI *fScriptFreeCache)(SCRIPT_CACHE *);
extern fScriptFreeCache ScriptFreeCache;
static inline quint32 getUInt(unsigned char *p)
{
quint32 val;
val = *p++ << 24;
val |= *p++ << 16;
val |= *p++ << 8;
val |= *p;
return val;
}
static inline quint16 getUShort(unsigned char *p)
{
quint16 val;
val = *p++ << 8;
val |= *p;
return val;
}
static inline HFONT systemFont()
{
if (stock_sysfont == 0)
stock_sysfont = (HFONT)GetStockObject(SYSTEM_FONT);
return stock_sysfont;
}
// general font engine
QFixed QFontEngineWin::lineThickness() const
{
if(lineWidth > 0)
return lineWidth;
return QFontEngine::lineThickness();
}
#if defined(Q_OS_WINCE)
static OUTLINETEXTMETRICW *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsW(hdc, 0, 0);
OUTLINETEXTMETRICW *otm = (OUTLINETEXTMETRICW *)malloc(size);
GetOutlineTextMetricsW(hdc, size, otm);
return otm;
}
#else
static OUTLINETEXTMETRICA *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsA(hdc, 0, 0);
OUTLINETEXTMETRICA *otm = (OUTLINETEXTMETRICA *)malloc(size);
GetOutlineTextMetricsA(hdc, size, otm);
return otm;
}
#endif
void QFontEngineWin::getCMap()
{
QT_WA({
ttf = (bool)(tm.w.tmPitchAndFamily & TMPF_TRUETYPE);
} , {
ttf = (bool)(tm.a.tmPitchAndFamily & TMPF_TRUETYPE);
});
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
bool symb = false;
if (ttf) {
cmapTable = getSfntTable(qbswap<quint32>(MAKE_TAG('c', 'm', 'a', 'p')));
int size = 0;
cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()),
cmapTable.size(), &symb, &size);
}
if (!cmap) {
ttf = false;
symb = false;
}
symbol = symb;
designToDevice = 1;
_faceId.index = 0;
if(cmap) {
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
designToDevice = QFixed((int)otm->otmEMSquare)/int(otm->otmTextMetrics.tmHeight);
unitsPerEm = otm->otmEMSquare;
x_height = (int)otm->otmsXHeight;
loadKerningPairs(designToDevice);
_faceId.filename = (char *)otm + (int)otm->otmpFullName;
lineWidth = otm->otmsUnderscoreSize;
fsType = otm->otmfsType;
free(otm);
} else {
unitsPerEm = tm.w.tmHeight;
}
}
inline unsigned int getChar(const QChar *str, int &i, const int len)
{
unsigned int uc = str[i].unicode();
if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
uint low = str[i+1].unicode();
if (low >= 0xdc00 && low < 0xe000) {
uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
++i;
}
}
return uc;
}
int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs, bool mirrored) const
{
QGlyphLayout *g = glyphs;
if (mirrored) {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, QChar::mirroredChar(uc));
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint ucs = QChar::mirroredChar(getChar(str, i, numChars));
if (ucs >= first && ucs <= last)
glyphs->glyph = ucs;
else
glyphs->glyph = 0;
glyphs++;
}
}
} else {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint uc = getChar(str, i, numChars);
if (uc >= first && uc <= last)
glyphs->glyph = uc;
else
glyphs->glyph = 0;
glyphs++;
}
}
}
return glyphs - g;
}
QFontEngineWin::QFontEngineWin(const QString &name, HFONT _hfont, bool stockFont, LOGFONT lf)
{
//qDebug("regular windows font engine created: font='%s', size=%d", name, lf.lfHeight);
_name = name;
cmap = 0;
hfont = _hfont;
logfont = lf;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
this->stockFont = stockFont;
fontDef.pixelSize = -lf.lfHeight;
lbearing = SHRT_MIN;
rbearing = SHRT_MIN;
synthesized_flags = -1;
lineWidth = -1;
x_height = -1;
BOOL res;
QT_WA({
res = GetTextMetricsW(hdc, &tm.w);
} , {
res = GetTextMetricsA(hdc, &tm.a);
});
fontDef.fixedPitch = !(tm.w.tmPitchAndFamily & TMPF_FIXED_PITCH);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
cache_cost = tm.w.tmHeight * tm.w.tmAveCharWidth * 2000;
getCMap();
useTextOutA = false;
#ifndef Q_OS_WINCE
// TextOutW doesn't work for symbol fonts on Windows 95!
// since we're using glyph indices we don't care for ttfs about this!
if (QSysInfo::WindowsVersion == QSysInfo::WV_95 && !ttf &&
(_name == QLatin1String("Marlett") || _name == QLatin1String("Symbol") ||
_name == QLatin1String("Webdings") || _name == QLatin1String("Wingdings")))
useTextOutA = true;
#endif
widthCache = 0;
widthCacheSize = 0;
designAdvances = 0;
designAdvancesSize = 0;
if (!resolvedGetCharWidthI)
resolveGetCharWidthI();
}
QFontEngineWin::~QFontEngineWin()
{
if (designAdvances)
free(designAdvances);
if (widthCache)
free(widthCache);
// make sure we aren't by accident still selected
SelectObject(shared_dc(), systemFont());
if (!stockFont) {
if (!DeleteObject(hfont))
qErrnoWarning("QFontEngineWin: failed to delete non-stock font...");
}
}
HGDIOBJ QFontEngineWin::selectDesignFont(QFixed *overhang) const
{
LOGFONT f = logfont;
f.lfHeight = unitsPerEm;
HFONT designFont;
QT_WA({
designFont = CreateFontIndirectW(&f);
}, {
LOGFONTA fa;
wa_copy_logfont(&f, &fa);
designFont = CreateFontIndirectA(&fa);
});
HGDIOBJ oldFont = SelectObject(shared_dc(), designFont);
if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) {
BOOL res;
QT_WA({
TEXTMETRICW tm;
res = GetTextMetricsW(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
} , {
TEXTMETRICA tm;
res = GetTextMetricsA(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
});
} else {
*overhang = 0;
}
return oldFont;
}
bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
{
if (*nglyphs < len) {
*nglyphs = len;
return false;
}
*nglyphs = getGlyphIndexes(str, len, glyphs, flags & QTextEngine::RightToLeft);
if (flags & QTextEngine::GlyphIndicesOnly)
return true;
#if defined(Q_OS_WINCE)
HDC hdc = shared_dc();
if (flags & QTextEngine::DesignMetrics) {
HGDIOBJ oldFont = 0;
QFixed overhang = 0;
int glyph_pos = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)(str+i), surrogate ? 2 : 1, &size);
designAdvances[glyph] = QFixed((int)size.cx)/designToDevice;
}
glyphs[glyph_pos].advance.x = designAdvances[glyph];
glyphs[glyph_pos].advance.y = 0;
if (surrogate)
++i;
++glyph_pos;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
int glyph_pos = 0;
HGDIOBJ oldFont = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
glyphs[glyph_pos].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[glyph_pos].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[glyph_pos].advance.x == 0) {
SIZE size = {0, 0};
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
GetTextExtentPoint32W(hdc, (wchar_t *)str + i, surrogate ? 2 : 1, &size);
size.cx -= overhang;
glyphs[glyph_pos].advance.x = size.cx;
// if glyph's within cache range, store it for later
if (size.cx > 0 && size.cx < 0x100)
widthCache[glyph] = size.cx;
}
if (surrogate)
++i;
++glyph_pos;
}
if (oldFont)
SelectObject(hdc, oldFont);
}
#else
recalcAdvances(*nglyphs, glyphs, flags);
#endif
return true;
}
void QFontEngineWin::recalcAdvances(int len, QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
{
HGDIOBJ oldFont = 0;
HDC hdc = shared_dc();
if (ttf && (flags & QTextEngine::DesignMetrics)) {
QFixed overhang = 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
if (ptrGetCharWidthI) {
int width = 0;
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
designAdvances[glyph] = QFixed(width) / designToDevice;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
designAdvances[glyph] = QFixed(gm.gmCellIncX) / designToDevice;
}
#endif
}
}
glyphs[i].advance.x = designAdvances[glyph];
glyphs[i].advance.y = 0;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
glyphs[i].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[i].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[i].advance.x == 0) {
int width = 0;
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
if (!ttf) {
QChar ch[2] = { ushort(glyph), 0 };
int chrLen = 1;
if (glyph > 0xffff) {
ch[0] = QChar::highSurrogate(glyph);
ch[1] = QChar::lowSurrogate(glyph);
++chrLen;
}
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)ch, chrLen, &size);
width = size.cx;
} else if (ptrGetCharWidthI) {
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
width -= overhang;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
width = gm.gmCellIncX;
}
#endif
}
glyphs[i].advance.x = width;
// if glyph's within cache range, store it for later
if (width > 0 && width < 0x100)
widthCache[glyph] = width;
}
}
if (oldFont)
SelectObject(hdc, oldFont);
}
}
glyph_metrics_t QFontEngineWin::boundingBox(const QGlyphLayout *glyphs, int numGlyphs)
{
if (numGlyphs == 0)
return glyph_metrics_t();
QFixed w = 0;
const QGlyphLayout *end = glyphs + numGlyphs;
while(end > glyphs) {
--end;
w += end->effectiveAdvance();
}
return glyph_metrics_t(0, -tm.w.tmAscent, w, tm.w.tmHeight, w, 0);
}
#ifndef Q_OS_WINCE
typedef HRESULT (WINAPI *pGetCharABCWidthsFloat)(HDC, UINT, UINT, LPABCFLOAT);
static pGetCharABCWidthsFloat qt_GetCharABCWidthsFloat = 0;
#endif
glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph)
{
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if(!ttf) {
SIZE s = {0, 0};
WCHAR ch = glyph;
int width;
int overhang = 0;
static bool resolved = false;
if (!resolved) {
QLibrary lib(QLatin1String("gdi32"));
qt_GetCharABCWidthsFloat = (pGetCharABCWidthsFloat) lib.resolve("GetCharABCWidthsFloatW");
resolved = true;
}
if (QT_WA_INLINE(true, false) && qt_GetCharABCWidthsFloat) {
ABCFLOAT abc;
qt_GetCharABCWidthsFloat(hdc, ch, ch, &abc);
width = qRound(abc.abcfB);
} else {
GetTextExtentPoint32W(hdc, &ch, 1, &s);
overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
width = s.cx;
}
return glyph_metrics_t(0, -tm.a.tmAscent, width, tm.a.tmHeight, width-overhang, 0);
} else {
DWORD res = 0;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR)
return glyph_metrics_t(gm.gmptGlyphOrigin.x, -gm.gmptGlyphOrigin.y,
(int)gm.gmBlackBoxX, (int)gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY);
}
return glyph_metrics_t();
#else
SIZE s = {0, 0};
WCHAR ch = glyph;
HDC hdc = shared_dc();
BOOL res = GetTextExtentPoint32W(hdc, &ch, 1, &s);
Q_UNUSED(res);
return glyph_metrics_t(0, -tm.a.tmAscent, s.cx, tm.a.tmHeight, s.cx, 0);
#endif
}
QFixed QFontEngineWin::ascent() const
{
return tm.w.tmAscent;
}
QFixed QFontEngineWin::descent() const
{
return tm.w.tmDescent;
}
QFixed QFontEngineWin::leading() const
{
return tm.w.tmExternalLeading;
}
QFixed QFontEngineWin::xHeight() const
{
if(x_height >= 0)
return x_height;
return QFontEngine::xHeight();
}
QFixed QFontEngineWin::averageCharWidth() const
{
return tm.w.tmAveCharWidth;
}
qreal QFontEngineWin::maxCharWidth() const
{
return tm.w.tmMaxCharWidth;
}
enum { max_font_count = 256 };
static const ushort char_table[] = {
40,
67,
70,
75,
86,
88,
89,
91,
102,
114,
124,
127,
205,
645,
884,
922,
1070,
12386,
0
};
static const int char_table_entries = sizeof(char_table)/sizeof(ushort);
qreal QFontEngineWin::minLeftBearing() const
{
if (lbearing == SHRT_MIN)
minRightBearing(); // calculates both
return lbearing;
}
qreal QFontEngineWin::minRightBearing() const
{
#ifdef Q_OS_WINCE
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABC[char_table_entries+1];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
ml = 0;
mr = -tm.a.tmOverhang;
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#else
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
QT_WA({
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
}, {
GetCharABCWidthsA(hdc,tm.a.tmFirstChar,tm.a.tmLastChar,abc);
});
} else {
abc = new ABC[char_table_entries+1];
QT_WA({
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
}, {
for(int i = 0; i < char_table_entries; i++) {
QByteArray w = QString(QChar(char_table[i])).toLocal8Bit();
if (w.length() == 1) {
uint ch8 = (uchar)w[0];
GetCharABCWidthsA(hdc, ch8, ch8, abc+i);
}
}
});
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
QT_WA({
ABCFLOAT *abc = 0;
int n = tm.w.tmLastChar - tm.w.tmFirstChar+1;
if (n <= max_font_count) {
abc = new ABCFLOAT[n];
GetCharABCWidthsFloat(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABCFLOAT[char_table_entries];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
float fml = abc[0].abcfA;
float fmr = abc[0].abcfC;
for (int i=1; i<n; i++) {
if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) {
fml = qMin(fml,abc[i].abcfA);
fmr = qMin(fmr,abc[i].abcfC);
}
}
ml = int(fml-0.9999);
mr = int(fmr-0.9999);
delete [] abc;
} , {
ml = 0;
mr = -tm.a.tmOverhang;
});
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#endif
}
const char *QFontEngineWin::name() const
{
return 0;
}
bool QFontEngineWin::canRender(const QChar *string, int len)
{
if (symbol) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0) {
if (uc < 0x100) {
if (getTrueTypeGlyphIndex(cmap, uc + 0xf000) == 0)
return false;
} else {
return false;
}
}
}
} else if (ttf) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0)
return false;
}
} else {
QT_WA({
while(len--) {
if (tm.w.tmFirstChar > string->unicode() || tm.w.tmLastChar < string->unicode())
return false;
}
}, {
while(len--) {
if (tm.a.tmFirstChar > string->unicode() || tm.a.tmLastChar < string->unicode())
return false;
}
});
}
return true;
}
QFontEngine::Type QFontEngineWin::type() const
{
return QFontEngine::Win;
}
static inline double qt_fixed_to_double(const FIXED &p) {
return ((p.value << 16) + p.fract) / 65536.0;
}
static inline QPointF qt_to_qpointf(const POINTFX &pt, qreal scale) {
return QPointF(qt_fixed_to_double(pt.x) * scale, -qt_fixed_to_double(pt.y) * scale);
}
#ifndef GGO_UNHINTED
#define GGO_UNHINTED 0x0100
#endif
static void addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc,
QPainterPath *path, bool ttf, glyph_metrics_t *metric = 0, qreal scale = 1)
{
#if defined(Q_OS_WINCE)
Q_UNUSED(glyph);
Q_UNUSED(hdc);
#endif
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
uint glyphFormat = GGO_NATIVE;
if (ttf)
glyphFormat |= GGO_GLYPH_INDEX;
GLYPHMETRICS gMetric;
memset(&gMetric, 0, sizeof(GLYPHMETRICS));
int bufferSize = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
bufferSize = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
}, {
bufferSize = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
});
#endif
if ((DWORD)bufferSize == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(1) failed");
return;
}
void *dataBuffer = new char[bufferSize];
DWORD ret = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
ret = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
}, {
ret = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
} );
#endif
if (ret == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(2) failed");
delete [](char *)dataBuffer;
return;
}
if(metric) {
// #### obey scale
*metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
(int)gMetric.gmBlackBoxX, (int)gMetric.gmBlackBoxY,
gMetric.gmCellIncX, gMetric.gmCellIncY);
}
int offset = 0;
int headerOffset = 0;
TTPOLYGONHEADER *ttph = 0;
QPointF oset = position.toPointF();
while (headerOffset < bufferSize) {
ttph = (TTPOLYGONHEADER*)((char *)dataBuffer + headerOffset);
QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale));
path->moveTo(lastPoint + oset);
offset += sizeof(TTPOLYGONHEADER);
TTPOLYCURVE *curve;
while (offset<int(headerOffset + ttph->cb)) {
curve = (TTPOLYCURVE*)((char*)(dataBuffer) + offset);
switch (curve->wType) {
case TT_PRIM_LINE: {
for (int i=0; i<curve->cpfx; ++i) {
QPointF p = qt_to_qpointf(curve->apfx[i], scale) + oset;
path->lineTo(p);
}
break;
}
case TT_PRIM_QSPLINE: {
const QPainterPath::Element &elm = path->elementAt(path->elementCount()-1);
QPointF prev(elm.x, elm.y);
QPointF endPoint;
for (int i=0; i<curve->cpfx - 1; ++i) {
QPointF p1 = qt_to_qpointf(curve->apfx[i], scale) + oset;
QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale) + oset;
if (i < curve->cpfx - 2) {
endPoint = QPointF((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
} else {
endPoint = p2;
}
path->quadTo(p1, endPoint);
prev = endPoint;
}
break;
}
case TT_PRIM_CSPLINE: {
for (int i=0; i<curve->cpfx; ) {
QPointF p2 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
path->cubicTo(p2, p3, p4);
}
break;
}
default:
qWarning("QFontEngineWin::addOutlineToPath, unhandled switch case");
}
offset += sizeof(TTPOLYCURVE) + (curve->cpfx-1) * sizeof(POINTFX);
}
path->closeSubpath();
headerOffset += ttph->cb;
}
delete [] (char*)dataBuffer;
}
void QFontEngineWin::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
QPainterPath *path, QTextItem::RenderFlags)
{
LOGFONT lf = logfont;
// The sign must be negative here to make sure we match against character height instead of
// hinted cell height. This ensures that we get linear matching, and we need this for
// paths since we later on apply a scaling transform to the glyph outline to get the
// font at the correct pixel size.
lf.lfHeight = -unitsPerEm;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
for(int i = 0; i < nglyphs; ++i)
addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0, qreal(fontDef.pixelSize) / unitsPerEm);
DeleteObject(SelectObject(hdc, oldfont));
}
void QFontEngineWin::addOutlineToPath(qreal x, qreal y, const QGlyphLayout *glyphs, int numGlyphs,
QPainterPath *path, QTextItem::RenderFlags flags)
{
#if !defined(Q_OS_WINCE)
if(tm.w.tmPitchAndFamily & (TMPF_TRUETYPE)) {
QFontEngine::addOutlineToPath(x, y, glyphs, numGlyphs, path, flags);
return;
}
#endif
QFontEngine::addBitmapFontToPath(x, y, glyphs, numGlyphs, path, flags);
}
QFontEngine::FaceId QFontEngineWin::faceId() const
{
return _faceId;
}
QT_BEGIN_INCLUDE_NAMESPACE
#include <qdebug.h>
QT_END_INCLUDE_NAMESPACE
int QFontEngineWin::synthesized() const
{
if(synthesized_flags == -1) {
synthesized_flags = 0;
if(ttf) {
const DWORD HEAD = MAKE_TAG('h', 'e', 'a', 'd');
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
uchar data[4];
GetFontData(hdc, HEAD, 44, &data, 4);
USHORT macStyle = getUShort(data);
if (tm.w.tmItalic && !(macStyle & 2))
synthesized_flags = SynthesizedItalic;
if (fontDef.stretch != 100 && ttf)
synthesized_flags |= SynthesizedStretch;
if (tm.w.tmWeight >= 500 && !(macStyle & 1))
synthesized_flags |= SynthesizedBold;
//qDebug() << "font is" << _name <<
// "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags;
}
}
return synthesized_flags;
}
QFixed QFontEngineWin::emSquareSize() const
{
return unitsPerEm;
}
QFontEngine::Properties QFontEngineWin::properties() const
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
Properties p;
p.emSquare = unitsPerEm;
p.italicAngle = otm->otmItalicAngle;
p.postscriptName = (char *)otm + (int)otm->otmpFamilyName;
p.postscriptName += (char *)otm + (int)otm->otmpStyleName;
#ifndef QT_NO_PRINTER
p.postscriptName = QPdf::stripSpecialCharacters(p.postscriptName);
#endif
p.boundingBox = QRectF(otm->otmrcFontBox.left, -otm->otmrcFontBox.top,
otm->otmrcFontBox.right - otm->otmrcFontBox.left,
otm->otmrcFontBox.top - otm->otmrcFontBox.bottom);
p.ascent = otm->otmAscent;
p.descent = -otm->otmDescent;
p.leading = (int)otm->otmLineGap;
p.capHeight = 0;
p.lineWidth = otm->otmsUnderscoreSize;
free(otm);
DeleteObject(SelectObject(hdc, oldfont));
return p;
}
void QFontEngineWin::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
int flags = synthesized();
if(flags & SynthesizedItalic)
lf.lfItalic = false;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
QFixedPoint p;
p.x = 0;
p.y = 0;
addGlyphToPath(glyph, p, hdc, path, ttf, metrics);
DeleteObject(SelectObject(hdc, oldfont));
}
bool QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) const
{
if (!ttf)
return false;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
DWORD t = qbswap<quint32>(tag);
*length = GetFontData(hdc, t, 0, buffer, *length);
return *length != GDI_ERROR;
}
#if !defined(CLEARTYPE_QUALITY)
# define CLEARTYPE_QUALITY 5
#endif
QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph)
{
glyph_metrics_t gm = boundingBox(glyph);
int glyph_x = qFloor(gm.x.toReal());
int glyph_y = qFloor(gm.y.toReal());
int glyph_width = qCeil((gm.x + gm.width).toReal()) - glyph_x;
int glyph_height = qCeil((gm.y + gm.height).toReal()) - glyph_y;
if (glyph_width + glyph_x <= 0 || glyph_height <= 0)
return QImage();
QImage im(glyph_width, glyph_height, QImage::Format_ARGB32_Premultiplied);
im.fill(0);
QPainter p(&im);
HFONT oldHFont = hfont;
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
// try hard to disable cleartype rendering
static_cast<QRasterPaintEngine *>(p.paintEngine())->disableClearType();
LOGFONT nonCleartypeFont = logfont;
nonCleartypeFont.lfQuality = ANTIALIASED_QUALITY;
hfont = CreateFontIndirect(&nonCleartypeFont);
}
p.setPen(Qt::black);
p.setBrush(Qt::NoBrush);
QTextItemInt ti;
ti.ascent = ascent();
ti.descent = descent();
ti.width = glyph_width;
ti.fontEngine = this;
ti.num_glyphs = 1;
QGlyphLayout glyphLayout;
ti.glyphs = &glyphLayout;
glyphLayout.glyph = glyph;
memset(&glyphLayout.attributes, 0, sizeof(glyphLayout.attributes));
glyphLayout.advance.x = glyph_width;
p.drawTextItem(QPointF(-glyph_x, -glyph_y), ti);
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
DeleteObject(hfont);
hfont = oldHFont;
}
p.end();
QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
QVector<QRgb> colors(256);
for (int i=0; i<256; ++i)
colors[i] = qRgba(0, 0, 0, i);
indexed.setColorTable(colors);
for (int y=0; y<im.height(); ++y) {
uchar *dst = (uchar *) indexed.scanLine(y);
uint *src = (uint *) im.scanLine(y);
for (int x=0; x<im.width(); ++x)
dst[x] = qAlpha(src[x]);
}
return indexed;
}
// -------------------------------------- Multi font engine
QFontEngineMultiWin::QFontEngineMultiWin(QFontEngineWin *first, const QStringList &fallbacks)
: QFontEngineMulti(fallbacks.size()+1),
fallbacks(fallbacks)
{
engines[0] = first;
first->ref.ref();
fontDef = engines[0]->fontDef;
}
void QFontEngineMultiWin::loadEngine(int at)
{
Q_ASSERT(at < engines.size());
Q_ASSERT(engines.at(at) == 0);
QString fam = fallbacks.at(at-1);
LOGFONT lf = static_cast<QFontEngineWin *>(engines.at(0))->logfont;
HFONT hfont;
QT_WA({
memcpy(lf.lfFaceName, fam.utf16(), sizeof(TCHAR)*qMin(fam.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectW(&lf);
} , {
// LOGFONTA and LOGFONTW are binary compatible
QByteArray lname = fam.toLocal8Bit();
memcpy(lf.lfFaceName,lname.data(),
qMin(lname.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectA((LOGFONTA*)&lf);
});
bool stockFont = false;
if (hfont == 0) {
hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
stockFont = true;
}
engines[at] = new QFontEngineWin(fam, hfont, stockFont, lf);
engines[at]->ref.ref();
engines[at]->fontDef = fontDef;
}
QT_END_NAMESPACE
| liuyanghejerry/qtextended | qtopiacore/qt/src/gui/text/qfontengine_win.cpp | C++ | gpl-2.0 | 43,049 |
<?php
/**
* The markup for the frontend of the Latest Comments widget
*
* @package Muut
* @copyright 2014 Muut Inc
*/
/**
* This file assumes that we are within the widget() method of the Muut_Widget_Latest_Comments class (which extends WP_Widget).
* Knowing that, `$this` represents that widget instance.
*/
?>
<div id="muut-widget-latest-comments-wrapper" class="muut_widget_wrapper muut_widget_latest_comments_wrapper">
<ul id="muut-recentcomments">
<?php
foreach ( $latest_comments_data as $comment ) {
if ( is_string( $comment['user'] ) ) {
$user_obj->displayname = $comment['user'];
$user_obj->img = '';
$user_obj->path = $comment['user'];
} else {
$user_obj = $comment['user'];
}
echo $this->getRowMarkup( $comment['post_id'], $comment['timestamp'], $comment['user'] );
}
?>
</ul>
</div>
| AnduZhang/resource-center | wp-content/plugins/muut/views/widgets/widget-latest-comments.php | PHP | gpl-2.0 | 846 |
<?php defined( '_JEXEC') or die( 'Restricted Access' );
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BinaryStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Utility class to walk through a data stream byte by byte with conventional names
*
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Util_BinaryStream
{
/**
* @var string Byte stream
*/
protected $_stream;
/**
* @var int Length of stream
*/
protected $_streamLength;
/**
* @var bool BigEndian encoding?
*/
protected $_bigEndian;
/**
* @var int Current position in stream
*/
protected $_needle;
/**
* Constructor
*
* Create a reference to a byte stream that is going to be parsed or created
* by the methods in the class. Detect if the class should use big or
* little Endian encoding.
*
* @param string $stream use '' if creating a new stream or pass a string if reading.
* @return void
*/
public function __construct($stream)
{
if (!is_string($stream)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Inputdata is not of type String');
}
$this->_stream = $stream;
$this->_needle = 0;
$this->_streamLength = strlen($stream);
$this->_bigEndian = (pack('l', 1) === "\x00\x00\x00\x01");
}
/**
* Returns the current stream
*
* @return string
*/
public function getStream()
{
return $this->_stream;
}
/**
* Read the number of bytes in a row for the length supplied.
*
* @todo Should check that there are enough bytes left in the stream we are about to read.
* @param int $length
* @return string
* @throws Zend_Amf_Exception for buffer underrun
*/
public function readBytes($length)
{
if (($length + $this->_needle) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
$bytes = substr($this->_stream, $this->_needle, $length);
$this->_needle+= $length;
return $bytes;
}
/**
* Write any length of bytes to the stream
*
* Usually a string.
*
* @param string $bytes
* @return Zend_Amf_Util_BinaryStream
*/
public function writeBytes($bytes)
{
$this->_stream.= $bytes;
return $this;
}
/**
* Reads a signed byte
*
* @return int Value is in the range of -128 to 127.
*/
public function readByte()
{
if (($this->_needle + 1) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
return ord($this->_stream{$this->_needle++});
}
/**
* Writes the passed string into a signed byte on the stream.
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeByte($stream)
{
$this->_stream.= pack('c', $stream);
return $this;
}
/**
* Reads a signed 32-bit integer from the data stream.
*
* @return int Value is in the range of -2147483648 to 2147483647
*/
public function readInt()
{
return ($this->readByte() << 8) + $this->readByte();
}
/**
* Write an the integer to the output stream as a 32 bit signed integer
*
* @param int $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeInt($stream)
{
$this->_stream.= pack('n', $stream);
return $this;
}
/**
* Reads a UTF-8 string from the data stream
*
* @return string A UTF-8 string produced by the byte representation of characters
*/
public function readUtf()
{
$length = $this->readInt();
return $this->readBytes($length);
}
/**
* Wite a UTF-8 string to the outputstream
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeUtf($stream)
{
$this->writeInt(strlen($stream));
$this->_stream.= $stream;
return $this;
}
/**
* Read a long UTF string
*
* @return string
*/
public function readLongUtf()
{
$length = $this->readLong();
return $this->readBytes($length);
}
/**
* Write a long UTF string to the buffer
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLongUtf($stream)
{
$this->writeLong(strlen($stream));
$this->_stream.= $stream;
}
/**
* Read a long numeric value
*
* @return double
*/
public function readLong()
{
return ($this->readByte() << 24) + ($this->readByte() << 16) + ($this->readByte() << 8) + $this->readByte();
}
/**
* Write long numeric value to output stream
*
* @param int|string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLong($stream)
{
$this->_stream.= pack('N', $stream);
return $this;
}
/**
* Read a 16 bit unsigned short.
*
* @todo This could use the unpack() w/ S,n, or v
* @return double
*/
public function readUnsignedShort()
{
$byte1 = $this->readByte();
$byte2 = $this->readByte();
return (($byte1 << 8) | $byte2);
}
/**
* Reads an IEEE 754 double-precision floating point number from the data stream.
*
* @return double Floating point number
*/
public function readDouble()
{
$bytes = substr($this->_stream, $this->_needle, 8);
$this->_needle+= 8;
if (!$this->_bigEndian) {
$bytes = strrev($bytes);
}
$double = unpack('dflt', $bytes);
return $double['flt'];
}
/**
* Writes an IEEE 754 double-precision floating point number from the data stream.
*
* @param string|double $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeDouble($stream)
{
$stream = pack('d', $stream);
if (!$this->_bigEndian) {
$stream = strrev($stream);
}
$this->_stream.= $stream;
return $this;
}
}
| kiennd146/nhazz.com | plugins/system/zend/Zend/Amf/Util/BinaryStream.php | PHP | gpl-2.0 | 7,414 |
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
var varienTabs = new Class.create();
varienTabs.prototype = {
initialize : function(containerId, destElementId, activeTabId, shadowTabs){
this.containerId = containerId;
this.destElementId = destElementId;
this.activeTab = null;
this.tabOnClick = this.tabMouseClick.bindAsEventListener(this);
this.tabs = $$('#'+this.containerId+' li a.tab-item-link');
this.hideAllTabsContent();
for (var tab=0; tab<this.tabs.length; tab++) {
Event.observe(this.tabs[tab],'click',this.tabOnClick);
// move tab contents to destination element
if($(this.destElementId)){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].contentMoved = true;
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
/*
// this code is pretty slow in IE, so lets do it in tabs*.phtml
// mark ajax tabs as not loaded
if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) {
Element.addClassName($(this.tabs[tab].id), 'notloaded');
}
*/
// bind shadow tabs
if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) {
this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id];
}
}
this.displayFirst = activeTabId;
Event.observe(window,'load',this.moveTabContentInDest.bind(this));
},
setSkipDisplayFirstTab : function(){
this.displayFirst = null;
},
moveTabContentInDest : function(){
for(var tab=0; tab<this.tabs.length; tab++){
if($(this.destElementId) && !this.tabs[tab].contentMoved){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
}
if (this.displayFirst) {
this.showTabContent($(this.displayFirst));
this.displayFirst = null;
}
},
getTabContentElementId : function(tab){
if(tab){
return tab.id+'_content';
}
return false;
},
tabMouseClick : function(event) {
var tab = Event.findElement(event, 'a');
// go directly to specified url or switch tab
if ((tab.href.indexOf('#') != tab.href.length-1)
&& !(Element.hasClassName(tab, 'ajax'))
) {
location.href = tab.href;
}
else {
this.showTabContent(tab);
}
Event.stop(event);
},
hideAllTabsContent : function(){
for(var tab in this.tabs){
this.hideTabContent(this.tabs[tab]);
}
},
// show tab, ready or not
showTabContentImmediately : function(tab) {
this.hideAllTabsContent();
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
Element.show(tabContentElement);
Element.addClassName(tab, 'active');
// load shadow tabs, if any
if (tab.shadowTabs && tab.shadowTabs.length) {
for (var k in tab.shadowTabs) {
this.loadShadowTab($(tab.shadowTabs[k]));
}
}
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
this.activeTab = tab;
}
if (varienGlobalEvents) {
varienGlobalEvents.fireEvent('showTab', {tab:tab});
}
},
// the lazy show tab method
showTabContent : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
if (this.activeTab != tab) {
if (varienGlobalEvents) {
if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) {
return;
};
}
}
// wait for ajax request, if defined
var isAjax = Element.hasClassName(tab, 'ajax');
var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1;
var isNotLoaded = Element.hasClassName(tab, 'notloaded');
if ( isAjax && (isEmpty || isNotLoaded) )
{
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}.bind(this)
});
}
else {
this.showTabContentImmediately(tab);
}
}
},
loadShadowTab : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) {
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}.bind(this)
});
}
},
hideTabContent : function(tab){
var tabContentElement = $(this.getTabContentElementId(tab));
if($(this.destElementId) && tabContentElement){
Element.hide(tabContentElement);
Element.removeClassName(tab, 'active');
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('hideTab', {tab:tab});
}
}
}
| T0MM0R/magento | web/js/mage/adminhtml/tabs.js | JavaScript | gpl-2.0 | 10,013 |