answer stringlengths 15 1.25M |
|---|
const path = require(`path`);
const _ = require("lodash");
const { createFilePath } = require(`<API key>`);
exports.onCreateNode = ({ node, getNode, actions }, pluginOptions) => {
const { createNodeField } = actions;
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `pages` });
const parent = getNode(node.parent);
const idName = _.kebabCase(node.frontmatter.title || parent.name);
createNodeField({
node,
name: `slug`,
value: slug
});
createNodeField({
node,
name: `idName`,
value: idName
});
// save the file's directory so it can be used by the Template
// component to group data in a GraphQL query
createNodeField({
node,
name: `<API key>`,
value: parent.relativeDirectory
});
// set a version field on pages so they can be queried
// appropriately in the Template component
let version = pluginOptions.currentVersion;
if (parent.gitRemote___NODE) {
const { sourceInstanceName } = getNode(parent.gitRemote___NODE);
version = sourceInstanceName;
}
createNodeField({
node,
name: `version`,
value: version
});
}
};
exports.createPages = async ({ actions, graphql }, pluginOptions) => {
actions.createPage({
path: `/`,
component: path.resolve(`./src/components/template.js`)
});
}; |
<?php
//
// DO NOT EDIT DIRECTLY. EDIT THE CLASS EXTENSIONS IN THE CONTROL PANEL.
namespace LiamW\<API key>\XF\Admin\Controller
{
class XFCP_User extends \XF\Admin\Controller\User {}
}
namespace LiamW\<API key>\XF\ChangeLog
{
class XFCP_User extends \XF\ChangeLog\User {}
}
namespace LiamW\<API key>\XF\Pub\Controller
{
class XFCP_Account extends \XF\Pub\Controller\Account {}
class XFCP_Register extends \XF\Pub\Controller\Register {}
}
namespace LiamW\<API key>\XF\Searcher
{
class XFCP_User extends \XF\Searcher\User {}
}
namespace LiamW\<API key>\XF\Service\User
{
class XFCP_Registration extends \XF\Service\User\Registration {}
} |
#define PROXY_DELEGATION
#include <rpcproxy.h>
#ifdef __cplusplus
extern "C" {
#endif
EXTERN_PROXY_FILE( _tstlib )
<API key>
/* Start of list */
<API key>( _tstlib ),
/* End of list */
PROXYFILE_LIST_END
DLLDATA_ROUTINES( aProxyFileList, GET_DLL_CLSID )
#ifdef __cplusplus
} /*extern "C" */
#endif
/* end of generated dlldata file */ |
<?php
require_once(FCPATH.'/application/views/breadcrumb.php');
require_once(FCPATH.'/application/views/<API key>.php');
$request_counter_url = site_url('admin/counters/get_all/');
?>
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light ">
<div class="portlet-title">
<div class="caption font-dark">
<i class="icon-settings font-dark"></i>
<span class="caption-subject bold uppercase">Company Counter</span>
</div>
<div class="actions">
<div class="btn-group btn-group-devided">
<a class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm" href="<?php echo site_url('admin/counters/register'); ?>">Add New</a>
</div>
</div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover dt-responsive" id="counters-tb1" data-url="<?php echo $request_counter_url; ?>">
<thead>
<tr>
<th class="all">Counter name</th>
<th class="min-phone-l">Address</th>
<th class="min-phone-l">Details</th>
<th class="none">Company Name</th>
<th class="none">Incharge</th>
<th class="none">Mobile</th>
<th class="none">Thana</th>
<th class="none">District</th>
<th width="20" class="all">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div> |
import Vue from "vue";
import WithRender from "./app.html";
@WithRender
export default class App extends Vue {} |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CWT-Prolog Server Interface %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_parameters)).
:- use_module(database).
% Basic header for plain text
header('text/plain', 'Content-type: text/plain~n~n').
%
% Main Interface
%
:- dynamic port/1.
:- http_handler(/, server_status, []).
:- http_handler('/login', login, []).
:- http_handler('/logout', logout, []).
:- http_handler('/ping', ping, []).
:- http_handler('/create_game', create_game, []).
:- http_handler('/join_game', join_game, []).
:- http_handler('/resign_game', resign_game, []).
%% start_server(+File:atom, +Port:between(1, 0xffff)) is semidet.
%
% Attach to the specified database file, and start the server on the specified
% port.
start_server(File, Port) :-
must_be(between(1, 0xffff), Port),
attach_db(File),
db_sync(gc),
asserta(port(Port)),
http_server(http_dispatch, [port(Port)]).
%% server_status(+Request) is det.
%
% Friendly message to let client know that the server is up.
server_status(_Request) :-
header('text/plain', Header),
format(Header),
format('Server is up.~n').
%% send_status(+Status:string) is det.
%
% Takes a response status and sends the information to the client.
send_status(Status) :-
header('text/plain', Header),
format(Header),
format('~s', [Status]).
%% disconnect is det.
%
% Shut down server on specified port and clean up information from top level.
disconnect :-
port(Port),
http_stop_server(Port, []),
retractall(port(_)).
%
% Queries
%
%% login(+Query:compound) is det.
%
% Attempt login and send status back to client.
login(Query) :-
http_parameters(Query, [name(User, [string])]),
login(user(User), Response),
send_status(Response).
%% login(+Query:compound) is det.
%
% Attempt logout and send status back to client.
logout(Query) :-
http_parameters(Query, [name(User, [string])]),
logout(user(User), Response),
send_status(Response).
%% ping(+Query:compound) is det.
%
% Receive ping from client with username.
ping(Query) :-
http_parameters(Query, [name(User, [string])]),
ping(user(User), Response),
send_status(Response).
%% create_game(+Query:compound) is det.
%
% Create a game if all internal restrictions are met for creation.
create_game(Query) :-
http_parameters(Query, [
user(User, [string]),
pos(Pos, [between(1, 4)]),
game(Game, [string]),
limit(Limit, [between(1, 4)]),
layout(Layout, [string])
]),
string_codes(Layout, Codes),
maplist(code_lower_char, Codes, Chars),
create_game(game(User, Game, limit(Limit), Chars), pos(Pos), Response),
send_status(Response).
code_lower_char(Code, Char) :-
to_lower(Code, Lower),
char_code(Char, Lower).
%% join_game(+Query:compound) is det.
%
% Allow a user to join a game if all internal restrictions are met for admission.
join_game(Query) :-
http_parameters(Query, [
user(User, [string]),
pos(Pos, [between(1, 4)]),
game(Game, [string])
]),
join_game(user(User), pos(Pos), Game, Response),
send_status(Response).
%% resign_game(+Query:compound) is det.
%
% Resign a user from a game.
resign_game(Query) :-
http_parameters(Query, [
user(User, [string]),
game(Game, [string]),
pos(Pos, [between(1, 4)])
]),
resign_game(user(User), Game, pos(Pos), Response),
send_status(Response). |
require("./38.js");
require("./76.js");
require("./153.js");
require("./306.js");
module.exports = 307; |
#include "ofApp.h"
void ofApp::setup(){
receiver.setup(12345);
panel.setup("pin control");
// SETUP fan (which will alter panel here)
panel.add(allOn.setup("all on", false));
panel.add(useOsc.setup("use osc", false));
LC.setup();
FM.setup();
SM.setup();
ofSoundStreamSetup(2,0,this, 44100, 256, 4);
angle = 0;
angleAdder = 0.01;
mainTargetColor.set(255,255,255);
overallEnergySmooth = 0;
<API key> = 0;
}
static float crazyAngle = 0;
void ofApp::update(){
while(receiver.hasWaitingMessages()){
ofxOscMessage m;
receiver.getNextMessage(&m);
if(m.getAddress() == "/strength");
float strength = m.getArgAsFloat(0);
overAllEnergy = strength;
float <API key> = overallEnergySmooth;
if (overallEnergySmooth < overAllEnergy){
overallEnergySmooth = 0.94f * overallEnergySmooth + 0.06 * overAllEnergy;
} else {
overallEnergySmooth = 0.99f * overallEnergySmooth + 0.01 * overAllEnergy;
}
overallEnergyChange = <API key>;
cout << fabs(overallEnergyChange) << endl;
if (fabs(overallEnergyChange) < 0.001){
<API key>++;
} else {
<API key> = 0;
}
if (<API key> > 100 && overallEnergySmooth < 0.05){
<API key> = <API key> * 0.99 + 0.01 * 1.0;
} else {
<API key> = <API key> * 0.99 + 0.01 * 0.0;
}
// cout << <API key> << endl;
// sub energies:
// TODO param
individEnergy[0] = 0.95f * individEnergy[0] + 0.05 * m.getArgAsFloat(1);
individEnergy[1] = 0.95f * individEnergy[1] + 0.05 * m.getArgAsFloat(2);
individEnergy[2] = 0.95f * individEnergy[2] + 0.05 * m.getArgAsFloat(3);
// TODO better logic here please
if (useOsc == true){
FM.setStrength(0, m.getArgAsFloat(1));
FM.setStrength(1, m.getArgAsFloat(2));
FM.setStrength(2, m.getArgAsFloat(3));
//FM.setStrength(overAllEnergy);
// TODO FIXME //setStregnth
}
FM.computeFanEnergy();
}
//cout << allOn << endl;
// light
ofColor a =ofColor::green;
ofColor b =ofColor::red;
ofColor c =ofColor::blue;
a.setBrightness( ofMap(individEnergy[0], 0, 1, 100, 255, true));
b.setBrightness( ofMap(individEnergy[1], 0, 1, 100, 255, true));
c.setBrightness( ofMap(individEnergy[2], 0, 1, 100, 255, true));
int order[] = { 0,1,2,3,5,4,11,10,9,6,8,7 };
int whoIsStrongest = -1;
float strength = -1;
for (int i = 0; i < 3; i++){
if (strength < individEnergy[i]){
strength = individEnergy[i];
whoIsStrongest = i;
}
}
ofColor aT =ofColor::green;
ofColor bT =ofColor::red;
ofColor cT =ofColor::blue;
ofColor colors[3];
colors[0]= aT;
colors[1]= bT;
colors[2]= cT;
if (whoIsStrongest != -1 && strength > 0.15){
mainTargetColor = 0.93f * mainTargetColor + 0.07 * ofPoint(colors[whoIsStrongest].r, colors[whoIsStrongest].g, colors[whoIsStrongest].b);
} else {
mainTargetColor = 0.93f * mainTargetColor + 0.07 * ofPoint(255,255,255);
}
//overAllEnergy = ofMap(mouseX, 0, ofGetWidth(), 0, 1);
//overallEnergySmooth = 0.98f * overallEnergySmooth + 0.02*overAllEnergy;
angleAdder = ofMap( powf(overallEnergySmooth, 5.0), 0, 1.0, 0.05, 0.19);
angle += angleAdder;
while(angle > TWO_PI) angle -= TWO_PI;
while(angle < 0) angle += TWO_PI;
crazyAngle += ofMap(powf(overallEnergySmooth, 3.0), 0,1.0, 0.1, 0.6);
while(crazyAngle > TWO_PI) crazyAngle -= TWO_PI;
while(crazyAngle < 0) crazyAngle += TWO_PI;
for (int i = 0; i < 12; i++){
int who = order[i];
//dmx.setLevel(1 + who * 5, 255);
for (int j = 0; j < 3; j++){
float angleComp = (i/12.0) * TWO_PI;
float angleDiff = angleComp - angle;
while (angleDiff < -PI) angleDiff += TWO_PI;
while (angleDiff > PI) angleDiff -= TWO_PI;
float pct = 1 - fabs(angleDiff) / PI;
pct = powf(pct, ofMap(overallEnergySmooth, 0, 1, 0.9, 3.0));
//cout << order[i] << " " << pct << endl;
ofColor result = ofColor(mainTargetColor.x, mainTargetColor.y, mainTargetColor.z);
float crazyAmount = powf(overallEnergySmooth, 1.4);
float onValue = ofMap( sin(crazyAngle + i*0.37), -1,1, 0 + overallEnergySmooth * 0.7, 1);
float onPulse = crazyAmount * onValue + (1-crazyAmount) * pct;
float newVal = onPulse *( 80 + powf(overallEnergySmooth,2.0) * (255-80));
newVal = ofMap( powf(sin(<API key>()/2000.0)*0.5+0.5, 6.0), 0,1, newVal, newVal - newVal * <API key>);
result.setBrightness( newVal );
LC.setColor(i, result);
//dmx.setLevel(2+j+ who * 5, 255 * pct);
}
}
SM.actualVolume = ofMap( powf(overallEnergySmooth, SM.soundHitShaper), 0, 1, 0, SM.maxVolume, true);
// FM.setStrength(overallEnergySmooth);
//if (<API key> > 0.01){
a.r = ofMap( sin(<API key>()/1000.0 + TWO_PI/4), -1,1, a.r, a.r - a.r * <API key>);
a.g = ofMap( sin(<API key>()/1000.0+ TWO_PI/4), -1,1, a.g, a.g - a.g * <API key>);
a.b = ofMap( sin(<API key>()/1000.0+ TWO_PI/4), -1,1, a.b, a.b - a.b * <API key>);
b.r = ofMap( sin(<API key>()/1000.0+ TWO_PI/2), -1,1, b.r, b.r - b.r * <API key>);
b.g = ofMap( sin(<API key>()/1000.0+ TWO_PI/2), -1,1, b.g, b.g - b.g * <API key>);
b.b = ofMap( sin(<API key>()/1000.0+ TWO_PI/2), -1,1, b.b, b.b - b.b * <API key>);
c.r = ofMap( sin(<API key>()/1000.0+3*TWO_PI/2), -1,1, c.r, c.r - c.r * <API key>);
c.g = ofMap( sin(<API key>()/1000.0+3*TWO_PI/2), -1,1, c.g, c.g - c.g * <API key>);
c.b = ofMap( sin(<API key>()/1000.0+3*TWO_PI/2), -1,1, c.b, c.b - c.b * <API key>);
LC.setColor(12, a);
LC.setColor(13, b);
LC.setColor(14, c);
LC.update();
FM.update();
SM.update();
}
void ofApp::draw(){
ofBackground(ofColor::lightCoral);
panel.draw();
LC.draw();
FM.draw();
SM.draw();
}
void ofApp::audioRequested(float * output, int bufferSize, int nChannels){
for (int i = 0; i < bufferSize; i++){
output[i*nChannels ] = 0;
output[i*nChannels + 1] = 0;
}
// TODO: optimize
SM.audioRequested(output, bufferSize, nChannels);
}
void ofApp::keyPressed(int key){
SM.keyPressed(key);
}
void ofApp::keyReleased(int key){
}
void ofApp::mouseMoved(int x, int y ){
}
void ofApp::mouseDragged(int x, int y, int button){
}
void ofApp::mousePressed(int x, int y, int button){
}
void ofApp::mouseReleased(int x, int y, int button){
}
void ofApp::windowResized(int w, int h){
}
void ofApp::gotMessage(ofMessage msg){
}
void ofApp::dragEvent(ofDragInfo dragInfo){
} |
<!doctype html>
<html>
<head>
<title>Tracking.JS Test Page</title>
<meta name="ga-trackingid" content="UA-12314225-13">
<meta name="ga-features" content="displayfeatures,linkid,events">
<meta name="ga-debug" content="true">
<meta name="ga-trace" content="true">
<meta name="ga-dimension1" content="Captured">
</head>
<body>
<h1>Tracking.JS Test Page</h1>
<p><a href="tel:0731126400">07 3112 6400</a></p>
<p><a href="#bottom">Goto Bottom of the Page</a></p>
<script src="../dist/tracking-js.min.js"></script>
</body>
</html> |
TinkerforgeDemos
=============
Tinkerforge demo projects (originaly for the article in dotnetpro Magazin 12/2013)
https: |
//
// extend.js
//
var createjs = createjs||{};
/**
* @class Utility Methods
*/
createjs.extend = function(subclass, superclass) {
"use strict";
function o() { this.constructor = subclass; }
o.prototype = superclass.prototype;
return (subclass.prototype = new o());
};
//
// promote.js
//
//this.createjs = this.createjs||{};
/**
* @class Utility Methods
*/
/**
* Promotes any methods on the super class that were overridden, by creating an alias in the format `prefix_methodName`.
* It is recommended to use the super class's name as the prefix.
* An alias to the super class's constructor is always added in the format `prefix_constructor`.
* This allows the subclass to call super class methods without using `function.call`, providing better performance.
*
* For example, if `MySubClass` extends `MySuperClass`, and both define a `draw` method, then calling `promote(MySubClass, "MySuperClass")`
* would add a `<API key>` method to MySubClass and promote the `draw` method on `MySuperClass` to the
* prototype of `MySubClass` as `MySuperClass_draw`.
*
* This should be called after the class's prototype is fully defined.
*
* function ClassA(name) {
* this.name = name;
* }
* ClassA.prototype.greet = function() {
* return "Hello "+this.name;
* }
*
* function ClassB(name, punctuation) {
* this.ClassA_constructor(name);
* this.punctuation = punctuation;
* }
* createjs.extend(ClassB, ClassA);
* ClassB.prototype.greet = function() {
* return this.ClassA_greet()+this.punctuation;
* }
* createjs.promote(ClassB, "ClassA");
*
* var foo = new ClassB("World", "!?!");
* console.log(foo.greet()); // Hello World!?!
*
* @method promote
* @param {Function} subclass The class to promote super class methods on.
* @param {String} prefix The prefix to add to the promoted method names. Usually the name of the superclass.
* @return {Function} Returns the subclass.
*/
createjs.promote = function(subclass, prefix) {
"use strict";
var subP = subclass.prototype, supP = (Object.getPrototypeOf&&Object.getPrototypeOf(subP))||subP.__proto__;
if (supP) {
subP[(prefix+="_") + "constructor"] = supP.constructor; // constructor is not always innumerable
for (var n in supP) {
if (subP.hasOwnProperty(n) && (typeof supP[n] == "function")) { subP[prefix + n] = supP[n]; }
}
}
return subclass;
};
//
// indexOf.js
//
//this.createjs = this.createjs||{};
/**
* @class Utility Methods
*/
/**
* Finds the first occurrence of a specified value searchElement in the passed in array, and returns the index of
* that value. Returns -1 if value is not found.
*
* var i = createjs.indexOf(myArray, myElementToFind);
*
* @method indexOf
* @param {Array} array Array to search for searchElement
* @param searchElement Element to find in array.
* @return {Number} The first index of searchElement in array.
*/
createjs.indexOf = function (array, searchElement){
"use strict";
for (var i = 0,l=array.length; i < l; i++) {
if (searchElement === array[i]) {
return i;
}
}
return -1;
};
//
// Event.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* Contains properties and methods shared by all events for use with
* {{#crossLink "EventDispatcher"}}{{/crossLink}}.
*
* Note that Event objects are often reused, so you should never
* rely on an event object's state outside of the call stack it was received in.
* @class Event
* @param {String} type The event type.
* @param {Boolean} bubbles Indicates whether the event will bubble through the display list.
* @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled.
* @constructor
**/
function Event(type, bubbles, cancelable) {
// public properties:
/**
* The type of event.
* @property type
* @type String
**/
this.type = type;
/**
* The object that generated an event.
* @property target
* @type Object
* @default null
* @readonly
*/
this.target = null;
/**
* The current target that a bubbling event is being dispatched from. For non-bubbling events, this will
* always be the same as target. For example, if childObj.parent = parentObj, and a bubbling event
* is generated from childObj, then a listener on parentObj would receive the event with
* target=childObj (the original target) and currentTarget=parentObj (where the listener was added).
* @property currentTarget
* @type Object
* @default null
* @readonly
*/
this.currentTarget = null;
/**
* For bubbling events, this indicates the current event phase:<OL>
* <LI> capture phase: starting from the top parent to the target</LI>
* <LI> at target phase: currently being dispatched from the target</LI>
* <LI> bubbling phase: from the target to the top parent</LI>
* </OL>
* @property eventPhase
* @type Number
* @default 0
* @readonly
*/
this.eventPhase = 0;
/**
* Indicates whether the event will bubble through the display list.
* @property bubbles
* @type Boolean
* @default false
* @readonly
*/
this.bubbles = !!bubbles;
/**
* Indicates whether the default behaviour of this event can be cancelled via
* {{#crossLink "Event/preventDefault"}}{{/crossLink}}. This is set via the Event constructor.
* @property cancelable
* @type Boolean
* @default false
* @readonly
*/
this.cancelable = !!cancelable;
/**
* The epoch time at which this event was created.
* @property timeStamp
* @type Number
* @default 0
* @readonly
*/
this.timeStamp = (new Date()).getTime();
/**
* Indicates if {{#crossLink "Event/preventDefault"}}{{/crossLink}} has been called
* on this event.
* @property defaultPrevented
* @type Boolean
* @default false
* @readonly
*/
this.defaultPrevented = false;
/**
* Indicates if {{#crossLink "Event/stopPropagation"}}{{/crossLink}} or
* {{#crossLink "Event/<API key>"}}{{/crossLink}} has been called on this event.
* @property propagationStopped
* @type Boolean
* @default false
* @readonly
*/
this.propagationStopped = false;
/**
* Indicates if {{#crossLink "Event/<API key>"}}{{/crossLink}} has been called
* on this event.
* @property <API key>
* @type Boolean
* @default false
* @readonly
*/
this.<API key> = false;
/**
* Indicates if {{#crossLink "Event/remove"}}{{/crossLink}} has been called on this event.
* @property removed
* @type Boolean
* @default false
* @readonly
*/
this.removed = false;
}
var p = Event.prototype;
/**
* <strong>REMOVED</strong>. Removed in favor of using `<API key>`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// public methods:
/**
* Sets {{#crossLink "Event/defaultPrevented"}}{{/crossLink}} to true if the event is cancelable.
* Mirrors the DOM level 2 event standard. In general, cancelable events that have `preventDefault()` called will
* cancel the default behaviour associated with the event.
* @method preventDefault
**/
p.preventDefault = function() {
this.defaultPrevented = this.cancelable&&true;
};
/**
* Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} to true.
* Mirrors the DOM event standard.
* @method stopPropagation
**/
p.stopPropagation = function() {
this.propagationStopped = true;
};
/**
* Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} and
* {{#crossLink "Event/<API key>"}}{{/crossLink}} to true.
* Mirrors the DOM event standard.
* @method <API key>
**/
p.<API key> = function() {
this.<API key> = this.propagationStopped = true;
};
/**
* Causes the active listener to be removed via removeEventListener();
*
* myBtn.addEventListener("click", function(evt) {
* // do stuff...
* evt.remove(); // removes this listener.
* });
*
* @method remove
**/
p.remove = function() {
this.removed = true;
};
/**
* Returns a clone of the Event instance.
* @method clone
* @return {Event} a clone of the Event instance.
**/
p.clone = function() {
return new Event(this.type, this.bubbles, this.cancelable);
};
/**
* Provides a chainable shortcut method for setting a number of properties on the instance.
*
* @method set
* @param {Object} props A generic object containing properties to copy to the instance.
* @return {Event} Returns the instance the method is called on (useful for chaining calls.)
* @chainable
*/
p.set = function(props) {
for (var n in props) { this[n] = props[n]; }
return this;
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Event (type="+this.type+")]";
};
createjs.Event = Event;
}());
//
// EventDispatcher.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* EventDispatcher provides methods for managing queues of event listeners and dispatching events.
*
* You can either extend EventDispatcher or mix its methods into an existing prototype or instance by using the
* EventDispatcher {{#crossLink "EventDispatcher/initialize"}}{{/crossLink}} method.
*
* Together with the CreateJS Event class, EventDispatcher provides an extended event model that is based on the
* DOM Level 2 event model, including addEventListener, removeEventListener, and dispatchEvent. It supports
* bubbling / capture, preventDefault, stopPropagation, <API key>, and handleEvent.
*
* EventDispatcher also exposes a {{#crossLink "EventDispatcher/on"}}{{/crossLink}} method, which makes it easier
* to create scoped listeners, listeners that only run once, and listeners with associated arbitrary data. The
* {{#crossLink "EventDispatcher/off"}}{{/crossLink}} method is merely an alias to
* {{#crossLink "EventDispatcher/removeEventListener"}}{{/crossLink}}.
*
* Another addition to the DOM Level 2 model is the {{#crossLink "EventDispatcher/<API key>"}}{{/crossLink}}
* method, which can be used to listeners for all events, or listeners for a specific event. The Event object also
* includes a {{#crossLink "Event/remove"}}{{/crossLink}} method which removes the active listener.
*
* <h4>Example</h4>
* Add EventDispatcher capabilities to the "MyClass" class.
*
* EventDispatcher.initialize(MyClass.prototype);
*
* Add an event (see {{#crossLink "EventDispatcher/addEventListener"}}{{/crossLink}}).
*
* instance.addEventListener("eventName", handlerMethod);
* function handlerMethod(event) {
* console.log(event.target + " Was Clicked");
* }
*
* <b>Maintaining proper scope</b><br />
* Scope (ie. "this") can be be a challenge with events. Using the {{#crossLink "EventDispatcher/on"}}{{/crossLink}}
* method to subscribe to events simplifies this.
*
* instance.addEventListener("click", function(event) {
* console.log(instance == this); // false, scope is ambiguous.
* });
*
* instance.on("click", function(event) {
* console.log(instance == this); // true, "on" uses dispatcher scope by default.
* });
*
* If you want to use addEventListener instead, you may want to use function.bind() or a similar proxy to manage
* scope.
*
* <b>Browser support</b>
* The event model in CreateJS can be used separately from the suite in any project, however the inheritance model
* requires modern browsers (IE9+).
*
*
* @class EventDispatcher
* @constructor
**/
function EventDispatcher() {
// private properties:
/**
* @protected
* @property _listeners
* @type Object
**/
this._listeners = null;
/**
* @protected
* @property _captureListeners
* @type Object
**/
this._captureListeners = null;
}
var p = EventDispatcher.prototype;
/**
* <strong>REMOVED</strong>. Removed in favor of using `<API key>`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// static public methods:
/**
* Static initializer to mix EventDispatcher methods into a target object or prototype.
*
* EventDispatcher.initialize(MyClass.prototype); // add to the prototype of the class
* EventDispatcher.initialize(myObject); // add to a specific instance
*
* @method initialize
* @static
* @param {Object} target The target object to inject EventDispatcher methods into. This can be an instance or a
* prototype.
**/
EventDispatcher.initialize = function(target) {
debugger
target.addEventListener = p.addEventListener;
target.on = p.on;
target.removeEventListener = target.off = p.removeEventListener;
target.<API key> = p.<API key>;
target.hasEventListener = p.hasEventListener;
target.dispatchEvent = p.dispatchEvent;
target._dispatchEvent = p._dispatchEvent;
target.willTrigger = p.willTrigger;
};
// public methods:
/**
* Adds the specified event listener. Note that adding multiple listeners to the same function will result in
* multiple callbacks getting fired.
*
* <h4>Example</h4>
*
* displayObject.addEventListener("click", handleClick);
* function handleClick(event) {
* // Click happened.
* }
*
* @method addEventListener
* @param {String} type The string type of the event.
* @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
* the event is dispatched.
* @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
* @return {Function | Object} Returns the listener for chaining or assignment.
**/
p.addEventListener = function(type, listener, useCapture) {
var listeners;
if (useCapture) {
listeners = this._captureListeners = this._captureListeners||{};
} else {
listeners = this._listeners = this._listeners||{};
}
var arr = listeners[type];
if (arr) { this.removeEventListener(type, listener, useCapture); }
arr = listeners[type]; // remove may have deleted the array
if (!arr) { listeners[type] = [listener]; }
else { arr.push(listener); }
return listener;
};
/**
* A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener
* only run once, associate arbitrary data with the listener, and remove the listener.
*
* This method works by creating an anonymous wrapper function and subscribing it with addEventListener.
* The wrapper function is returned for use with `removeEventListener` (or `off`).
*
* <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener, or use
* {{#crossLink "Event/remove"}}{{/crossLink}}. Likewise, each time you call `on` a NEW wrapper function is subscribed, so multiple calls
* to `on` with the same params will create multiple listeners.
*
* <h4>Example</h4>
*
* var listener = myBtn.on("click", handleClick, null, false, {count:3});
* function handleClick(evt, data) {
* data.count -= 1;
* console.log(this == myBtn); // true - scope defaults to the dispatcher
* if (data.count == 0) {
* alert("clicked 3 times!");
* myBtn.off("click", listener);
* // alternately: evt.remove();
* }
* }
*
* @method on
* @param {String} type The string type of the event.
* @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
* the event is dispatched.
* @param {Object} [scope] The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).
* @param {Boolean} [once=false] If true, the listener will remove itself after the first time it is triggered.
* @param {*} [data] Arbitrary data that will be included as the second parameter when the listener is called.
* @param {Boolean} [useCapture=false] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
* @return {Function} Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.
**/
p.on = function(type, listener, scope, once, data, useCapture) {
if (listener.handleEvent) {
scope = scope||listener;
listener = listener.handleEvent;
}
scope = scope||this;
return this.addEventListener(type, function(evt) {
listener.call(scope, evt, data);
once&&evt.remove();
}, useCapture);
};
/**
* Removes the specified event listener.
*
* <b>Important Note:</b> that you must pass the exact function reference used when the event was added. If a proxy
* function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or
* closure will not work.
*
* <h4>Example</h4>
*
* displayObject.removeEventListener("click", handleClick);
*
* @method removeEventListener
* @param {String} type The string type of the event.
* @param {Function | Object} listener The listener function or object.
* @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
**/
p.removeEventListener = function(type, listener, useCapture) {
var listeners = useCapture ? this._captureListeners : this._listeners;
if (!listeners) { return; }
var arr = listeners[type];
if (!arr) { return; }
for (var i=0,l=arr.length; i<l; i++) {
if (arr[i] == listener) {
if (l==1) { delete(listeners[type]); } // allows for faster checks.
else { arr.splice(i,1); }
break;
}
}
};
/**
* A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the
* .on method.
*
* <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener. See
* {{#crossLink "EventDispatcher/on"}}{{/crossLink}} for an example.
*
* @method off
* @param {String} type The string type of the event.
* @param {Function | Object} listener The listener function or object.
* @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
**/
p.off = p.removeEventListener;
/**
* Removes all listeners for the specified type, or all listeners of all types.
*
* <h4>Example</h4>
*
* // Remove all listeners
* displayObject.<API key>();
*
* // Remove all click listeners
* displayObject.<API key>("click");
*
* @method <API key>
* @param {String} [type] The string type of the event. If omitted, all listeners for all types will be removed.
**/
p.<API key> = function(type) {
if (!type) { this._listeners = this._captureListeners = null; }
else {
if (this._listeners) { delete(this._listeners[type]); }
if (this._captureListeners) { delete(this._captureListeners[type]); }
}
};
/**
* Dispatches the specified event to all listeners.
*
* <h4>Example</h4>
*
* // Use a string event
* this.dispatchEvent("complete");
*
* // Use an Event instance
* var event = new createjs.Event("progress");
* this.dispatchEvent(event);
*
* @method dispatchEvent
* @param {Object | String | Event} eventObj An object with a "type" property, or a string type.
* While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used,
* dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can
* be used to avoid event object instantiation for non-bubbling events that may not have any listeners.
* @param {Boolean} [bubbles] Specifies the `bubbles` value when a string was passed to eventObj.
* @param {Boolean} [cancelable] Specifies the `cancelable` value when a string was passed to eventObj.
* @return {Boolean} Returns false if `preventDefault()` was called on a cancelable event, true otherwise.
**/
p.dispatchEvent = function(eventObj, bubbles, cancelable) {
if (typeof eventObj == "string") {
// skip everything if there's no listeners and it doesn't bubble:
var listeners = this._listeners;
if (!bubbles && (!listeners || !listeners[eventObj])) { return true; }
eventObj = new createjs.Event(eventObj, bubbles, cancelable);
} else if (eventObj.target && eventObj.clone) {
// redispatching an active event object, so clone it:
eventObj = eventObj.clone();
}
// TODO: it would be nice to eliminate this. Maybe in favour of evtObj instanceof Event? Or !!evtObj.createEvent
try { eventObj.target = this; } catch (e) {} // try/catch allows redispatching of native events
if (!eventObj.bubbles || !this.parent) {
this._dispatchEvent(eventObj, 2);
} else {
var top=this, list=[top];
while (top.parent) { list.push(top = top.parent); }
var i, l=list.length;
// capture & atTarget
for (i=l-1; i>=0 && !eventObj.propagationStopped; i
list[i]._dispatchEvent(eventObj, 1+(i==0));
}
// bubbling
for (i=1; i<l && !eventObj.propagationStopped; i++) {
list[i]._dispatchEvent(eventObj, 3);
}
}
return !eventObj.defaultPrevented;
};
/**
* Indicates whether there is at least one listener for the specified event type.
* @method hasEventListener
* @param {String} type The string type of the event.
* @return {Boolean} Returns true if there is at least one listener for the specified event.
**/
p.hasEventListener = function(type) {
var listeners = this._listeners, captureListeners = this._captureListeners;
return !!((listeners && listeners[type]) || (captureListeners && captureListeners[type]));
};
/**
* Indicates whether there is at least one listener for the specified event type on this object or any of its
* ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the
* specified type is dispatched from this object, it will trigger at least one listener.
*
* This is similar to {{#crossLink "EventDispatcher/hasEventListener"}}{{/crossLink}}, but it searches the entire
* event flow for a listener, not just this object.
* @method willTrigger
* @param {String} type The string type of the event.
* @return {Boolean} Returns `true` if there is at least one listener for the specified event.
**/
p.willTrigger = function(type) {
var o = this;
while (o) {
if (o.hasEventListener(type)) { return true; }
o = o.parent;
}
return false;
};
/**
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[EventDispatcher]";
};
// private methods:
/**
* @method _dispatchEvent
* @param {Object | String | Event} eventObj
* @param {Object} eventPhase
* @protected
**/
p._dispatchEvent = function(eventObj, eventPhase) {
var l, listeners = (eventPhase==1) ? this._captureListeners : this._listeners;
if (eventObj && listeners) {
var arr = listeners[eventObj.type];
if (!arr||!(l=arr.length)) { return; }
try { eventObj.currentTarget = this; } catch (e) {}
try { eventObj.eventPhase = eventPhase; } catch (e) {}
eventObj.removed = false;
arr = arr.slice(); // to avoid issues with items being removed or added during the dispatch
for (var i=0; i<l && !eventObj.<API key>; i++) {
var o = arr[i];
if (o.handleEvent) { o.handleEvent(eventObj); }
else { o(eventObj); }
if (eventObj.removed) {
this.off(eventObj.type, o, eventPhase==1);
eventObj.removed = false;
}
}
}
};
createjs.EventDispatcher = EventDispatcher;
}());
//
// UID.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* Global utility for generating sequential unique ID numbers. The UID class uses a static interface (ex. <code>UID.get()</code>)
* and should not be instantiated.
* @class UID
* @static
**/
function UID() {
throw "UID cannot be instantiated";
}
// private static properties:
/**
* @property _nextID
* @type Number
* @protected
**/
UID._nextID = 0;
// public static methods:
/**
* Returns the next unique id.
* @method get
* @return {Number} The next unique id
* @static
**/
UID.get = function() {
return UID._nextID++;
};
createjs.UID = UID;
}());
//
// MouseEvent.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* Passed as the parameter to all mouse/pointer/touch related events. For a listing of mouse events and their properties,
* see the {{#crossLink "DisplayObject"}}{{/crossLink}} and {{#crossLink "Stage"}}{{/crossLink}} event listings.
* @class MouseEvent
* @param {String} type The event type.
* @param {Boolean} bubbles Indicates whether the event will bubble through the display list.
* @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled.
* @param {Number} stageX The normalized x position relative to the stage.
* @param {Number} stageY The normalized y position relative to the stage.
* @param {MouseEvent} nativeEvent The native DOM event related to this mouse event.
* @param {Number} pointerID The unique id for the pointer.
* @param {Boolean} primary Indicates whether this is the primary pointer in a multitouch environment.
* @param {Number} rawX The raw x position relative to the stage.
* @param {Number} rawY The raw y position relative to the stage.
* @param {DisplayObject} relatedTarget The secondary target for the event.
* @extends Event
* @constructor
**/
function MouseEvent(type, bubbles, cancelable, stageX, stageY, nativeEvent, pointerID, primary, rawX, rawY, relatedTarget) {
this.Event_constructor(type, bubbles, cancelable);
// public properties:
/**
* The normalized x position on the stage. This will always be within the range 0 to stage width.
* @property stageX
* @type Number
*/
this.stageX = stageX;
/**
* The normalized y position on the stage. This will always be within the range 0 to stage height.
* @property stageY
* @type Number
**/
this.stageY = stageY;
/**
* The raw x position relative to the stage. Normally this will be the same as the stageX value, unless
* stage.mouseMoveOutside is true and the pointer is outside of the stage bounds.
* @property rawX
* @type Number
*/
this.rawX = (rawX==null)?stageX:rawX;
/**
* The raw y position relative to the stage. Normally this will be the same as the stageY value, unless
* stage.mouseMoveOutside is true and the pointer is outside of the stage bounds.
* @property rawY
* @type Number
*/
this.rawY = (rawY==null)?stageY:rawY;
/**
* The native MouseEvent generated by the browser. The properties and API for this
* event may differ between browsers. This property will be null if the
* EaselJS property was not directly generated from a native MouseEvent.
* @property nativeEvent
* @type HtmlMouseEvent
* @default null
**/
this.nativeEvent = nativeEvent;
/**
* The unique id for the pointer (touch point or cursor). This will be either -1 for the mouse, or the system
* supplied id value.
* @property pointerID
* @type {Number}
*/
this.pointerID = pointerID;
/**
* Indicates whether this is the primary pointer in a multitouch environment. This will always be true for the mouse.
* For touch pointers, the first pointer in the current stack will be considered the primary pointer.
* @property primary
* @type {Boolean}
*/
this.primary = !!primary;
/**
* The secondary target for the event, if applicable. This is used for mouseout/rollout
* events to indicate the object that the mouse entered from, mouseover/rollover for the object the mouse exited,
* and stagemousedown/stagemouseup events for the object that was the under the cursor, if any.
*
* Only valid interaction targets will be returned (ie. objects with mouse listeners or a cursor set).
* @property relatedTarget
* @type {DisplayObject}
*/
this.relatedTarget = relatedTarget;
}
var p = createjs.extend(MouseEvent, createjs.Event);
// TODO: deprecated
// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.
// getter / setters:
/**
* Returns the x position of the mouse in the local coordinate system of the current target (ie. the dispatcher).
* @property localX
* @type {Number}
* @readonly
*/
p._get_localX = function() {
return this.currentTarget.globalToLocal(this.rawX, this.rawY).x;
};
/**
* Returns the y position of the mouse in the local coordinate system of the current target (ie. the dispatcher).
* @property localY
* @type {Number}
* @readonly
*/
p._get_localY = function() {
return this.currentTarget.globalToLocal(this.rawX, this.rawY).y;
};
/**
* Indicates whether the event was generated by a touch input (versus a mouse input).
* @property isTouch
* @type {Boolean}
* @readonly
*/
p._get_isTouch = function() {
return this.pointerID !== -1;
};
try {
Object.defineProperties(p, {
localX: { get: p._get_localX },
localY: { get: p._get_localY },
isTouch: { get: p._get_isTouch }
});
} catch (e) {} // TODO: use Log
// public methods:
/**
* Returns a clone of the MouseEvent instance.
* @method clone
* @return {MouseEvent} a clone of the MouseEvent instance.
**/
p.clone = function() {
return new MouseEvent(this.type, this.bubbles, this.cancelable, this.stageX, this.stageY, this.nativeEvent, this.pointerID, this.primary, this.rawX, this.rawY);
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[MouseEvent (type="+this.type+" stageX="+this.stageX+" stageY="+this.stageY+")]";
};
createjs.MouseEvent = createjs.promote(MouseEvent, "Event");
}());
//
// Matrix2D.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* Represents an affine transformation matrix, and provides tools for constructing and concatenating matrices.
*
* This matrix can be visualized as:
*
* [ a c tx
* b d ty
* 0 0 1 ]
*
* Note the locations of b and c.
*
* @class Matrix2D
* @param {Number} [a=1] Specifies the a property for the new matrix.
* @param {Number} [b=0] Specifies the b property for the new matrix.
* @param {Number} [c=0] Specifies the c property for the new matrix.
* @param {Number} [d=1] Specifies the d property for the new matrix.
* @param {Number} [tx=0] Specifies the tx property for the new matrix.
* @param {Number} [ty=0] Specifies the ty property for the new matrix.
* @constructor
**/
function Matrix2D(a, b, c, d, tx, ty) {
this.setValues(a,b,c,d,tx,ty);
// public properties:
// assigned in the setValues method.
/**
* Position (0, 0) in a 3x3 affine transformation matrix.
* @property a
* @type Number
**/
/**
* Position (0, 1) in a 3x3 affine transformation matrix.
* @property b
* @type Number
**/
/**
* Position (1, 0) in a 3x3 affine transformation matrix.
* @property c
* @type Number
**/
/**
* Position (1, 1) in a 3x3 affine transformation matrix.
* @property d
* @type Number
**/
/**
* Position (2, 0) in a 3x3 affine transformation matrix.
* @property tx
* @type Number
**/
/**
* Position (2, 1) in a 3x3 affine transformation matrix.
* @property ty
* @type Number
**/
}
var p = Matrix2D.prototype;
/**
* <strong>REMOVED</strong>. Removed in favor of using `<API key>`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// constants:
/**
* Multiplier for converting degrees to radians. Used internally by Matrix2D.
* @property DEG_TO_RAD
* @static
* @final
* @type Number
* @readonly
**/
Matrix2D.DEG_TO_RAD = Math.PI/180;
// static public properties:
/**
* An identity matrix, representing a null transformation.
* @property identity
* @static
* @type Matrix2D
* @readonly
**/
Matrix2D.identity = null; // set at bottom of class definition.
// public methods:
/**
* Sets the specified values on this instance.
* @method setValues
* @param {Number} [a=1] Specifies the a property for the new matrix.
* @param {Number} [b=0] Specifies the b property for the new matrix.
* @param {Number} [c=0] Specifies the c property for the new matrix.
* @param {Number} [d=1] Specifies the d property for the new matrix.
* @param {Number} [tx=0] Specifies the tx property for the new matrix.
* @param {Number} [ty=0] Specifies the ty property for the new matrix.
* @return {Matrix2D} This instance. Useful for chaining method calls.
*/
p.setValues = function(a, b, c, d, tx, ty) {
// don't forget to update docs in the constructor if these change:
this.a = (a == null) ? 1 : a;
this.b = b || 0;
this.c = c || 0;
this.d = (d == null) ? 1 : d;
this.tx = tx || 0;
this.ty = ty || 0;
return this;
};
/**
* Appends the specified matrix properties to this matrix. All parameters are required.
* This is the equivalent of multiplying `(this matrix) * (specified matrix)`.
* @method append
* @param {Number} a
* @param {Number} b
* @param {Number} c
* @param {Number} d
* @param {Number} tx
* @param {Number} ty
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.append = function(a, b, c, d, tx, ty) {
var a1 = this.a;
var b1 = this.b;
var c1 = this.c;
var d1 = this.d;
if (a != 1 || b != 0 || c != 0 || d != 1) {
this.a = a1*a+c1*b;
this.b = b1*a+d1*b;
this.c = a1*c+c1*d;
this.d = b1*c+d1*d;
}
this.tx = a1*tx+c1*ty+this.tx;
this.ty = b1*tx+d1*ty+this.ty;
return this;
};
/**
* Prepends the specified matrix properties to this matrix.
* This is the equivalent of multiplying `(specified matrix) * (this matrix)`.
* All parameters are required.
* @method prepend
* @param {Number} a
* @param {Number} b
* @param {Number} c
* @param {Number} d
* @param {Number} tx
* @param {Number} ty
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.prepend = function(a, b, c, d, tx, ty) {
var a1 = this.a;
var c1 = this.c;
var tx1 = this.tx;
this.a = a*a1+c*this.b;
this.b = b*a1+d*this.b;
this.c = a*c1+c*this.d;
this.d = b*c1+d*this.d;
this.tx = a*tx1+c*this.ty+tx;
this.ty = b*tx1+d*this.ty+ty;
return this;
};
/**
* Appends the specified matrix to this matrix.
* This is the equivalent of multiplying `(this matrix) * (specified matrix)`.
* @method appendMatrix
* @param {Matrix2D} matrix
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.appendMatrix = function(matrix) {
return this.append(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
};
/**
* Prepends the specified matrix to this matrix.
* This is the equivalent of multiplying `(specified matrix) * (this matrix)`.
* For example, you could calculate the combined transformation for a child object using:
*
* var o = myDisplayObject;
* var mtx = o.getMatrix();
* while (o = o.parent) {
* // prepend each parent's transformation in turn:
* o.prependMatrix(o.getMatrix());
* }
* @method prependMatrix
* @param {Matrix2D} matrix
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.prependMatrix = function(matrix) {
return this.prepend(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
};
/**
* Generates matrix properties from the specified display object transform properties, and appends them to this matrix.
* For example, you can use this to generate a matrix representing the transformations of a display object:
*
* var mtx = new Matrix2D();
* mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation);
* @method appendTransform
* @param {Number} x
* @param {Number} y
* @param {Number} scaleX
* @param {Number} scaleY
* @param {Number} rotation
* @param {Number} skewX
* @param {Number} skewY
* @param {Number} regX Optional.
* @param {Number} regY Optional.
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.appendTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) {
if (rotation%360) {
var r = rotation*Matrix2D.DEG_TO_RAD;
var cos = Math.cos(r);
var sin = Math.sin(r);
} else {
cos = 1;
sin = 0;
}
if (skewX || skewY) {
// TODO: can this be combined into a single append operation?
skewX *= Matrix2D.DEG_TO_RAD;
skewY *= Matrix2D.DEG_TO_RAD;
this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y);
this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0);
} else {
this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y);
}
if (regX || regY) {
// append the registration offset:
this.tx -= regX*this.a+regY*this.c;
this.ty -= regX*this.b+regY*this.d;
}
return this;
};
/**
* Generates matrix properties from the specified display object transform properties, and prepends them to this matrix.
* For example, you could calculate the combined transformation for a child object using:
*
* var o = myDisplayObject;
* var mtx = new createjs.Matrix2D();
* do {
* // prepend each parent's transformation in turn:
* mtx.prependTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY);
* } while (o = o.parent);
*
* Note that the above example would not account for {{#crossLink "DisplayObject/transformMatrix:property"}}{{/crossLink}}
* values. See {{#crossLink "Matrix2D/prependMatrix"}}{{/crossLink}} for an example that does.
* @method prependTransform
* @param {Number} x
* @param {Number} y
* @param {Number} scaleX
* @param {Number} scaleY
* @param {Number} rotation
* @param {Number} skewX
* @param {Number} skewY
* @param {Number} regX Optional.
* @param {Number} regY Optional.
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.prependTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) {
if (rotation%360) {
var r = rotation*Matrix2D.DEG_TO_RAD;
var cos = Math.cos(r);
var sin = Math.sin(r);
} else {
cos = 1;
sin = 0;
}
if (regX || regY) {
// prepend the registration offset:
this.tx -= regX; this.ty -= regY;
}
if (skewX || skewY) {
// TODO: can this be combined into a single prepend operation?
skewX *= Matrix2D.DEG_TO_RAD;
skewY *= Matrix2D.DEG_TO_RAD;
this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0);
this.prepend(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y);
} else {
this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y);
}
return this;
};
/**
* Applies a clockwise rotation transformation to the matrix.
* @method rotate
* @param {Number} angle The angle to rotate by, in degrees. To use a value in radians, multiply it by `180/Math.PI`.
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.rotate = function(angle) {
angle = angle*Matrix2D.DEG_TO_RAD;
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var a1 = this.a;
var b1 = this.b;
this.a = a1*cos+this.c*sin;
this.b = b1*cos+this.d*sin;
this.c = -a1*sin+this.c*cos;
this.d = -b1*sin+this.d*cos;
return this;
};
/**
* Applies a skew transformation to the matrix.
* @method skew
* @param {Number} skewX The amount to skew horizontally in degrees. To use a value in radians, multiply it by `180/Math.PI`.
* @param {Number} skewY The amount to skew vertically in degrees.
* @return {Matrix2D} This matrix. Useful for chaining method calls.
*/
p.skew = function(skewX, skewY) {
skewX = skewX*Matrix2D.DEG_TO_RAD;
skewY = skewY*Matrix2D.DEG_TO_RAD;
this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), 0, 0);
return this;
};
/**
* Applies a scale transformation to the matrix.
* @method scale
* @param {Number} x The amount to scale horizontally. E.G. a value of 2 will double the size in the X direction, and 0.5 will halve it.
* @param {Number} y The amount to scale vertically.
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.scale = function(x, y) {
this.a *= x;
this.b *= x;
this.c *= y;
this.d *= y;
//this.tx *= x;
//this.ty *= y;
return this;
};
/**
* Translates the matrix on the x and y axes.
* @method translate
* @param {Number} x
* @param {Number} y
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.translate = function(x, y) {
this.tx += this.a*x + this.c*y;
this.ty += this.b*x + this.d*y;
return this;
};
/**
* Sets the properties of the matrix to those of an identity matrix (one that applies a null transformation).
* @method identity
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.identity = function() {
this.a = this.d = 1;
this.b = this.c = this.tx = this.ty = 0;
return this;
};
/**
* Inverts the matrix, causing it to perform the opposite transformation.
* @method invert
* @return {Matrix2D} This matrix. Useful for chaining method calls.
**/
p.invert = function() {
var a1 = this.a;
var b1 = this.b;
var c1 = this.c;
var d1 = this.d;
var tx1 = this.tx;
var n = a1*d1-b1*c1;
this.a = d1/n;
this.b = -b1/n;
this.c = -c1/n;
this.d = a1/n;
this.tx = (c1*this.ty-d1*tx1)/n;
this.ty = -(a1*this.ty-b1*tx1)/n;
return this;
};
/**
* Returns true if the matrix is an identity matrix.
* @method isIdentity
* @return {Boolean}
**/
p.isIdentity = function() {
return this.tx === 0 && this.ty === 0 && this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1;
};
/**
* Returns true if this matrix is equal to the specified matrix (all property values are equal).
* @method equals
* @param {Matrix2D} matrix The matrix to compare.
* @return {Boolean}
**/
p.equals = function(matrix) {
return this.tx === matrix.tx && this.ty === matrix.ty && this.a === matrix.a && this.b === matrix.b && this.c === matrix.c && this.d === matrix.d;
};
/**
* Transforms a point according to this matrix.
* @method transformPoint
* @param {Number} x The x component of the point to transform.
* @param {Number} y The y component of the point to transform.
* @param {Point | Object} [pt] An object to copy the result into. If omitted a generic object with x/y properties will be returned.
* @return {Point} This matrix. Useful for chaining method calls.
**/
p.transformPoint = function(x, y, pt) {
pt = pt||{};
pt.x = x*this.a+y*this.c+this.tx;
pt.y = x*this.b+y*this.d+this.ty;
return pt;
};
/**
* Decomposes the matrix into transform properties (x, y, scaleX, scaleY, and rotation). Note that these values
* may not match the transform properties you used to generate the matrix, though they will produce the same visual
* results.
* @method decompose
* @param {Object} target The object to apply the transform properties to. If null, then a new object will be returned.
* @return {Object} The target, or a new generic object with the transform properties applied.
*/
p.decompose = function(target) {
// TODO: it would be nice to be able to solve for whether the matrix can be decomposed into only scale/rotation even when scale is negative
if (target == null) { target = {}; }
target.x = this.tx;
target.y = this.ty;
target.scaleX = Math.sqrt(this.a * this.a + this.b * this.b);
target.scaleY = Math.sqrt(this.c * this.c + this.d * this.d);
var skewX = Math.atan2(-this.c, this.d);
var skewY = Math.atan2(this.b, this.a);
var delta = Math.abs(1-skewX/skewY);
if (delta < 0.00001) { // effectively identical, can use rotation:
target.rotation = skewY/Matrix2D.DEG_TO_RAD;
if (this.a < 0 && this.d >= 0) {
target.rotation += (target.rotation <= 0) ? 180 : -180;
}
target.skewX = target.skewY = 0;
} else {
target.skewX = skewX/Matrix2D.DEG_TO_RAD;
target.skewY = skewY/Matrix2D.DEG_TO_RAD;
}
return target;
};
/**
* Copies all properties from the specified matrix to this matrix.
* @method copy
* @param {Matrix2D} matrix The matrix to copy properties from.
* @return {Matrix2D} This matrix. Useful for chaining method calls.
*/
p.copy = function(matrix) {
return this.setValues(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
};
/**
* Returns a clone of the Matrix2D instance.
* @method clone
* @return {Matrix2D} a clone of the Matrix2D instance.
**/
p.clone = function() {
return new Matrix2D(this.a, this.b, this.c, this.d, this.tx, this.ty);
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Matrix2D (a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+")]";
};
// this has to be populated after the class is defined:
Matrix2D.identity = new Matrix2D();
createjs.Matrix2D = Matrix2D;
}());
//
// DisplayProps.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
/**
* Used for calculating and encapsulating display related properties.
* @class DisplayProps
* @param {Number} [visible=true] Visible value.
* @param {Number} [alpha=1] Alpha value.
* @param {Number} [shadow=null] A Shadow instance or null.
* @param {Number} [compositeOperation=null] A compositeOperation value or null.
* @param {Number} [matrix] A transformation matrix. Defaults to a new identity matrix.
* @constructor
**/
function DisplayProps(visible, alpha, shadow, compositeOperation, matrix) {
this.setValues(visible, alpha, shadow, compositeOperation, matrix);
// public properties:
// assigned in the setValues method.
/**
* Property representing the alpha that will be applied to a display object.
* @property alpha
* @type Number
**/
/**
* Property representing the shadow that will be applied to a display object.
* @property shadow
* @type Shadow
**/
/**
* Property representing the value for visible that will be applied to a display object.
* @property visible
* @type Boolean
**/
/**
* The transformation matrix that will be applied to a display object.
* @property matrix
* @type Matrix2D
**/
}
var p = DisplayProps.prototype;
// initialization:
/**
* Reinitializes the instance with the specified values.
* @method setValues
* @param {Number} [visible=true] Visible value.
* @param {Number} [alpha=1] Alpha value.
* @param {Number} [shadow=null] A Shadow instance or null.
* @param {Number} [compositeOperation=null] A compositeOperation value or null.
* @param {Number} [matrix] A transformation matrix. Defaults to an identity matrix.
* @return {DisplayProps} This instance. Useful for chaining method calls.
* @chainable
*/
p.setValues = function (visible, alpha, shadow, compositeOperation, matrix) {
this.visible = visible == null ? true : !!visible;
this.alpha = alpha == null ? 1 : alpha;
this.shadow = shadow;
this.compositeOperation = compositeOperation;
this.matrix = matrix || (this.matrix&&this.matrix.identity()) || new createjs.Matrix2D();
return this;
};
// public methods:
/**
* Appends the specified display properties. This is generally used to apply a child's properties its parent's.
* @method append
* @param {Boolean} visible desired visible value
* @param {Number} alpha desired alpha value
* @param {Shadow} shadow desired shadow value
* @param {String} compositeOperation desired composite operation value
* @param {Matrix2D} [matrix] a Matrix2D instance
* @return {DisplayProps} This instance. Useful for chaining method calls.
* @chainable
*/
p.append = function(visible, alpha, shadow, compositeOperation, matrix) {
this.alpha *= alpha;
this.shadow = shadow || this.shadow;
this.compositeOperation = compositeOperation || this.compositeOperation;
this.visible = this.visible && visible;
matrix&&this.matrix.appendMatrix(matrix);
return this;
};
/**
* Prepends the specified display properties. This is generally used to apply a parent's properties to a child's.
* For example, to get the combined display properties that would be applied to a child, you could use:
*
* var o = myDisplayObject;
* var props = new createjs.DisplayProps();
* do {
* // prepend each parent's props in turn:
* props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation, o.getMatrix());
* } while (o = o.parent);
*
* @method prepend
* @param {Boolean} visible desired visible value
* @param {Number} alpha desired alpha value
* @param {Shadow} shadow desired shadow value
* @param {String} compositeOperation desired composite operation value
* @param {Matrix2D} [matrix] a Matrix2D instance
* @return {DisplayProps} This instance. Useful for chaining method calls.
* @chainable
*/
p.prepend = function(visible, alpha, shadow, compositeOperation, matrix) {
this.alpha *= alpha;
this.shadow = this.shadow || shadow;
this.compositeOperation = this.compositeOperation || compositeOperation;
this.visible = this.visible && visible;
matrix&&this.matrix.prependMatrix(matrix);
return this;
};
/**
* Resets this instance and its matrix to default values.
* @method identity
* @return {DisplayProps} This instance. Useful for chaining method calls.
* @chainable
*/
p.identity = function() {
this.visible = true;
this.alpha = 1;
this.shadow = this.compositeOperation = null;
this.matrix.identity();
return this;
};
/**
* Returns a clone of the DisplayProps instance. Clones the associated matrix.
* @method clone
* @return {DisplayProps} a clone of the DisplayProps instance.
**/
p.clone = function() {
return new DisplayProps(this.alpha, this.shadow, this.compositeOperation, this.visible, this.matrix.clone());
};
// private methods:
createjs.DisplayProps = DisplayProps;
})();
//
// Rectangle.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* Represents a rectangle as defined by the points (x, y) and (x+width, y+height).
*
* <h4>Example</h4>
*
* var rect = new createjs.Rectangle(0, 0, 100, 100);
*
* @class Rectangle
* @param {Number} [x=0] X position.
* @param {Number} [y=0] Y position.
* @param {Number} [width=0] The width of the Rectangle.
* @param {Number} [height=0] The height of the Rectangle.
* @constructor
**/
function Rectangle(x, y, width, height) {
this.setValues(x, y, width, height);
// public properties:
// assigned in the setValues method.
/**
* X position.
* @property x
* @type Number
**/
/**
* Y position.
* @property y
* @type Number
**/
/**
* Width.
* @property width
* @type Number
**/
/**
* Height.
* @property height
* @type Number
**/
}
var p = Rectangle.prototype;
/**
* <strong>REMOVED</strong>. Removed in favor of using `<API key>`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// public methods:
/**
* Sets the specified values on this instance.
* @method setValues
* @param {Number} [x=0] X position.
* @param {Number} [y=0] Y position.
* @param {Number} [width=0] The width of the Rectangle.
* @param {Number} [height=0] The height of the Rectangle.
* @return {Rectangle} This instance. Useful for chaining method calls.
* @chainable
*/
p.setValues = function(x, y, width, height) {
// don't forget to update docs in the constructor if these change:
this.x = x||0;
this.y = y||0;
this.width = width||0;
this.height = height||0;
return this;
};
/**
* Extends the rectangle's bounds to include the described point or rectangle.
* @method extend
* @param {Number} x X position of the point or rectangle.
* @param {Number} y Y position of the point or rectangle.
* @param {Number} [width=0] The width of the rectangle.
* @param {Number} [height=0] The height of the rectangle.
* @return {Rectangle} This instance. Useful for chaining method calls.
* @chainable
*/
p.extend = function(x, y, width, height) {
width = width||0;
height = height||0;
if (x+width > this.x+this.width) { this.width = x+width-this.x; }
if (y+height > this.y+this.height) { this.height = y+height-this.y; }
if (x < this.x) { this.width += this.x-x; this.x = x; }
if (y < this.y) { this.height += this.y-y; this.y = y; }
return this;
};
/**
* Adds the specified padding to the rectangle's bounds.
* @method pad
* @param {Number} top
* @param {Number} left
* @param {Number} right
* @param {Number} bottom
* @return {Rectangle} This instance. Useful for chaining method calls.
* @chainable
*/
p.pad = function(top, left, bottom, right) {
this.x -= left;
this.y -= top;
this.width += left+right;
this.height += top+bottom;
return this;
};
/**
* Copies all properties from the specified rectangle to this rectangle.
* @method copy
* @param {Rectangle} rectangle The rectangle to copy properties from.
* @return {Rectangle} This rectangle. Useful for chaining method calls.
* @chainable
*/
p.copy = function(rectangle) {
return this.setValues(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
};
/**
* Returns true if this rectangle fully encloses the described point or rectangle.
* @method contains
* @param {Number} x X position of the point or rectangle.
* @param {Number} y Y position of the point or rectangle.
* @param {Number} [width=0] The width of the rectangle.
* @param {Number} [height=0] The height of the rectangle.
* @return {Boolean} True if the described point or rectangle is contained within this rectangle.
*/
p.contains = function(x, y, width, height) {
width = width||0;
height = height||0;
return (x >= this.x && x+width <= this.x+this.width && y >= this.y && y+height <= this.y+this.height);
};
/**
* Returns a new rectangle which contains this rectangle and the specified rectangle.
* @method union
* @param {Rectangle} rect The rectangle to calculate a union with.
* @return {Rectangle} A new rectangle describing the union.
*/
p.union = function(rect) {
return this.clone().extend(rect.x, rect.y, rect.width, rect.height);
};
/**
* Returns a new rectangle which describes the intersection (overlap) of this rectangle and the specified rectangle,
* or null if they do not intersect.
* @method intersection
* @param {Rectangle} rect The rectangle to calculate an intersection with.
* @return {Rectangle} A new rectangle describing the intersection or null.
*/
p.intersection = function(rect) {
var x1 = rect.x, y1 = rect.y, x2 = x1+rect.width, y2 = y1+rect.height;
if (this.x > x1) { x1 = this.x; }
if (this.y > y1) { y1 = this.y; }
if (this.x + this.width < x2) { x2 = this.x + this.width; }
if (this.y + this.height < y2) { y2 = this.y + this.height; }
return (x2 <= x1 || y2 <= y1) ? null : new Rectangle(x1, y1, x2-x1, y2-y1);
};
/**
* Returns true if the specified rectangle intersects (has any overlap) with this rectangle.
* @method intersects
* @param {Rectangle} rect The rectangle to compare.
* @return {Boolean} True if the rectangles intersect.
*/
p.intersects = function(rect) {
return (rect.x <= this.x+this.width && this.x <= rect.x+rect.width && rect.y <= this.y+this.height && this.y <= rect.y + rect.height);
};
/**
* Returns true if the width or height are equal or less than 0.
* @method isEmpty
* @return {Boolean} True if the rectangle is empty.
*/
p.isEmpty = function() {
return this.width <= 0 || this.height <= 0;
};
/**
* Returns a clone of the Rectangle instance.
* @method clone
* @return {Rectangle} a clone of the Rectangle instance.
**/
p.clone = function() {
return new Rectangle(this.x, this.y, this.width, this.height);
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")]";
};
createjs.Rectangle = Rectangle;
}());
//
// Graphics.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* The Graphics class exposes an easy to use API for generating vector drawing instructions and drawing them to a
* specified context. Note that you can use Graphics without any dependency on the EaselJS framework by calling {{#crossLink "Graphics/draw"}}{{/crossLink}}
* directly, or it can be used with the {{#crossLink "Shape"}}{{/crossLink}} object to draw vector graphics within the
* context of an EaselJS display list.
*
* There are two approaches to working with Graphics object: calling methods on a Graphics instance (the "Graphics API"), or
* instantiating Graphics command objects and adding them to the graphics queue via {{#crossLink "Graphics/append"}}{{/crossLink}}.
* The former abstracts the latter, simplifying beginning and ending paths, fills, and strokes.
*
* var g = new createjs.Graphics();
* g.setStrokeStyle(1);
* g.beginStroke("#000000");
* g.beginFill("red");
* g.drawCircle(0,0,30);
*
* All drawing methods in Graphics return the Graphics instance, so they can be chained together. For example,
* the following line of code would generate the instructions to draw a rectangle with a red stroke and blue fill:
*
* myGraphics.beginStroke("red").beginFill("blue").drawRect(20, 20, 100, 50);
*
* Each graphics API call generates a command object (see below). The last command to be created can be accessed via
* {{#crossLink "Graphics/command:property"}}{{/crossLink}}:
*
* var fillCommand = myGraphics.beginFill("red").command;
* // ... later, update the fill style/color:
* fillCommand.style = "blue";
* // or change it to a bitmap fill:
* fillCommand.bitmap(myImage);
*
* For more direct control of rendering, you can instantiate and append command objects to the graphics queue directly. In this case, you
* need to manage path creation manually, and ensure that fill/stroke is applied to a defined path:
*
* // start a new path. Graphics.beginCmd is a reusable BeginPath instance:
* myGraphics.append(createjs.Graphics.beginCmd);
* // we need to define the path before applying the fill:
* var circle = new createjs.Graphics.Circle(0,0,30);
* myGraphics.append(circle);
* // fill the path we just defined:
* var fill = new createjs.Graphics.Fill("red");
* myGraphics.append(fill);
*
* These approaches can be used together, for example to insert a custom command:
*
* myGraphics.beginFill("red");
* var customCommand = new CustomSpiralCommand(etc);
* myGraphics.append(customCommand);
* myGraphics.beginFill("blue");
* myGraphics.drawCircle(0, 0, 30);
*
* See {{#crossLink "Graphics/append"}}{{/crossLink}} for more info on creating custom commands.
*
* <h4>Tiny API</h4>
* The Graphics class also includes a "tiny API", which is one or two-letter methods that are shortcuts for all of the
* Graphics methods. These methods are great for creating compact instructions, and is used by the Toolkit for CreateJS
* to generate readable code. All tiny methods are marked as protected, so you can view them by enabling protected
* descriptions in the docs.
*
* <table>
* <tr><td><b>Tiny</b></td><td><b>Method</b></td><td><b>Tiny</b></td><td><b>Method</b></td></tr>
* <tr><td>mt</td><td>{{#crossLink "Graphics/moveTo"}}{{/crossLink}} </td>
* <td>lt</td> <td>{{#crossLink "Graphics/lineTo"}}{{/crossLink}}</td></tr>
* <tr><td>a/at</td><td>{{#crossLink "Graphics/arc"}}{{/crossLink}} / {{#crossLink "Graphics/arcTo"}}{{/crossLink}} </td>
* <td>bt</td><td>{{#crossLink "Graphics/bezierCurveTo"}}{{/crossLink}} </td></tr>
* <tr><td>qt</td><td>{{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} (also curveTo)</td>
* <td>r</td><td>{{#crossLink "Graphics/rect"}}{{/crossLink}} </td></tr>
* <tr><td>cp</td><td>{{#crossLink "Graphics/closePath"}}{{/crossLink}} </td>
* <td>c</td><td>{{#crossLink "Graphics/clear"}}{{/crossLink}} </td></tr>
* <tr><td>f</td><td>{{#crossLink "Graphics/beginFill"}}{{/crossLink}} </td>
* <td>lf</td><td>{{#crossLink "Graphics/<API key>"}}{{/crossLink}} </td></tr>
* <tr><td>rf</td><td>{{#crossLink "Graphics/<API key>"}}{{/crossLink}} </td>
* <td>bf</td><td>{{#crossLink "Graphics/beginBitmapFill"}}{{/crossLink}} </td></tr>
* <tr><td>ef</td><td>{{#crossLink "Graphics/endFill"}}{{/crossLink}} </td>
* <td>ss / sd</td><td>{{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} / {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}} </td></tr>
* <tr><td>s</td><td>{{#crossLink "Graphics/beginStroke"}}{{/crossLink}} </td>
* <td>ls</td><td>{{#crossLink "Graphics/<API key>"}}{{/crossLink}} </td></tr>
* <tr><td>rs</td><td>{{#crossLink "Graphics/<API key>"}}{{/crossLink}} </td>
* <td>bs</td><td>{{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}} </td></tr>
* <tr><td>es</td><td>{{#crossLink "Graphics/endStroke"}}{{/crossLink}} </td>
* <td>dr</td><td>{{#crossLink "Graphics/drawRect"}}{{/crossLink}} </td></tr>
* <tr><td>rr</td><td>{{#crossLink "Graphics/drawRoundRect"}}{{/crossLink}} </td>
* <td>rc</td><td>{{#crossLink "Graphics/<API key>"}}{{/crossLink}} </td></tr>
* <tr><td>dc</td><td>{{#crossLink "Graphics/drawCircle"}}{{/crossLink}} </td>
* <td>de</td><td>{{#crossLink "Graphics/drawEllipse"}}{{/crossLink}} </td></tr>
* <tr><td>dp</td><td>{{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} </td>
* <td>p</td><td>{{#crossLink "Graphics/decodePath"}}{{/crossLink}} </td></tr>
* </table>
*
* Here is the above example, using the tiny API instead.
*
* myGraphics.s("red").f("blue").r(20, 20, 100, 50);
*
* @class Graphics
* @constructor
**/
function Graphics() {
// public properties
/**
* Holds a reference to the last command that was created or appended. For example, you could retain a reference
* to a Fill command in order to dynamically update the color later by using:
* myFill = myGraphics.beginFill("red").command;
* // update color later:
* myFill.style = "yellow";
* @property command
* @type Object
**/
this.command = null;
// private properties
/**
* @property _stroke
* @protected
* @type {Stroke}
**/
this._stroke = null;
/**
* @property _strokeStyle
* @protected
* @type {StrokeStyle}
**/
this._strokeStyle = null;
/**
* @property _oldStrokeStyle
* @protected
* @type {StrokeStyle}
**/
this._oldStrokeStyle = null;
/**
* @property _strokeDash
* @protected
* @type {StrokeDash}
**/
this._strokeDash = null;
/**
* @property _oldStrokeDash
* @protected
* @type {StrokeDash}
**/
this._oldStrokeDash = null;
/**
* @property _strokeIgnoreScale
* @protected
* @type Boolean
**/
this._strokeIgnoreScale = false;
/**
* @property _fill
* @protected
* @type {Fill}
**/
this._fill = null;
/**
* @property _instructions
* @protected
* @type {Array}
**/
this._instructions = [];
/**
* Indicates the last instruction index that was committed.
* @property _commitIndex
* @protected
* @type {Number}
**/
this._commitIndex = 0;
/**
* Uncommitted instructions.
* @property _activeInstructions
* @protected
* @type {Array}
**/
this._activeInstructions = [];
/**
* This indicates that there have been changes to the activeInstruction list since the last updateInstructions call.
* @property _dirty
* @protected
* @type {Boolean}
* @default false
**/
this._dirty = false;
/**
* Index to draw from if a store operation has happened.
* @property _storeIndex
* @protected
* @type {Number}
* @default 0
**/
this._storeIndex = 0;
// setup:
this.clear();
}
var p = Graphics.prototype;
var G = Graphics; // shortcut
/**
* <strong>REMOVED</strong>. Removed in favor of using `<API key>`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// static public methods:
/**
* Returns a CSS compatible color string based on the specified RGB numeric color values in the format
* "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)". For example,
*
* createjs.Graphics.getRGB(50, 100, 150, 0.5);
* // Returns "rgba(50,100,150,0.5)"
*
* It also supports passing a single hex color value as the first param, and an optional alpha value as the second
* param. For example,
*
* createjs.Graphics.getRGB(0xFF00FF, 0.2);
* // Returns "rgba(255,0,255,0.2)"
*
* @method getRGB
* @static
* @param {Number} r The red component for the color, between 0 and 0xFF (255).
* @param {Number} g The green component for the color, between 0 and 0xFF (255).
* @param {Number} b The blue component for the color, between 0 and 0xFF (255).
* @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque.
* @return {String} A CSS compatible color string based on the specified RGB numeric color values in the format
* "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)".
**/
Graphics.getRGB = function(r, g, b, alpha) {
if (r != null && b == null) {
alpha = g;
b = r&0xFF;
g = r>>8&0xFF;
r = r>>16&0xFF;
}
if (alpha == null) {
return "rgb("+r+","+g+","+b+")";
} else {
return "rgba("+r+","+g+","+b+","+alpha+")";
}
};
/**
* Returns a CSS compatible color string based on the specified HSL numeric color values in the format "hsla(360,100,100,1.0)",
* or if alpha is null then in the format "hsl(360,100,100)".
*
* createjs.Graphics.getHSL(150, 100, 70);
* // Returns "hsl(150,100,70)"
*
* @method getHSL
* @static
* @param {Number} hue The hue component for the color, between 0 and 360.
* @param {Number} saturation The saturation component for the color, between 0 and 100.
* @param {Number} lightness The lightness component for the color, between 0 and 100.
* @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque.
* @return {String} A CSS compatible color string based on the specified HSL numeric color values in the format
* "hsla(360,100,100,1.0)", or if alpha is null then in the format "hsl(360,100,100)".
**/
Graphics.getHSL = function(hue, saturation, lightness, alpha) {
if (alpha == null) {
return "hsl("+(hue%360)+","+saturation+"%,"+lightness+"%)";
} else {
return "hsla("+(hue%360)+","+saturation+"%,"+lightness+"%,"+alpha+")";
}
};
// static properties:
/**
* A reusable instance of {{#crossLink "Graphics/BeginPath"}}{{/crossLink}} to avoid
* unnecessary instantiation.
* @property beginCmd
* @type {Graphics.BeginPath}
* @static
**/
// defined at the bottom of this file.
/**
* Map of Base64 characters to values. Used by {{#crossLink "Graphics/decodePath"}}{{/crossLink}}.
* @property BASE_64
* @static
* @final
* @readonly
* @type {Object}
**/
Graphics.BASE_64 = {"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,"H":7,"I":8,"J":9,"K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T":19,"U":20,"V":21,"W":22,"X":23,"Y":24,"Z":25,"a":26,"b":27,"c":28,"d":29,"e":30,"f":31,"g":32,"h":33,"i":34,"j":35,"k":36,"l":37,"m":38,"n":39,"o":40,"p":41,"q":42,"r":43,"s":44,"t":45,"u":46,"v":47,"w":48,"x":49,"y":50,"z":51,"0":52,"1":53,"2":54,"3":55,"4":56,"5":57,"6":58,"7":59,"8":60,"9":61,"+":62,"/":63};
/**
* Maps numeric values for the caps parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to
* corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to
* "butt", 1 to "round", and 2 to "square".
* For example, to set the line caps to "square":
*
* myGraphics.ss(16, 2);
*
* @property STROKE_CAPS_MAP
* @static
* @final
* @readonly
* @type {Array}
**/
Graphics.STROKE_CAPS_MAP = ["butt", "round", "square"];
/**
* Maps numeric values for the joints parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to
* corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to
* "miter", 1 to "round", and 2 to "bevel".
* For example, to set the line joints to "bevel":
*
* myGraphics.ss(16, 0, 2);
*
* @property STROKE_JOINTS_MAP
* @static
* @final
* @readonly
* @type {Array}
**/
Graphics.STROKE_JOINTS_MAP = ["miter", "round", "bevel"];
/**
* @property _ctx
* @static
* @protected
* @type {<API key>}
**/
var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"));
if (canvas.getContext) {
Graphics._ctx = canvas.getContext("2d");
canvas.width = canvas.height = 1;
}
// getter / setters:
/**
* Use the {{#crossLink "Graphics/instructions:property"}}{{/crossLink}} property instead.
* @method getInstructions
* @return {Array}
* @deprecated
**/
p.getInstructions = function() {
this._updateInstructions();
return this._instructions;
};
/**
* Returns the graphics instructions array. Each entry is a graphics command object (ex. Graphics.Fill, Graphics.Rect)
* Modifying the returned array directly is not recommended, and is likely to result in unexpected behaviour.
*
* This property is mainly intended for introspection of the instructions (ex. for graphics export).
* @property instructions
* @type {Array}
* @readonly
**/
try {
Object.defineProperties(p, {
instructions: { get: p.getInstructions }
});
} catch (e) {}
// public methods:
/**
* Returns true if this Graphics instance has no drawing commands.
* @method isEmpty
* @return {Boolean} Returns true if this Graphics instance has no drawing commands.
**/
p.isEmpty = function() {
return !(this._instructions.length || this._activeInstructions.length);
};
/**
* Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform.
* Returns true if the draw was handled (useful for overriding functionality).
*
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method draw
* @param {<API key>} ctx The canvas 2D context object to draw into.
* @param {Object} data Optional data that is passed to graphics command exec methods. When called from a Shape instance, the shape passes itself as the data parameter. This can be used by custom graphic commands to insert contextual data.
**/
p.draw = function(ctx, data) {
this._updateInstructions();
var instr = this._instructions;
for (var i=this._storeIndex, l=instr.length; i<l; i++) {
instr[i].exec(ctx, data);
}
};
/**
* Draws only the path described for this Graphics instance, skipping any non-path instructions, including fill and
* stroke descriptions. Used for <code>DisplayObject.mask</code> to draw the clipping path, for example.
*
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method drawAsPath
* @param {<API key>} ctx The canvas 2D context object to draw into.
**/
p.drawAsPath = function(ctx) {
this._updateInstructions();
var instr, instrs = this._instructions;
for (var i=this._storeIndex, l=instrs.length; i<l; i++) {
// the first command is always a beginPath command.
if ((instr = instrs[i]).path !== false) { instr.exec(ctx); }
}
};
// public methods that map directly to context 2D calls:
/**
* Moves the drawing point to the specified position. A tiny API method "mt" also exists.
* @method moveTo
* @param {Number} x The x coordinate the drawing point should move to.
* @param {Number} y The y coordinate the drawing point should move to.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls).
* @chainable
**/
p.moveTo = function(x, y) {
return this.append(new G.MoveTo(x,y), true);
};
p.lineTo = function(x, y) {
return this.append(new G.LineTo(x,y));
};
p.arcTo = function(x1, y1, x2, y2, radius) {
return this.append(new G.ArcTo(x1, y1, x2, y2, radius));
};
p.arc = function(x, y, radius, startAngle, endAngle, anticlockwise) {
return this.append(new G.Arc(x, y, radius, startAngle, endAngle, anticlockwise));
};
p.quadraticCurveTo = function(cpx, cpy, x, y) {
return this.append(new G.QuadraticCurveTo(cpx, cpy, x, y));
};
p.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
return this.append(new G.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y));
};
p.rect = function(x, y, w, h) {
return this.append(new G.Rect(x, y, w, h));
};
/**
* Closes the current path, effectively drawing a line from the current drawing point to the first drawing point specified
* since the fill or stroke was last set. A tiny API method "cp" also exists.
* @method closePath
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.closePath = function() {
return this._activeInstructions.length ? this.append(new G.ClosePath()) : this;
};
// public methods that roughly map to Flash graphics APIs:
/**
* Clears all drawing instructions, effectively resetting this Graphics instance. Any line and fill styles will need
* to be redefined to draw shapes following a clear call. A tiny API method "c" also exists.
* @method clear
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.clear = function() {
this._instructions.length = this._activeInstructions.length = this._commitIndex = 0;
this._strokeStyle = this._oldStrokeStyle = this._stroke = this._fill = this._strokeDash = this._oldStrokeDash = null;
this._dirty = this._strokeIgnoreScale = false;
return this;
};
/**
* Begins a fill with the specified color. This ends the current sub-path. A tiny API method "f" also exists.
* @method beginFill
* @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to
* null will result in no fill.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.beginFill = function(color) {
return this._setFill(color ? new G.Fill(color) : null);
};
/**
* Begins a linear gradient fill defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For
* example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a
* square to display it:
*
* myGraphics.<API key>(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120);
*
* A tiny API method "lf" also exists.
* @method <API key>
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient
* drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw
* the first color to 10% then interpolating to the second color at 90%.
* @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size.
* @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.<API key> = function(colors, ratios, x0, y0, x1, y1) {
return this._setFill(new G.Fill().linearGradient(colors, ratios, x0, y0, x1, y1));
};
/**
* Begins a radial gradient fill. This ends the current sub-path. For example, the following code defines a red to
* blue radial gradient centered at (100, 100), with a radius of 50, and draws a circle to display it:
*
* myGraphics.<API key>(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50).drawCircle(100, 100, 50);
*
* A tiny API method "rf" also exists.
* @method <API key>
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define
* a gradient drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1,
* 0.9] would draw the first color to 10% then interpolating to the second color at 90%.
* @param {Number} x0 Center position of the inner circle that defines the gradient.
* @param {Number} y0 Center position of the inner circle that defines the gradient.
* @param {Number} r0 Radius of the inner circle that defines the gradient.
* @param {Number} x1 Center position of the outer circle that defines the gradient.
* @param {Number} y1 Center position of the outer circle that defines the gradient.
* @param {Number} r1 Radius of the outer circle that defines the gradient.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.<API key> = function(colors, ratios, x0, y0, r0, x1, y1, r1) {
return this._setFill(new G.Fill().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1));
};
/**
* Begins a pattern fill using the specified image. This ends the current sub-path. A tiny API method "bf" also
* exists.
* @method beginBitmapFill
* @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use
* as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty.
* @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat",
* "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or
* "repeat-y" (latest tests were in FF 20.0), and will default to "repeat".
* @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation
* will be applied relative to the parent transform.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.beginBitmapFill = function(image, repetition, matrix) {
return this._setFill(new G.Fill(null,matrix).bitmap(image, repetition));
};
/**
* Ends the current sub-path, and begins a new one with no fill. Functionally identical to <code>beginFill(null)</code>.
* A tiny API method "ef" also exists.
* @method endFill
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.endFill = function() {
return this.beginFill();
};
/**
* Sets the stroke style. Like all drawing methods, this can be chained, so you can define
* the stroke style and color in a single line of code like so:
*
* myGraphics.setStrokeStyle(8,"round").beginStroke("#F00");
*
* A tiny API method "ss" also exists.
* @method setStrokeStyle
* @param {Number} thickness The width of the stroke.
* @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt,
* round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with
* the tiny API.
* @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet.
* One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel)
* for use with the tiny API.
* @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which
* controls at what point a mitered joint will be clipped.
* @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless
* of active transformations.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.setStrokeStyle = function(thickness, caps, joints, miterLimit, ignoreScale) {
this._updateInstructions(true);
this._strokeStyle = this.command = new G.StrokeStyle(thickness, caps, joints, miterLimit, ignoreScale);
// ignoreScale lives on Stroke, not StrokeStyle, so we do a little trickery:
if (this._stroke) { this._stroke.ignoreScale = ignoreScale; }
this._strokeIgnoreScale = ignoreScale;
return this;
};
/**
* Sets or clears the stroke dash pattern.
*
* myGraphics.setStrokeDash([20, 10], 0);
*
* A tiny API method `sd` also exists.
* @method setStrokeDash
* @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap.
* For example, `[20,10]` would create a pattern of 20 pixel lines with 10 pixel gaps between them.
* Passing null or an empty array will clear the existing stroke dash.
* @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.setStrokeDash = function(segments, offset) {
this._updateInstructions(true);
this._strokeDash = this.command = new G.StrokeDash(segments, offset);
return this;
};
/**
* Begins a stroke with the specified color. This ends the current sub-path. A tiny API method "s" also exists.
* @method beginStroke
* @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to
* null will result in no stroke.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.beginStroke = function(color) {
return this._setStroke(color ? new G.Stroke(color) : null);
};
/**
* Begins a linear gradient stroke defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For
* example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a
* square to display it:
*
* myGraphics.setStrokeStyle(10).
* <API key>(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120);
*
* A tiny API method "ls" also exists.
* @method <API key>
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define
* a gradient drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1,
* 0.9] would draw the first color to 10% then interpolating to the second color at 90%.
* @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size.
* @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.<API key> = function(colors, ratios, x0, y0, x1, y1) {
return this._setStroke(new G.Stroke().linearGradient(colors, ratios, x0, y0, x1, y1));
};
/**
* Begins a radial gradient stroke. This ends the current sub-path. For example, the following code defines a red to
* blue radial gradient centered at (100, 100), with a radius of 50, and draws a rectangle to display it:
*
* myGraphics.setStrokeStyle(10)
* .<API key>(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50)
* .drawRect(50, 90, 150, 110);
*
* A tiny API method "rs" also exists.
* @method <API key>
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define
* a gradient drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1,
* 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color
* to 100%.
* @param {Number} x0 Center position of the inner circle that defines the gradient.
* @param {Number} y0 Center position of the inner circle that defines the gradient.
* @param {Number} r0 Radius of the inner circle that defines the gradient.
* @param {Number} x1 Center position of the outer circle that defines the gradient.
* @param {Number} y1 Center position of the outer circle that defines the gradient.
* @param {Number} r1 Radius of the outer circle that defines the gradient.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.<API key> = function(colors, ratios, x0, y0, r0, x1, y1, r1) {
return this._setStroke(new G.Stroke().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1));
};
/**
* Begins a pattern fill using the specified image. This ends the current sub-path. Note that unlike bitmap fills,
* strokes do not currently support a matrix parameter due to limitations in the canvas API. A tiny API method "bs"
* also exists.
* @method beginBitmapStroke
* @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use
* as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty.
* @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of
* "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat".
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.beginBitmapStroke = function(image, repetition) {
// NOTE: matrix is not supported for stroke because transforms on strokes also affect the drawn stroke width.
return this._setStroke(new G.Stroke().bitmap(image, repetition));
};
/**
* Ends the current sub-path, and begins a new one with no stroke. Functionally identical to <code>beginStroke(null)</code>.
* A tiny API method "es" also exists.
* @method endStroke
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.endStroke = function() {
return this.beginStroke();
};
/**
* Maps the familiar ActionScript <code>curveTo()</code> method to the functionally similar {{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}}
* method.
* @method quadraticCurveTo
* @param {Number} cpx
* @param {Number} cpy
* @param {Number} x
* @param {Number} y
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.curveTo = p.quadraticCurveTo;
/**
*
* Maps the familiar ActionScript <code>drawRect()</code> method to the functionally similar {{#crossLink "Graphics/rect"}}{{/crossLink}}
* method.
* @method drawRect
* @param {Number} x
* @param {Number} y
* @param {Number} w Width of the rectangle
* @param {Number} h Height of the rectangle
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.drawRect = p.rect;
/**
* Draws a rounded rectangle with all corners with the specified radius.
* @method drawRoundRect
* @param {Number} x
* @param {Number} y
* @param {Number} w
* @param {Number} h
* @param {Number} radius Corner radius.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.drawRoundRect = function(x, y, w, h, radius) {
return this.<API key>(x, y, w, h, radius, radius, radius, radius);
};
/**
* Draws a rounded rectangle with different corner radii. Supports positive and negative corner radii. A tiny API
* method "rc" also exists.
* @method <API key>
* @param {Number} x The horizontal coordinate to draw the round rect.
* @param {Number} y The vertical coordinate to draw the round rect.
* @param {Number} w The width of the round rect.
* @param {Number} h The height of the round rect.
* @param {Number} radiusTL Top left corner radius.
* @param {Number} radiusTR Top right corner radius.
* @param {Number} radiusBR Bottom right corner radius.
* @param {Number} radiusBL Bottom left corner radius.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.<API key> = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) {
return this.append(new G.RoundRect(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL));
};
/**
* Draws a circle with the specified radius at (x, y).
*
* var g = new createjs.Graphics();
* g.setStrokeStyle(1);
* g.beginStroke(createjs.Graphics.getRGB(0,0,0));
* g.beginFill(createjs.Graphics.getRGB(255,0,0));
* g.drawCircle(0,0,3);
*
* var s = new createjs.Shape(g);
* s.x = 100;
* s.y = 100;
*
* stage.addChild(s);
* stage.update();
*
* A tiny API method "dc" also exists.
* @method drawCircle
* @param {Number} x x coordinate center point of circle.
* @param {Number} y y coordinate center point of circle.
* @param {Number} radius Radius of circle.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.drawCircle = function(x, y, radius) {
return this.append(new G.Circle(x, y, radius));
};
/**
* Draws an ellipse (oval) with a specified width (w) and height (h). Similar to {{#crossLink "Graphics/drawCircle"}}{{/crossLink}},
* except the width and height can be different. A tiny API method "de" also exists.
* @method drawEllipse
* @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}}
* which draws from center.
* @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}}
* which draws from the center.
* @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this
* number.
* @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.drawEllipse = function(x, y, w, h) {
return this.append(new G.Ellipse(x, y, w, h));
};
/**
* Draws a star if pointSize is greater than 0, or a regular polygon if pointSize is 0 with the specified number of
* points. For example, the following code will draw a familiar 5 pointed star shape centered at 100, 100 and with a
* radius of 50:
*
* myGraphics.beginFill("#FF0").drawPolyStar(100, 100, 50, 5, 0.6, -90);
* // Note: -90 makes the first point vertical
*
* A tiny API method "dp" also exists.
*
* @method drawPolyStar
* @param {Number} x Position of the center of the shape.
* @param {Number} y Position of the center of the shape.
* @param {Number} radius The outer radius of the shape.
* @param {Number} sides The number of points on the star or sides on the polygon.
* @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular
* polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy.
* @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point
* directly to the right of the center.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.drawPolyStar = function(x, y, radius, sides, pointSize, angle) {
return this.append(new G.PolyStar(x, y, radius, sides, pointSize, angle));
};
// TODO: deprecated.
/**
* Removed in favour of using custom command objects with {{#crossLink "Graphics/append"}}{{/crossLink}}.
* @method inject
* @deprecated
**/
/**
* Appends a graphics command object to the graphics queue. Command objects expose an "exec" method
* that accepts two parameters: the Context2D to operate on, and an arbitrary data object passed into
* {{#crossLink "Graphics/draw"}}{{/crossLink}}. The latter will usually be the Shape instance that called draw.
*
* This method is used internally by Graphics methods, such as drawCircle, but can also be used directly to insert
* built-in or custom graphics commands. For example:
*
* // attach data to our shape, so we can access it during the draw:
* myShape.color = "red";
*
* // append a Circle command object:
* myShape.graphics.append(new Graphics.Circle(50, 50, 30));
*
* // append a custom command object with an exec method that sets the fill style
* // based on the shape's data, and then fills the circle.
* myShape.graphics.append({exec:function(ctx, shape) {
* ctx.fillStyle = shape.color;
* ctx.fill();
* }});
*
* @method append
* @param {Object} command A graphics command object exposing an "exec" method.
* @param {boolean} clean The clean param is primarily for internal use. A value of true indicates that a command does not generate a path that should be stroked or filled.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.append = function(command, clean) {
this._activeInstructions.push(command);
this.command = command;
if (!clean) { this._dirty = true; }
return this;
};
/**
* Decodes a compact encoded path string into a series of draw instructions.
* This format is not intended to be human readable, and is meant for use by authoring tools.
* The format uses a base64 character set, with each character representing 6 bits, to define a series of draw
* commands.
*
* Each command is comprised of a single "header" character followed by a variable number of alternating x and y
* position values. Reading the header bits from left to right (most to least significant): bits 1 to 3 specify the
* type of operation (0-moveTo, 1-lineTo, 2-quadraticCurveTo, 3-bezierCurveTo, 4-closePath, 5-7 unused). Bit 4
* indicates whether position values use 12 bits (2 characters) or 18 bits (3 characters), with a one indicating the
* latter. Bits 5 and 6 are currently unused.
*
* Following the header is a series of 0 (closePath), 2 (moveTo, lineTo), 4 (quadraticCurveTo), or 6 (bezierCurveTo)
* parameters. These parameters are alternating x/y positions represented by 2 or 3 characters (as indicated by the
* 4th bit in the command char). These characters consist of a 1 bit sign (1 is negative, 0 is positive), followed
* by an 11 (2 char) or 17 (3 char) bit integer value. All position values are in tenths of a pixel. Except in the
* case of move operations which are absolute, this value is a delta from the previous x or y position (as
* appropriate).
*
* For example, the string "A3cAAMAu4AAA" represents a line starting at -150,0 and ending at 150,0.
* <br />A - bits 000000. First 3 bits (000) indicate a moveTo operation. 4th bit (0) indicates 2 chars per
* parameter.
* <br />n0 - 110111011100. Absolute x position of -150.0px. First bit indicates a negative value, remaining bits
* indicate 1500 tenths of a pixel.
* <br />AA - 000000000000. Absolute y position of 0.
* <br />I - 001100. First 3 bits (001) indicate a lineTo operation. 4th bit (1) indicates 3 chars per parameter.
* <br />Au4 - 000000101110111000. An x delta of 300.0px, which is added to the previous x value of -150.0px to
* provide an absolute position of +150.0px.
* <br />AAA - 000000000000000000. A y delta value of 0.
*
* A tiny API method "p" also exists.
* @method decodePath
* @param {String} str The path string to decode.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.decodePath = function(str) {
var instructions = [this.moveTo, this.lineTo, this.quadraticCurveTo, this.bezierCurveTo, this.closePath];
var paramCount = [2, 2, 4, 6, 0];
var i=0, l=str.length;
var params = [];
var x=0, y=0;
var base64 = Graphics.BASE_64;
while (i<l) {
var c = str.charAt(i);
var n = base64[c];
var fi = n>>3; // highest order bits 1-3 code for operation.
var f = instructions[fi];
// check that we have a valid instruction & that the unused bits are empty:
if (!f || (n&3)) { throw("bad path data (@"+i+"): "+c); }
var pl = paramCount[fi];
if (!fi) { x=y=0; } // move operations reset the position.
params.length = 0;
i++;
var charCount = (n>>2&1)+2; // 4th header bit indicates number size for this operation.
for (var p=0; p<pl; p++) {
var num = base64[str.charAt(i)];
var sign = (num>>5) ? -1 : 1;
num = ((num&31)<<6)|(base64[str.charAt(i+1)]);
if (charCount == 3) { num = (num<<6)|(base64[str.charAt(i+2)]); }
num = sign*num/10;
if (p%2) { x = (num += x); }
else { y = (num += y); }
params[p] = num;
i += charCount;
}
f.apply(this,params);
}
return this;
};
/**
* Stores all graphics commands so they won't be executed in future draws. Calling store() a second time adds to
* the existing store. This also affects `drawAsPath()`.
*
* This is useful in cases where you are creating vector graphics in an iterative manner (ex. generative art), so
* that only new graphics need to be drawn (which can provide huge performance benefits), but you wish to retain all
* of the vector instructions for later use (ex. scaling, modifying, or exporting).
*
* Note that calling store() will force the active path (if any) to be ended in a manner similar to changing
* the fill or stroke.
*
* For example, consider a application where the user draws lines with the mouse. As each line segment (or collection of
* segments) are added to a Shape, it can be rasterized using {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}},
* and then stored, so that it can be redrawn at a different scale when the application is resized, or exported to SVG.
*
* // set up cache:
* myShape.cache(0,0,500,500,scale);
*
* // when the user drags, draw a new line:
* myShape.graphics.moveTo(oldX,oldY).lineTo(newX,newY);
* // then draw it into the existing cache:
* myShape.updateCache("source-over");
* // store the new line, so it isn't redrawn next time:
* myShape.store();
*
* // then, when the window resizes, we can re-render at a different scale:
* // first, unstore all our lines:
* myShape.unstore();
* // then cache using the new scale:
* myShape.cache(0,0,500,500,newScale);
* // finally, store the existing commands again:
* myShape.store();
*
* @method store
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.store = function() {
this._updateInstructions(true);
this._storeIndex = this._instructions.length;
return this;
};
/**
* Unstores any graphics commands that were previously stored using {{#crossLink "Graphics/store"}}{{/crossLink}}
* so that they will be executed in subsequent draw calls.
*
* @method unstore
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
**/
p.unstore = function() {
this._storeIndex = 0;
return this;
};
/**
* Returns a clone of this Graphics instance. Note that the individual command objects are not cloned.
* @method clone
* @return {Graphics} A clone of the current Graphics instance.
**/
p.clone = function() {
var o = new Graphics();
o.command = this.command;
o._stroke = this._stroke;
o._strokeStyle = this._strokeStyle;
o._strokeDash = this._strokeDash;
o._strokeIgnoreScale = this._strokeIgnoreScale;
o._fill = this._fill;
o._instructions = this._instructions.slice();
o._commitIndex = this._commitIndex;
o._activeInstructions = this._activeInstructions.slice();
o._dirty = this._dirty;
o._storeIndex = this._storeIndex;
return o;
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Graphics]";
};
// tiny API:
/**
* Shortcut to moveTo.
* @method mt
* @param {Number} x The x coordinate the drawing point should move to.
* @param {Number} y The y coordinate the drawing point should move to.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls).
* @chainable
* @protected
**/
p.mt = p.moveTo;
/**
* Shortcut to lineTo.
* @method lt
* @param {Number} x The x coordinate the drawing point should draw to.
* @param {Number} y The y coordinate the drawing point should draw to.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.lt = p.lineTo;
/**
* Shortcut to arcTo.
* @method at
* @param {Number} x1
* @param {Number} y1
* @param {Number} x2
* @param {Number} y2
* @param {Number} radius
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.at = p.arcTo;
/**
* Shortcut to bezierCurveTo.
* @method bt
* @param {Number} cp1x
* @param {Number} cp1y
* @param {Number} cp2x
* @param {Number} cp2y
* @param {Number} x
* @param {Number} y
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.bt = p.bezierCurveTo;
/**
* Shortcut to quadraticCurveTo / curveTo.
* @method qt
* @param {Number} cpx
* @param {Number} cpy
* @param {Number} x
* @param {Number} y
* @protected
* @chainable
**/
p.qt = p.quadraticCurveTo;
/**
* Shortcut to arc.
* @method a
* @param {Number} x
* @param {Number} y
* @param {Number} radius
* @param {Number} startAngle Measured in radians.
* @param {Number} endAngle Measured in radians.
* @param {Boolean} anticlockwise
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @protected
* @chainable
**/
p.a = p.arc;
/**
* Shortcut to rect.
* @method r
* @param {Number} x
* @param {Number} y
* @param {Number} w Width of the rectangle
* @param {Number} h Height of the rectangle
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.r = p.rect;
/**
* Shortcut to closePath.
* @method cp
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.cp = p.closePath;
/**
* Shortcut to clear.
* @method c
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.c = p.clear;
/**
* Shortcut to beginFill.
* @method f
* @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to
* null will result in no fill.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.f = p.beginFill;
/**
* Shortcut to <API key>.
* @method lf
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient
* drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw
* the first color to 10% then interpolating to the second color at 90%.
* @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size.
* @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.lf = p.<API key>;
/**
* Shortcut to <API key>.
* @method rf
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define
* a gradient drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1,
* 0.9] would draw the first color to 10% then interpolating to the second color at 90%.
* @param {Number} x0 Center position of the inner circle that defines the gradient.
* @param {Number} y0 Center position of the inner circle that defines the gradient.
* @param {Number} r0 Radius of the inner circle that defines the gradient.
* @param {Number} x1 Center position of the outer circle that defines the gradient.
* @param {Number} y1 Center position of the outer circle that defines the gradient.
* @param {Number} r1 Radius of the outer circle that defines the gradient.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.rf = p.<API key>;
/**
* Shortcut to beginBitmapFill.
* @method bf
* @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use
* as the pattern.
* @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat",
* "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or
* "repeat-y" (latest tests were in FF 20.0), and will default to "repeat".
* @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation
* will be applied relative to the parent transform.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.bf = p.beginBitmapFill;
/**
* Shortcut to endFill.
* @method ef
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.ef = p.endFill;
/**
* Shortcut to setStrokeStyle.
* @method ss
* @param {Number} thickness The width of the stroke.
* @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt,
* round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with
* the tiny API.
* @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet.
* One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel)
* for use with the tiny API.
* @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which
* controls at what point a mitered joint will be clipped.
* @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless
* of active transformations.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.ss = p.setStrokeStyle;
/**
* Shortcut to setStrokeDash.
* @method sd
* @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap.
* For example, [20,10] would create a pattern of 20 pixel lines with 10 pixel gaps between them.
* Passing null or an empty array will clear any existing dash.
* @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.sd = p.setStrokeDash;
/**
* Shortcut to beginStroke.
* @method s
* @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to
* null will result in no stroke.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.s = p.beginStroke;
/**
* Shortcut to <API key>.
* @method ls
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define
* a gradient drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1,
* 0.9] would draw the first color to 10% then interpolating to the second color at 90%.
* @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size.
* @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size.
* @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.ls = p.<API key>;
/**
* Shortcut to <API key>.
* @method rs
* @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define
* a gradient drawing from red to blue.
* @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1,
* 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color
* to 100%.
* @param {Number} x0 Center position of the inner circle that defines the gradient.
* @param {Number} y0 Center position of the inner circle that defines the gradient.
* @param {Number} r0 Radius of the inner circle that defines the gradient.
* @param {Number} x1 Center position of the outer circle that defines the gradient.
* @param {Number} y1 Center position of the outer circle that defines the gradient.
* @param {Number} r1 Radius of the outer circle that defines the gradient.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.rs = p.<API key>;
/**
* Shortcut to beginBitmapStroke.
* @method bs
* @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use
* as the pattern.
* @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of
* "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat".
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.bs = p.beginBitmapStroke;
/**
* Shortcut to endStroke.
* @method es
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.es = p.endStroke;
/**
* Shortcut to drawRect.
* @method dr
* @param {Number} x
* @param {Number} y
* @param {Number} w Width of the rectangle
* @param {Number} h Height of the rectangle
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.dr = p.drawRect;
/**
* Shortcut to drawRoundRect.
* @method rr
* @param {Number} x
* @param {Number} y
* @param {Number} w
* @param {Number} h
* @param {Number} radius Corner radius.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.rr = p.drawRoundRect;
/**
* Shortcut to <API key>.
* @method rc
* @param {Number} x The horizontal coordinate to draw the round rect.
* @param {Number} y The vertical coordinate to draw the round rect.
* @param {Number} w The width of the round rect.
* @param {Number} h The height of the round rect.
* @param {Number} radiusTL Top left corner radius.
* @param {Number} radiusTR Top right corner radius.
* @param {Number} radiusBR Bottom right corner radius.
* @param {Number} radiusBL Bottom left corner radius.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.rc = p.<API key>;
/**
* Shortcut to drawCircle.
* @method dc
* @param {Number} x x coordinate center point of circle.
* @param {Number} y y coordinate center point of circle.
* @param {Number} radius Radius of circle.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.dc = p.drawCircle;
/**
* Shortcut to drawEllipse.
* @method de
* @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}}
* which draws from center.
* @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}}
* which draws from the center.
* @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this
* number.
* @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.de = p.drawEllipse;
/**
* Shortcut to drawPolyStar.
* @method dp
* @param {Number} x Position of the center of the shape.
* @param {Number} y Position of the center of the shape.
* @param {Number} radius The outer radius of the shape.
* @param {Number} sides The number of points on the star or sides on the polygon.
* @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular
* polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy.
* @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point
* directly to the right of the center.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.dp = p.drawPolyStar;
/**
* Shortcut to decodePath.
* @method p
* @param {String} str The path string to decode.
* @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.)
* @chainable
* @protected
**/
p.p = p.decodePath;
// private methods:
/**
* @method _updateInstructions
* @param commit
* @protected
**/
p._updateInstructions = function(commit) {
var instr = this._instructions, active = this._activeInstructions, commitIndex = this._commitIndex;
if (this._dirty && active.length) {
instr.length = commitIndex; // remove old, uncommitted commands
instr.push(Graphics.beginCmd);
var l = active.length, ll = instr.length;
instr.length = ll+l;
for (var i=0; i<l; i++) { instr[i+ll] = active[i]; }
if (this._fill) { instr.push(this._fill); }
if (this._stroke) {
// doesn't need to be re-applied if it hasn't changed.
if (this._strokeDash !== this._oldStrokeDash) {
this._oldStrokeDash = this._strokeDash;
instr.push(this._strokeDash);
}
if (this._strokeStyle !== this._oldStrokeStyle) {
this._oldStrokeStyle = this._strokeStyle;
instr.push(this._strokeStyle);
}
instr.push(this._stroke);
}
this._dirty = false;
}
if (commit) {
active.length = 0;
this._commitIndex = instr.length;
}
};
/**
* @method _setFill
* @param fill
* @protected
**/
p._setFill = function(fill) {
this._updateInstructions(true);
this.command = this._fill = fill;
return this;
};
/**
* @method _setStroke
* @param stroke
* @protected
**/
p._setStroke = function(stroke) {
this._updateInstructions(true);
if (this.command = this._stroke = stroke) {
stroke.ignoreScale = this._strokeIgnoreScale;
}
return this;
};
// Command Objects:
/**
* @namespace Graphics
*/
/**
* Graphics command object. See {{#crossLink "Graphics/lineTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. See {{#crossLink "Graphics"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class LineTo
* @constructor
* @param {Number} x
* @param {Number} y
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.LineTo = function(x, y) {
this.x = x; this.y = y;
}).prototype.exec = function(ctx) { ctx.lineTo(this.x,this.y); };
/**
* Graphics command object. See {{#crossLink "Graphics/moveTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class MoveTo
* @constructor
* @param {Number} x
* @param {Number} y
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.MoveTo = function(x, y) {
this.x = x; this.y = y;
}).prototype.exec = function(ctx) { ctx.moveTo(this.x, this.y); };
/**
* Graphics command object. See {{#crossLink "Graphics/arcTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class ArcTo
* @constructor
* @param {Number} x1
* @param {Number} y1
* @param {Number} x2
* @param {Number} y2
* @param {Number} radius
**/
/**
* @property x1
* @type Number
*/
/**
* @property y1
* @type Number
*/
/**
* @property x2
* @type Number
*/
/**
* @property y2
* @type Number
*/
/**
* @property radius
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.ArcTo = function(x1, y1, x2, y2, radius) {
this.x1 = x1; this.y1 = y1;
this.x2 = x2; this.y2 = y2;
this.radius = radius;
}).prototype.exec = function(ctx) { ctx.arcTo(this.x1, this.y1, this.x2, this.y2, this.radius); };
/**
* Graphics command object. See {{#crossLink "Graphics/arc"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class Arc
* @constructor
* @param {Number} x
* @param {Number} y
* @param {Number} radius
* @param {Number} startAngle
* @param {Number} endAngle
* @param {Number} anticlockwise
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @property radius
* @type Number
*/
/**
* @property startAngle
* @type Number
*/
/**
* @property endAngle
* @type Number
*/
/**
* @property anticlockwise
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.Arc = function(x, y, radius, startAngle, endAngle, anticlockwise) {
this.x = x; this.y = y;
this.radius = radius;
this.startAngle = startAngle; this.endAngle = endAngle;
this.anticlockwise = !!anticlockwise;
}).prototype.exec = function(ctx) { ctx.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle, this.anticlockwise); };
/**
* Graphics command object. See {{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class QuadraticCurveTo
* @constructor
* @param {Number} cpx
* @param {Number} cpy
* @param {Number} x
* @param {Number} y
**/
/**
* @property cpx
* @type Number
*/
/**
* @property cpy
* @type Number
*/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.QuadraticCurveTo = function(cpx, cpy, x, y) {
this.cpx = cpx; this.cpy = cpy;
this.x = x; this.y = y;
}).prototype.exec = function(ctx) { ctx.quadraticCurveTo(this.cpx, this.cpy, this.x, this.y); };
/**
* Graphics command object. See {{#crossLink "Graphics/bezierCurveTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class BezierCurveTo
* @constructor
* @param {Number} cp1x
* @param {Number} cp1y
* @param {Number} cp2x
* @param {Number} cp2y
* @param {Number} x
* @param {Number} y
**/
/**
* @property cp1x
* @type Number
*/
/**
* @property cp1y
* @type Number
*/
/**
* @property cp2x
* @type Number
*/
/**
* @property cp2y
* @type Number
*/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.BezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
this.cp1x = cp1x; this.cp1y = cp1y;
this.cp2x = cp2x; this.cp2y = cp2y;
this.x = x; this.y = y;
}).prototype.exec = function(ctx) { ctx.bezierCurveTo(this.cp1x, this.cp1y, this.cp2x, this.cp2y, this.x, this.y); };
/**
* Graphics command object. See {{#crossLink "Graphics/rect"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class Rect
* @constructor
* @param {Number} x
* @param {Number} y
* @param {Number} w
* @param {Number} h
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @property w
* @type Number
*/
/**
* @property h
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.Rect = function(x, y, w, h) {
this.x = x; this.y = y;
this.w = w; this.h = h;
}).prototype.exec = function(ctx) { ctx.rect(this.x, this.y, this.w, this.h); };
/**
* Graphics command object. See {{#crossLink "Graphics/closePath"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class ClosePath
* @constructor
**/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.ClosePath = function() {
}).prototype.exec = function(ctx) { ctx.closePath(); };
/**
* Graphics command object to begin a new path. See {{#crossLink "Graphics"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class BeginPath
* @constructor
**/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.BeginPath = function() {
}).prototype.exec = function(ctx) { ctx.beginPath(); };
/**
* Graphics command object. See {{#crossLink "Graphics/beginFill"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class Fill
* @constructor
* @param {Object} style A valid Context2D fillStyle.
* @param {Matrix2D} matrix
**/
/**
* A valid Context2D fillStyle.
* @property style
* @type Object
*/
/**
* @property matrix
* @type Matrix2D
*/
/**
* @method exec
* @param {<API key>} ctx
*/
p = (G.Fill = function(style, matrix) {
this.style = style;
this.matrix = matrix;
}).prototype;
p.exec = function(ctx) {
if (!this.style) { return; }
ctx.fillStyle = this.style;
var mtx = this.matrix;
if (mtx) { ctx.save(); ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); }
ctx.fill();
if (mtx) { ctx.restore(); }
};
/**
* Creates a linear gradient style and assigns it to {{#crossLink "Fill/style:property"}}{{/crossLink}}.
* See {{#crossLink "Graphics/<API key>"}}{{/crossLink}} for more information.
* @method linearGradient
* @param {Array} colors
*
* @param {Array} ratios
* @param {Number} x0
* @param {Number} y0
* @param {Number} x1
* @param {Number} y1
* @return {Fill} Returns this Fill object for chaining or assignment.
*/
p.linearGradient = function(colors, ratios, x0, y0, x1, y1) {
var o = this.style = Graphics._ctx.<API key>(x0, y0, x1, y1);
for (var i=0, l=colors.length; i<l; i++) { o.addColorStop(ratios[i], colors[i]); }
o.props = {colors:colors, ratios:ratios, x0:x0, y0:y0, x1:x1, y1:y1, type:"linear"};
return this;
};
/**
* Creates a radial gradient style and assigns it to {{#crossLink "Fill/style:property"}}{{/crossLink}}.
* See {{#crossLink "Graphics/<API key>"}}{{/crossLink}} for more information.
* @method radialGradient
* @param {Array} colors
* @param {Array} ratios
* @param {Number} x0
* @param {Number} y0
* @param {Number} r0
* @param {Number} x1
* @param {Number} y1
* @param {Number} r1
* @return {Fill} Returns this Fill object for chaining or assignment.
*/
p.radialGradient = function(colors, ratios, x0, y0, r0, x1, y1, r1) {
var o = this.style = Graphics._ctx.<API key>(x0, y0, r0, x1, y1, r1);
for (var i=0, l=colors.length; i<l; i++) { o.addColorStop(ratios[i], colors[i]); }
o.props = {colors:colors, ratios:ratios, x0:x0, y0:y0, r0:r0, x1:x1, y1:y1, r1:r1, type:"radial"};
return this;
};
/**
* Creates a bitmap fill style and assigns it to the {{#crossLink "Fill/style:property"}}{{/crossLink}}.
* See {{#crossLink "Graphics/beginBitmapFill"}}{{/crossLink}} for more information.
* @method bitmap
* @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image Must be loaded prior to creating a bitmap fill, or the fill will be empty.
* @param {String} [repetition] One of: repeat, repeat-x, repeat-y, or no-repeat.
* @return {Fill} Returns this Fill object for chaining or assignment.
*/
p.bitmap = function(image, repetition) {
if (image.naturalWidth || image.getContext || image.readyState >= 2) {
var o = this.style = Graphics._ctx.createPattern(image, repetition || "");
o.props = {image: image, repetition: repetition, type: "bitmap"};
}
return this;
};
p.path = false;
/**
* Graphics command object. See {{#crossLink "Graphics/beginStroke"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class Stroke
* @constructor
* @param {Object} style A valid Context2D fillStyle.
* @param {Boolean} ignoreScale
**/
/**
* A valid Context2D strokeStyle.
* @property style
* @type Object
*/
/**
* @property ignoreScale
* @type Boolean
*/
/**
* @method exec
* @param {<API key>} ctx
*/
p = (G.Stroke = function(style, ignoreScale) {
this.style = style;
this.ignoreScale = ignoreScale;
}).prototype;
p.exec = function(ctx) {
if (!this.style) { return; }
ctx.strokeStyle = this.style;
if (this.ignoreScale) { ctx.save(); ctx.setTransform(1,0,0,1,0,0); }
ctx.stroke();
if (this.ignoreScale) { ctx.restore(); }
};
/**
* Creates a linear gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}.
* See {{#crossLink "Graphics/<API key>"}}{{/crossLink}} for more information.
* @method linearGradient
* @param {Array} colors
* @param {Array} ratios
* @param {Number} x0
* @param {Number} y0
* @param {Number} x1
* @param {Number} y1
* @return {Fill} Returns this Stroke object for chaining or assignment.
*/
p.linearGradient = G.Fill.prototype.linearGradient;
/**
* Creates a radial gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}.
* See {{#crossLink "Graphics/<API key>"}}{{/crossLink}} for more information.
* @method radialGradient
* @param {Array} colors
* @param {Array} ratios
* @param {Number} x0
* @param {Number} y0
* @param {Number} r0
* @param {Number} x1
* @param {Number} y1
* @param {Number} r1
* @return {Fill} Returns this Stroke object for chaining or assignment.
*/
p.radialGradient = G.Fill.prototype.radialGradient;
/**
* Creates a bitmap fill style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}.
* See {{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}} for more information.
* @method bitmap
* @param {HTMLImageElement} image
* @param {String} [repetition] One of: repeat, repeat-x, repeat-y, or no-repeat.
* @return {Fill} Returns this Stroke object for chaining or assignment.
*/
p.bitmap = G.Fill.prototype.bitmap;
p.path = false;
/**
* Graphics command object. See {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class StrokeStyle
* @constructor
* @param {Number} width
* @param {String} [caps=butt]
* @param {String} [joints=miter]
* @param {Number} [miterLimit=10]
* @param {Boolean} [ignoreScale=false]
**/
/**
* @property width
* @type Number
*/
/**
* One of: butt, round, square
* @property caps
* @type String
*/
/**
* One of: round, bevel, miter
* @property joints
* @type String
*/
/**
* @property miterLimit
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
p = (G.StrokeStyle = function(width, caps, joints, miterLimit, ignoreScale) {
this.width = width;
this.caps = caps;
this.joints = joints;
this.miterLimit = miterLimit;
this.ignoreScale = ignoreScale;
}).prototype;
p.exec = function(ctx) {
ctx.lineWidth = (this.width == null ? "1" : this.width);
ctx.lineCap = (this.caps == null ? "butt" : (isNaN(this.caps) ? this.caps : Graphics.STROKE_CAPS_MAP[this.caps]));
ctx.lineJoin = (this.joints == null ? "miter" : (isNaN(this.joints) ? this.joints : Graphics.STROKE_JOINTS_MAP[this.joints]));
ctx.miterLimit = (this.miterLimit == null ? "10" : this.miterLimit);
ctx.ignoreScale = (this.ignoreScale == null ? false : this.ignoreScale);
};
p.path = false;
/**
* Graphics command object. See {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class StrokeDash
* @constructor
* @param {Array} [segments]
* @param {Number} [offset=0]
**/
/**
* @property segments
* @type Array
*/
/**
* @property offset
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.StrokeDash = function(segments, offset) {
this.segments = segments;
this.offset = offset||0;
}).prototype.exec = function(ctx) {
if (ctx.setLineDash) { // feature detection.
ctx.setLineDash(this.segments|| G.StrokeDash.EMPTY_SEGMENTS); // instead of [] to reduce churn.
ctx.lineDashOffset = this.offset||0;
}
};
/**
* The default value for segments (ie. no dash).
* @property EMPTY_SEGMENTS
* @static
* @final
* @readonly
* @protected
* @type {Array}
**/
G.StrokeDash.EMPTY_SEGMENTS = [];
/**
* Graphics command object. See {{#crossLink "Graphics/<API key>"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class RoundRect
* @constructor
* @param {Number} x
* @param {Number} y
* @param {Number} w
* @param {Number} h
* @param {Number} radiusTL
* @param {Number} radiusTR
* @param {Number} radiusBR
* @param {Number} radiusBL
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @property w
* @type Number
*/
/**
* @property h
* @type Number
*/
/**
* @property radiusTL
* @type Number
*/
/**
* @property radiusTR
* @type Number
*/
/**
* @property radiusBR
* @type Number
*/
/**
* @property radiusBL
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.RoundRect = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) {
this.x = x; this.y = y;
this.w = w; this.h = h;
this.radiusTL = radiusTL; this.radiusTR = radiusTR;
this.radiusBR = radiusBR; this.radiusBL = radiusBL;
}).prototype.exec = function(ctx) {
var max = (w<h?w:h)/2;
var mTL=0, mTR=0, mBR=0, mBL=0;
var x = this.x, y = this.y, w = this.w, h = this.h;
var rTL = this.radiusTL, rTR = this.radiusTR, rBR = this.radiusBR, rBL = this.radiusBL;
if (rTL < 0) { rTL *= (mTL=-1); }
if (rTL > max) { rTL = max; }
if (rTR < 0) { rTR *= (mTR=-1); }
if (rTR > max) { rTR = max; }
if (rBR < 0) { rBR *= (mBR=-1); }
if (rBR > max) { rBR = max; }
if (rBL < 0) { rBL *= (mBL=-1); }
if (rBL > max) { rBL = max; }
ctx.moveTo(x+w-rTR, y);
ctx.arcTo(x+w+rTR*mTR, y-rTR*mTR, x+w, y+rTR, rTR);
ctx.lineTo(x+w, y+h-rBR);
ctx.arcTo(x+w+rBR*mBR, y+h+rBR*mBR, x+w-rBR, y+h, rBR);
ctx.lineTo(x+rBL, y+h);
ctx.arcTo(x-rBL*mBL, y+h+rBL*mBL, x, y+h-rBL, rBL);
ctx.lineTo(x, y+rTL);
ctx.arcTo(x-rTL*mTL, y-rTL*mTL, x+rTL, y, rTL);
ctx.closePath();
};
/**
* Graphics command object. See {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class Circle
* @constructor
* @param {Number} x
* @param {Number} y
* @param {Number} radius
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @property radius
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.Circle = function(x, y, radius) {
this.x = x; this.y = y;
this.radius = radius;
}).prototype.exec = function(ctx) { ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2); };
/**
* Graphics command object. See {{#crossLink "Graphics/drawEllipse"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class Ellipse
* @constructor
* @param {Number} x
* @param {Number} y
* @param {Number} w
* @param {Number} h
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @property w
* @type Number
*/
/**
* @property h
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.Ellipse = function(x, y, w, h) {
this.x = x; this.y = y;
this.w = w; this.h = h;
}).prototype.exec = function(ctx) {
var x = this.x, y = this.y;
var w = this.w, h = this.h;
var k = 0.5522848;
var ox = (w / 2) * k;
var oy = (h / 2) * k;
var xe = x + w;
var ye = y + h;
var xm = x + w / 2;
var ym = y + h / 2;
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym-oy, xm-ox, y, xm, y);
ctx.bezierCurveTo(xm+ox, y, xe, ym-oy, xe, ym);
ctx.bezierCurveTo(xe, ym+oy, xm+ox, ye, xm, ye);
ctx.bezierCurveTo(xm-ox, ye, x, ym+oy, x, ym);
};
/**
* Graphics command object. See {{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information.
* @class PolyStar
* @constructor
* @param {Number} x
* @param {Number} y
* @param {Number} radius
* @param {Number} sides
* @param {Number} pointSize
* @param {Number} angle
**/
/**
* @property x
* @type Number
*/
/**
* @property y
* @type Number
*/
/**
* @property radius
* @type Number
*/
/**
* @property sides
* @type Number
*/
/**
* @property pointSize
* @type Number
*/
/**
* @property angle
* @type Number
*/
/**
* @method exec
* @param {<API key>} ctx
*/
(G.PolyStar = function(x, y, radius, sides, pointSize, angle) {
this.x = x; this.y = y;
this.radius = radius;
this.sides = sides;
this.pointSize = pointSize;
this.angle = angle;
}).prototype.exec = function(ctx) {
var x = this.x, y = this.y;
var radius = this.radius;
var angle = (this.angle||0)/180*Math.PI;
var sides = this.sides;
var ps = 1-(this.pointSize||0);
var a = Math.PI/sides;
ctx.moveTo(x+Math.cos(angle)*radius, y+Math.sin(angle)*radius);
for (var i=0; i<sides; i++) {
angle += a;
if (ps != 1) {
ctx.lineTo(x+Math.cos(angle)*radius*ps, y+Math.sin(angle)*radius*ps);
}
angle += a;
ctx.lineTo(x+Math.cos(angle)*radius, y+Math.sin(angle)*radius);
}
ctx.closePath();
};
// docced above.
Graphics.beginCmd = new G.BeginPath(); // so we don't have to instantiate multiple instances.
createjs.Graphics = Graphics;
}());
//
// DisplayObject.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* DisplayObject is an abstract class that should not be constructed directly. Instead construct subclasses such as
* {{#crossLink "Container"}}{{/crossLink}}, {{#crossLink "Bitmap"}}{{/crossLink}}, and {{#crossLink "Shape"}}{{/crossLink}}.
* DisplayObject is the base class for all display classes in the EaselJS library. It defines the core properties and
* methods that are shared between all display objects, such as transformation properties (x, y, scaleX, scaleY, etc),
* caching, and mouse handlers.
* @class DisplayObject
* @extends EventDispatcher
* @constructor
**/
function DisplayObject() {
this.<API key>();
// public properties:
/**
* The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque.
* @property alpha
* @type {Number}
* @default 1
**/
this.alpha = 1;
/**
* If a cache is active, this returns the canvas that holds the cached version of this display object. See {{#crossLink "cache"}}{{/crossLink}}
* for more information.
* @property cacheCanvas
* @type {HTMLCanvasElement | Object}
* @default null
* @readonly
**/
this.cacheCanvas = null;
/**
* Returns an ID number that uniquely identifies the current cache for this display object. This can be used to
* determine if the cache has changed since a previous check.
* @property cacheID
* @type {Number}
* @default 0
*/
this.cacheID = 0;
/**
* Unique ID for this display object. Makes display objects easier for some uses.
* @property id
* @type {Number}
* @default -1
**/
this.id = createjs.UID.get();
this.mouseEnabled = true;
/**
* If false, the tick will not run on this display object (or its children). This can provide some performance benefits.
* In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates
* on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling).
* @property tickEnabled
* @type Boolean
* @default true
**/
this.tickEnabled = true;
/**
* An optional name for this display object. Included in {{#crossLink "DisplayObject/toString"}}{{/crossLink}} . Useful for
* debugging.
* @property name
* @type {String}
* @default null
**/
this.name = null;
/**
* A reference to the {{#crossLink "Container"}}{{/crossLink}} or {{#crossLink "Stage"}}{{/crossLink}} object that
* contains this display object, or null if it has not been added
* to one.
* @property parent
* @final
* @type {Container}
* @default null
* @readonly
**/
this.parent = null;
/**
* The left offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate
* around its center, you would set regX and {{#crossLink "DisplayObject/regY:property"}}{{/crossLink}} to 50.
* @property regX
* @type {Number}
* @default 0
**/
this.regX = 0;
/**
* The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around
* its center, you would set {{#crossLink "DisplayObject/regX:property"}}{{/crossLink}} and regY to 50.
* @property regY
* @type {Number}
* @default 0
**/
this.regY = 0;
/**
* The rotation in degrees for this display object.
* @property rotation
* @type {Number}
* @default 0
**/
this.rotation = 0;
/**
* The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display
* object to twice its nominal width. To horizontally flip an object, set the scale to a negative number.
* @property scaleX
* @type {Number}
* @default 1
**/
this.scaleX = 1;
/**
* The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display
* object to half its nominal height. To vertically flip an object, set the scale to a negative number.
* @property scaleY
* @type {Number}
* @default 1
**/
this.scaleY = 1;
/**
* The factor to skew this display object horizontally.
* @property skewX
* @type {Number}
* @default 0
**/
this.skewX = 0;
/**
* The factor to skew this display object vertically.
* @property skewY
* @type {Number}
* @default 0
**/
this.skewY = 0;
/**
* A shadow object that defines the shadow to render on this display object. Set to `null` to remove a shadow. If
* null, this property is inherited from the parent container.
* @property shadow
* @type {Shadow}
* @default null
**/
this.shadow = null;
/**
* Indicates whether this display object should be rendered to the canvas and included when running the Stage
* {{#crossLink "Stage/<API key>"}}{{/crossLink}} method.
* @property visible
* @type {Boolean}
* @default true
**/
this.visible = true;
/**
* The x (horizontal) position of the display object, relative to its parent.
* @property x
* @type {Number}
* @default 0
**/
this.x = 0;
/** The y (vertical) position of the display object, relative to its parent.
* @property y
* @type {Number}
* @default 0
**/
this.y = 0;
/**
* If set, defines the transformation for this display object, overriding all other transformation properties
* (x, y, rotation, scale, skew).
* @property transformMatrix
* @type {Matrix2D}
* @default null
**/
this.transformMatrix = null;
this.compositeOperation = null;
/**
* Indicates whether the display object should be drawn to a whole pixel when
* {{#crossLink "Stage/snapToPixelEnabled"}}{{/crossLink}} is true. To enable/disable snapping on whole
* categories of display objects, set this value on the prototype (Ex. Text.prototype.snapToPixel = true).
* @property snapToPixel
* @type {Boolean}
* @default true
**/
this.snapToPixel = true;
/**
* An array of Filter objects to apply to this display object. Filters are only applied / updated when {{#crossLink "cache"}}{{/crossLink}}
* or {{#crossLink "updateCache"}}{{/crossLink}} is called on the display object, and only apply to the area that is
* cached.
* @property filters
* @type {Array}
* @default null
**/
this.filters = null;
/**
* A Shape instance that defines a vector mask (clipping path) for this display object. The shape's transformation
* will be applied relative to the display object's parent coordinates (as if it were a child of the parent).
* @property mask
* @type {Shape}
* @default null
*/
this.mask = null;
/**
* A display object that will be tested when checking mouse interactions or testing {{#crossLink "Container/<API key>"}}{{/crossLink}}.
* The hit area will have its transformation applied relative to this display object's coordinate space (as though
* the hit test object were a child of this display object and relative to its regX/Y). The hitArea will be tested
* using only its own `alpha` value regardless of the alpha value on the target display object, or the target's
* ancestors (parents).
*
* If set on a {{#crossLink "Container"}}{{/crossLink}}, children of the Container will not receive mouse events.
* This is similar to setting {{#crossLink "mouseChildren"}}{{/crossLink}} to false.
*
* Note that hitArea is NOT currently used by the `hitTest()` method, nor is it supported for {{#crossLink "Stage"}}{{/crossLink}}.
* @property hitArea
* @type {DisplayObject}
* @default null
*/
this.hitArea = null;
/**
* A CSS cursor (ex. "pointer", "help", "text", etc) that will be displayed when the user hovers over this display
* object. You must enable mouseover events using the {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}} method to
* use this property. Setting a non-null cursor on a Container will override the cursor set on its descendants.
* @property cursor
* @type {String}
* @default null
*/
this.cursor = null;
// private properties:
/**
* @property _cacheOffsetX
* @protected
* @type {Number}
* @default 0
**/
this._cacheOffsetX = 0;
/**
* @property _cacheOffsetY
* @protected
* @type {Number}
* @default 0
**/
this._cacheOffsetY = 0;
/**
* @property _filterOffsetX
* @protected
* @type {Number}
* @default 0
**/
this._filterOffsetX = 0;
/**
* @property _filterOffsetY
* @protected
* @type {Number}
* @default 0
**/
this._filterOffsetY = 0;
/**
* @property _cacheScale
* @protected
* @type {Number}
* @default 1
**/
this._cacheScale = 1;
/**
* @property _cacheDataURLID
* @protected
* @type {Number}
* @default 0
*/
this._cacheDataURLID = 0;
/**
* @property _cacheDataURL
* @protected
* @type {String}
* @default null
*/
this._cacheDataURL = null;
/**
* @property _props
* @protected
* @type {DisplayObject}
* @default null
**/
this._props = new createjs.DisplayProps();
/**
* @property _rectangle
* @protected
* @type {Rectangle}
* @default null
**/
this._rectangle = new createjs.Rectangle();
/**
* @property _bounds
* @protected
* @type {Rectangle}
* @default null
**/
this._bounds = null;
}
var p = createjs.extend(DisplayObject, createjs.EventDispatcher);
// TODO: deprecated
// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.
// static properties:
/**
* Listing of mouse event names. Used in <API key>.
* @property _MOUSE_EVENTS
* @protected
* @static
* @type {Array}
**/
DisplayObject._MOUSE_EVENTS = ["click","dblclick","mousedown","mouseout","mouseover","pressmove","pressup","rollout","rollover"];
/**
* Suppresses errors generated when using features like hitTest, mouse events, and {{#crossLink "<API key>"}}{{/crossLink}}
* with cross domain content.
* @property <API key>
* @static
* @type {Boolean}
* @default false
**/
DisplayObject.<API key> = false;
/**
* @property _snapToPixelEnabled
* @protected
* @static
* @type {Boolean}
* @default false
**/
DisplayObject._snapToPixelEnabled = false; // stage.snapToPixelEnabled is temporarily copied here during a draw to provide global access.
/**
* @property _hitTestCanvas
* @type {HTMLCanvasElement | Object}
* @static
* @protected
**/
/**
* @property _hitTestContext
* @type {<API key>}
* @static
* @protected
**/
var canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); // prevent errors on load in browsers without canvas.
if (canvas.getContext) {
DisplayObject._hitTestCanvas = canvas;
DisplayObject._hitTestContext = canvas.getContext("2d");
canvas.width = canvas.height = 1;
}
/**
* @property _nextCacheID
* @type {Number}
* @static
* @protected
**/
DisplayObject._nextCacheID = 1;
// events:
/**
* Dispatched when the user presses their left mouse button over the display object. See the
* {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event mousedown
* @since 0.6.0
*/
/**
* Dispatched when the user presses their left mouse button and then releases it while over the display object.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event click
* @since 0.6.0
*/
/**
* Dispatched when the user double clicks their left mouse button over this display object.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event dblclick
* @since 0.6.0
*/
/**
* Dispatched when the user's mouse enters this display object. This event must be enabled using
* {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}}.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event mouseover
* @since 0.6.0
*/
/**
* Dispatched when the user's mouse leaves this display object. This event must be enabled using
* {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event mouseout
* @since 0.6.0
*/
/**
* This event is similar to {{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}}, with the following
* differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an
* aggregate of their content.
*
* For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over
* shapeA and then directly on to shapeB. With a listener for {{#crossLink "mouseover:event"}}{{/crossLink}} on
* myContainer, two events would be received, each targeting a child element:<OL>
* <LI>when the mouse enters shapeA (target=shapeA)</LI>
* <LI>when the mouse enters shapeB (target=shapeB)</LI>
* </OL>
* However, with a listener for "rollover" instead, only a single event is received when the mouse first enters
* the aggregate myContainer content (target=myContainer).
*
* This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event rollover
* @since 0.7.0
*/
/**
* This event is similar to {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}, with the following
* differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an
* aggregate of their content.
*
* For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over
* shapeA, then directly on to shapeB, then off both. With a listener for {{#crossLink "mouseout:event"}}{{/crossLink}}
* on myContainer, two events would be received, each targeting a child element:<OL>
* <LI>when the mouse leaves shapeA (target=shapeA)</LI>
* <LI>when the mouse leaves shapeB (target=shapeB)</LI>
* </OL>
* However, with a listener for "rollout" instead, only a single event is received when the mouse leaves
* the aggregate myContainer content (target=myContainer).
*
* This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event rollout
* @since 0.7.0
*/
/**
* After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressmove
* event will be generated on that object whenever the mouse moves until the mouse press is released. This can be
* useful for dragging and similar operations.
* @event pressmove
* @since 0.7.0
*/
/**
* After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressup event
* will be generated on that object when that mouse press is released. This can be useful for dragging and similar
* operations.
* @event pressup
* @since 0.7.0
*/
/**
* Dispatched when the display object is added to a parent container.
* @event added
*/
/**
* Dispatched when the display object is removed from its parent container.
* @event removed
*/
/**
* Dispatched on each display object on a stage whenever the stage updates. This occurs immediately before the
* rendering (draw) pass. When {{#crossLink "Stage/update"}}{{/crossLink}} is called, first all display objects on
* the stage dispatch the tick event, then all of the display objects are drawn to stage. Children will have their
* {{#crossLink "tick:event"}}{{/crossLink}} event dispatched in order of their depth prior to the event being
* dispatched on their parent.
* @event tick
* @param {Object} target The object that dispatched the event.
* @param {String} type The event type.
* @param {Array} params An array containing any arguments that were passed to the Stage.update() method. For
* example if you called stage.update("hello"), then the params would be ["hello"].
* @since 0.6.0
*/
// getter / setters:
/**
* Use the {{#crossLink "DisplayObject/stage:property"}}{{/crossLink}} property instead.
* @method getStage
* @return {Stage}
* @deprecated
**/
p.getStage = function() {
// uses dynamic access to avoid circular dependencies;
var o = this, _Stage = createjs["Stage"];
while (o.parent) { o = o.parent; }
if (o instanceof _Stage) { return o; }
return null;
};
/**
* Returns the Stage instance that this display object will be rendered on, or null if it has not been added to one.
* @property stage
* @type {Stage}
* @readonly
**/
try {
Object.defineProperties(p, {
stage: { get: p.getStage }
});
} catch (e) {}
// public methods:
/**
* Returns true or false indicating whether the display object would be visible if drawn to a canvas.
* This does not account for whether it would be visible within the boundaries of the stage.
*
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method isVisible
* @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas
**/
p.isVisible = function() {
return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0);
};
/**
* Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform.
* Returns <code>true</code> if the draw was handled (useful for overriding functionality).
*
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method draw
* @param {<API key>} ctx The canvas 2D context object to draw into.
* @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example,
* used for drawing the cache (to prevent it from simply drawing an existing cache back into itself).
* @return {Boolean}
**/
p.draw = function(ctx, ignoreCache) {
var cacheCanvas = this.cacheCanvas;
if (ignoreCache || !cacheCanvas) { return false; }
var scale = this._cacheScale;
ctx.drawImage(cacheCanvas, this._cacheOffsetX+this._filterOffsetX, this._cacheOffsetY+this._filterOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale);
return true;
};
/**
* Applies this display object's transformation, alpha, <API key>, clipping path (mask), and shadow
* to the specified context. This is typically called prior to {{#crossLink "DisplayObject/draw"}}{{/crossLink}}.
* @method updateContext
* @param {<API key>} ctx The canvas 2D to update.
**/
p.updateContext = function(ctx) {
var o=this, mask=o.mask, mtx= o._props.matrix;
if (mask && mask.graphics && !mask.graphics.isEmpty()) {
mask.getMatrix(mtx);
ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
mask.graphics.drawAsPath(ctx);
ctx.clip();
mtx.invert();
ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
}
this.getMatrix(mtx);
var tx = mtx.tx, ty = mtx.ty;
if (DisplayObject._snapToPixelEnabled && o.snapToPixel) {
tx = tx + (tx < 0 ? -0.5 : 0.5) | 0;
ty = ty + (ty < 0 ? -0.5 : 0.5) | 0;
}
ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, tx, ty);
ctx.globalAlpha *= o.alpha;
if (o.compositeOperation) { ctx.<API key> = o.compositeOperation; }
if (o.shadow) { this._applyShadow(ctx, o.shadow); }
};
/**
* Draws the display object into a new canvas, which is then used for subsequent draws. For complex content
* that does not change frequently (ex. a Container with many children that do not move, or a complex vector Shape),
* this can provide for much faster rendering because the content does not need to be re-rendered each tick. The
* cached display object can be moved, rotated, faded, etc freely, however if its content changes, you must
* manually update the cache by calling <code>updateCache()</code> or <code>cache()</code> again. You must specify
* the cache area via the x, y, w, and h parameters. This defines the rectangle that will be rendered and cached
* using this display object's coordinates.
*
* <h4>Example</h4>
* For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25:
*
* var shape = new createjs.Shape();
* shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 25);
* myShape.cache(-25, -25, 50, 50);
*
* Note that filters need to be defined <em>before</em> the cache is applied. Check out the {{#crossLink "Filter"}}{{/crossLink}}
* class for more information. Some filters (ex. BlurFilter) will not work as expected in conjunction with the scale param.
*
* Usually, the resulting cacheCanvas will have the dimensions width*scale by height*scale, however some filters (ex. BlurFilter)
* will add padding to the canvas dimensions.
*
* @method cache
* @param {Number} x The x coordinate origin for the cache region.
* @param {Number} y The y coordinate origin for the cache region.
* @param {Number} width The width of the cache region.
* @param {Number} height The height of the cache region.
* @param {Number} [scale=1] The scale at which the cache will be created. For example, if you cache a vector shape using
* myShape.cache(0,0,100,100,2) then the resulting cacheCanvas will be 200x200 px. This lets you scale and rotate
* cached elements with greater fidelity. Default is 1.
**/
p.cache = function(x, y, width, height, scale) {
// draw to canvas.
scale = scale||1;
if (!this.cacheCanvas) { this.cacheCanvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); }
this._cacheWidth = width;
this._cacheHeight = height;
this._cacheOffsetX = x;
this._cacheOffsetY = y;
this._cacheScale = scale;
this.updateCache();
};
p.updateCache = function(compositeOperation) {
var cacheCanvas = this.cacheCanvas;
if (!cacheCanvas) { throw "cache() must be called before updateCache()"; }
var scale = this._cacheScale, offX = this._cacheOffsetX*scale, offY = this._cacheOffsetY*scale;
var w = this._cacheWidth, h = this._cacheHeight, ctx = cacheCanvas.getContext("2d");
var fBounds = this._getFilterBounds();
offX += (this._filterOffsetX = fBounds.x);
offY += (this._filterOffsetY = fBounds.y);
w = Math.ceil(w*scale) + fBounds.width;
h = Math.ceil(h*scale) + fBounds.height;
if (w != cacheCanvas.width || h != cacheCanvas.height) {
// TODO: it would be nice to preserve the content if there is a compositeOperation.
cacheCanvas.width = w;
cacheCanvas.height = h;
} else if (!compositeOperation) {
ctx.clearRect(0, 0, w+1, h+1);
}
ctx.save();
ctx.<API key> = compositeOperation;
ctx.setTransform(scale, 0, 0, scale, -offX, -offY);
this.draw(ctx, true);
// TODO: filters and cache scale don't play well together at present.
this._applyFilters();
ctx.restore();
this.cacheID = DisplayObject._nextCacheID++;
};
/**
* Clears the current cache. See {{#crossLink "DisplayObject/cache"}}{{/crossLink}} for more information.
* @method uncache
**/
p.uncache = function() {
this._cacheDataURL = this.cacheCanvas = null;
this.cacheID = this._cacheOffsetX = this._cacheOffsetY = this._filterOffsetX = this._filterOffsetY = 0;
this._cacheScale = 1;
};
/**
* Returns a data URL for the cache, or null if this display object is not cached.
* Uses cacheID to ensure a new data URL is not generated if the cache has not changed.
* @method getCacheDataURL
* @return {String} The image data url for the cache.
**/
p.getCacheDataURL = function() {
if (!this.cacheCanvas) { return null; }
if (this.cacheID != this._cacheDataURLID) { this._cacheDataURL = this.cacheCanvas.toDataURL(); }
return this._cacheDataURL;
};
/**
* Transforms the specified x and y position from the coordinate space of the display object
* to the global (stage) coordinate space. For example, this could be used to position an HTML label
* over a specific point on a nested display object. Returns a Point instance with x and y properties
* correlating to the transformed coordinates on the stage.
*
* <h4>Example</h4>
*
* displayObject.x = 300;
* displayObject.y = 200;
* stage.addChild(displayObject);
* var point = displayObject.localToGlobal(100, 100);
* // Results in x=400, y=300
*
* @method localToGlobal
* @param {Number} x The x position in the source display object to transform.
* @param {Number} y The y position in the source display object to transform.
* @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned.
* @return {Point} A Point instance with x and y properties correlating to the transformed coordinates
* on the stage.
**/
p.localToGlobal = function(x, y, pt) {
return this.<API key>(this._props.matrix).transformPoint(x,y, pt||new createjs.Point());
};
/**
* Transforms the specified x and y position from the global (stage) coordinate space to the
* coordinate space of the display object. For example, this could be used to determine
* the current mouse position within the display object. Returns a Point instance with x and y properties
* correlating to the transformed position in the display object's coordinate space.
*
* <h4>Example</h4>
*
* displayObject.x = 300;
* displayObject.y = 200;
* stage.addChild(displayObject);
* var point = displayObject.globalToLocal(100, 100);
* // Results in x=-200, y=-100
*
* @method globalToLocal
* @param {Number} x The x position on the stage to transform.
* @param {Number} y The y position on the stage to transform.
* @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned.
* @return {Point} A Point instance with x and y properties correlating to the transformed position in the
* display object's coordinate space.
**/
p.globalToLocal = function(x, y, pt) {
return this.<API key>(this._props.matrix).invert().transformPoint(x,y, pt||new createjs.Point());
};
/**
* Transforms the specified x and y position from the coordinate space of this display object to the coordinate
* space of the target display object. Returns a Point instance with x and y properties correlating to the
* transformed position in the target's coordinate space. Effectively the same as using the following code with
* {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}.
*
* var pt = this.localToGlobal(x, y);
* pt = target.globalToLocal(pt.x, pt.y);
*
* @method localToLocal
* @param {Number} x The x position in the source display object to transform.
* @param {Number} y The y position on the source display object to transform.
* @param {DisplayObject} target The target display object to which the coordinates will be transformed.
* @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned.
* @return {Point} Returns a Point instance with x and y properties correlating to the transformed position
* in the target's coordinate space.
**/
p.localToLocal = function(x, y, target, pt) {
pt = this.localToGlobal(x, y, pt);
return target.globalToLocal(pt.x, pt.y, pt);
};
/**
* Shortcut method to quickly set the transform properties on the display object. All parameters are optional.
* Omitted parameters will have the default value set.
*
* <h4>Example</h4>
*
* displayObject.setTransform(100, 100, 2, 2);
*
* @method setTransform
* @param {Number} [x=0] The horizontal translation (x position) in pixels
* @param {Number} [y=0] The vertical translation (y position) in pixels
* @param {Number} [scaleX=1] The horizontal scale, as a percentage of 1
* @param {Number} [scaleY=1] the vertical scale, as a percentage of 1
* @param {Number} [rotation=0] The rotation, in degrees
* @param {Number} [skewX=0] The horizontal skew factor
* @param {Number} [skewY=0] The vertical skew factor
* @param {Number} [regX=0] The horizontal registration point in pixels
* @param {Number} [regY=0] The vertical registration point in pixels
* @return {DisplayObject} Returns this instance. Useful for chaining commands.
* @chainable
*/
p.setTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) {
this.x = x || 0;
this.y = y || 0;
this.scaleX = scaleX == null ? 1 : scaleX;
this.scaleY = scaleY == null ? 1 : scaleY;
this.rotation = rotation || 0;
this.skewX = skewX || 0;
this.skewY = skewY || 0;
this.regX = regX || 0;
this.regY = regY || 0;
return this;
};
/**
* Returns a matrix based on this object's current transform.
* @method getMatrix
* @param {Matrix2D} matrix Optional. A Matrix2D object to populate with the calculated values. If null, a new
* Matrix object is returned.
* @return {Matrix2D} A matrix representing this display object's transform.
**/
p.getMatrix = function(matrix) {
var o = this, mtx = matrix&&matrix.identity() || new createjs.Matrix2D();
return o.transformMatrix ? mtx.copy(o.transformMatrix) : mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY);
};
/**
* Generates a Matrix2D object representing the combined transform of the display object and all of its
* parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}). This can
* be used to transform positions between coordinate spaces, such as with {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}}
* and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}.
* @method <API key>
* @param {Matrix2D} [matrix] A {{#crossLink "Matrix2D"}}{{/crossLink}} object to populate with the calculated values.
* If null, a new Matrix2D object is returned.
* @return {Matrix2D} The combined matrix.
**/
p.<API key> = function(matrix) {
var o = this, mtx = this.getMatrix(matrix);
while (o = o.parent) {
mtx.prependMatrix(o.getMatrix(o._props.matrix));
}
return mtx;
};
/**
* Generates a DisplayProps object representing the combined display properties of the object and all of its
* parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}).
* @method <API key>
* @param {DisplayProps} [props] A {{#crossLink "DisplayProps"}}{{/crossLink}} object to populate with the calculated values.
* If null, a new DisplayProps object is returned.
* @return {DisplayProps} The combined display properties.
**/
p.<API key> = function(props) {
props = props ? props.identity() : new createjs.DisplayProps();
var o = this, mtx = o.getMatrix(props.matrix);
do {
props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation);
// we do this to avoid problems with the matrix being used for both operations when o._props.matrix is passed in as the props param.
// this could be simplified (ie. just done as part of the prepend above) if we switched to using a pool.
if (o != this) { mtx.prependMatrix(o.getMatrix(o._props.matrix)); }
} while (o = o.parent);
return props;
};
/**
* Tests whether the display object intersects the specified point in local coordinates (ie. draws a pixel with alpha > 0 at
* the specified position). This ignores the alpha, shadow, hitArea, mask, and compositeOperation of the display object.
*
* <h4>Example</h4>
*
* stage.addEventListener("stagemousedown", handleMouseDown);
* function handleMouseDown(event) {
* var hit = myShape.hitTest(event.stageX, event.stageY);
* }
*
* Please note that shape-to-shape collision is not currently supported by EaselJS.
* @method hitTest
* @param {Number} x The x position to check in the display object's local coordinates.
* @param {Number} y The y position to check in the display object's local coordinates.
* @return {Boolean} A Boolean indicating whether a visible portion of the DisplayObject intersect the specified
* local Point.
*/
p.hitTest = function(x, y) {
var ctx = DisplayObject._hitTestContext;
ctx.setTransform(1, 0, 0, 1, -x, -y);
this.draw(ctx);
var hit = this._testHit(ctx);
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, 2, 2);
return hit;
};
/**
* Provides a chainable shortcut method for setting a number of properties on the instance.
*
* <h4>Example</h4>
*
* var myGraphics = new createjs.Graphics().beginFill("#ff0000").drawCircle(0, 0, 25);
* var shape = stage.addChild(new Shape()).set({graphics:myGraphics, x:100, y:100, alpha:0.5});
*
* @method set
* @param {Object} props A generic object containing properties to copy to the DisplayObject instance.
* @return {DisplayObject} Returns the instance the method is called on (useful for chaining calls.)
* @chainable
*/
p.set = function(props) {
for (var n in props) { this[n] = props[n]; }
return this;
};
/**
* Returns a rectangle representing this object's bounds in its local coordinate system (ie. with no transformation).
* Objects that have been cached will return the bounds of the cache.
*
* Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use
* {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container
* bounds.
*
* <table>
* <tr><td><b>All</b></td><td>
* All display objects support setting bounds manually using setBounds(). Likewise, display objects that
* have been cached using cache() will return the bounds of their cache. Manual and cache bounds will override
* the automatic calculations listed below.
* </td></tr>
* <tr><td><b>Bitmap</b></td><td>
* Returns the width and height of the sourceRect (if specified) or image, extending from (x=0,y=0).
* </td></tr>
* <tr><td><b>Sprite</b></td><td>
* Returns the bounds of the current frame. May have non-zero x/y if a frame registration point was specified
* in the spritesheet data. See also {{#crossLink "SpriteSheet/getFrameBounds"}}{{/crossLink}}
* </td></tr>
* <tr><td><b>Container</b></td><td>
* Returns the aggregate (combined) bounds of all children that return a non-null value from getBounds().
* </td></tr>
* <tr><td><b>Shape</b></td><td>
* Does not currently support automatic bounds calculations. Use setBounds() to manually define bounds.
* </td></tr>
* <tr><td><b>Text</b></td><td>
* Returns approximate bounds. Horizontal values (x/width) are quite accurate, but vertical values (y/height) are
* not, especially when using textBaseline values other than "top".
* </td></tr>
* <tr><td><b>BitmapText</b></td><td>
* Returns approximate bounds. Values will be more accurate if spritesheet frame registration points are close
* to (x=0,y=0).
* </td></tr>
* </table>
*
* Bounds can be expensive to calculate for some objects (ex. text, or containers with many children), and
* are recalculated each time you call getBounds(). You can prevent recalculation on static objects by setting the
* bounds explicitly:
*
* var bounds = obj.getBounds();
* obj.setBounds(bounds.x, bounds.y, bounds.width, bounds.height);
* // getBounds will now use the set values, instead of recalculating
*
* To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its
* values if you need to retain it.
*
* var myBounds = obj.getBounds().clone();
* // OR:
* myRect.copy(obj.getBounds());
*
* @method getBounds
* @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this
* object.
**/
p.getBounds = function() {
if (this._bounds) { return this._rectangle.copy(this._bounds); }
var cacheCanvas = this.cacheCanvas;
if (cacheCanvas) {
var scale = this._cacheScale;
return this._rectangle.setValues(this._cacheOffsetX, this._cacheOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale);
}
return null;
};
/**
* Returns a rectangle representing this object's bounds in its parent's coordinate system (ie. with transformations applied).
* Objects that have been cached will return the transformed bounds of the cache.
*
* Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use
* {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container
* bounds.
*
* To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its
* values if you need to retain it.
*
* Container instances calculate aggregate bounds for all children that return bounds via getBounds.
* @method <API key>
* @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this object.
**/
p.<API key> = function() {
return this._getBounds();
};
/**
* Allows you to manually specify the bounds of an object that either cannot calculate their own bounds (ex. Shape &
* Text) for future reference, or so the object can be included in Container bounds. Manually set bounds will always
* override calculated bounds.
*
* The bounds should be specified in the object's local (untransformed) coordinates. For example, a Shape instance
* with a 25px radius circle centered at 0,0 would have bounds of (-25, -25, 50, 50).
* @method setBounds
* @param {Number} x The x origin of the bounds. Pass null to remove the manual bounds.
* @param {Number} y The y origin of the bounds.
* @param {Number} width The width of the bounds.
* @param {Number} height The height of the bounds.
**/
p.setBounds = function(x, y, width, height) {
if (x == null) { this._bounds = x; }
this._bounds = (this._bounds || new createjs.Rectangle()).setValues(x, y, width, height);
};
/**
* Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are
* reverted to their defaults (for example .parent). Caches are not maintained across clones, and some elements
* are copied by reference (masks, individual filter instances, hit area)
* @method clone
* @return {DisplayObject} A clone of the current DisplayObject instance.
**/
p.clone = function() {
return this._cloneProps(new DisplayObject());
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[DisplayObject (name="+ this.name +")]";
};
// private methods:
// separated so it can be used more easily in subclasses:
/**
* @method _cloneProps
* @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject
* instance copied into.
* @return {DisplayObject} o
* @protected
**/
p._cloneProps = function(o) {
o.alpha = this.alpha;
o.mouseEnabled = this.mouseEnabled;
o.tickEnabled = this.tickEnabled;
o.name = this.name;
o.regX = this.regX;
o.regY = this.regY;
o.rotation = this.rotation;
o.scaleX = this.scaleX;
o.scaleY = this.scaleY;
o.shadow = this.shadow;
o.skewX = this.skewX;
o.skewY = this.skewY;
o.visible = this.visible;
o.x = this.x;
o.y = this.y;
o.compositeOperation = this.compositeOperation;
o.snapToPixel = this.snapToPixel;
o.filters = this.filters==null?null:this.filters.slice(0);
o.mask = this.mask;
o.hitArea = this.hitArea;
o.cursor = this.cursor;
o._bounds = this._bounds;
return o;
};
/**
* @method _applyShadow
* @protected
* @param {<API key>} ctx
* @param {Shadow} shadow
**/
p._applyShadow = function(ctx, shadow) {
shadow = shadow || Shadow.identity;
ctx.shadowColor = shadow.color;
ctx.shadowOffsetX = shadow.offsetX;
ctx.shadowOffsetY = shadow.offsetY;
ctx.shadowBlur = shadow.blur;
};
/**
* @method _tick
* @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs.
* @protected
**/
p._tick = function(evtObj) {
// because tick can be really performance sensitive, check for listeners before calling dispatchEvent.
var ls = this._listeners;
if (ls && ls["tick"]) {
// reset & reuse the event object to avoid construction / GC costs:
evtObj.target = null;
evtObj.propagationStopped = evtObj.<API key> = false;
this.dispatchEvent(evtObj);
}
};
/**
* @method _testHit
* @protected
* @param {<API key>} ctx
* @return {Boolean}
**/
p._testHit = function(ctx) {
try {
var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1;
} catch (e) {
if (!DisplayObject.<API key>) {
throw "An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images.";
}
}
return hit;
};
/**
* @method _applyFilters
* @protected
**/
p._applyFilters = function() {
if (!this.filters || this.filters.length == 0 || !this.cacheCanvas) { return; }
var l = this.filters.length;
var ctx = this.cacheCanvas.getContext("2d");
var w = this.cacheCanvas.width;
var h = this.cacheCanvas.height;
for (var i=0; i<l; i++) {
this.filters[i].applyFilter(ctx, 0, 0, w, h);
}
};
/**
* @method _getFilterBounds
* @return {Rectangle}
* @protected
**/
p._getFilterBounds = function(rect) {
var l, filters = this.filters, bounds = this._rectangle.setValues(0,0,0,0);
if (!filters || !(l=filters.length)) { return bounds; }
for (var i=0; i<l; i++) {
var f = this.filters[i];
f.getBounds&&f.getBounds(bounds);
}
return bounds;
};
/**
* @method _getBounds
* @param {Matrix2D} matrix
* @param {Boolean} ignoreTransform If true, does not apply this object's transform.
* @return {Rectangle}
* @protected
**/
p._getBounds = function(matrix, ignoreTransform){
return this._transformBounds(this.getBounds(), matrix, ignoreTransform);
};
/**
* @method _transformBounds
* @param {Rectangle} bounds
* @param {Matrix2D} matrix
* @param {Boolean} ignoreTransform
* @return {Rectangle}
* @protected
**/
p._transformBounds = function(bounds, matrix, ignoreTransform) {
if (!bounds) { return bounds; }
var x = bounds.x, y = bounds.y, width = bounds.width, height = bounds.height, mtx = this._props.matrix;
mtx = ignoreTransform ? mtx.identity() : this.getMatrix(mtx);
if (x || y) { mtx.appendTransform(0,0,1,1,0,0,0,-x,-y); } // TODO: simplify this.
if (matrix) { mtx.prependMatrix(matrix); }
var x_a = width*mtx.a, x_b = width*mtx.b;
var y_c = height*mtx.c, y_d = height*mtx.d;
var tx = mtx.tx, ty = mtx.ty;
var minX = tx, maxX = tx, minY = ty, maxY = ty;
if ((x = x_a + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; }
if ((x = x_a + y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; }
if ((x = y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; }
if ((y = x_b + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; }
if ((y = x_b + y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; }
if ((y = y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; }
return bounds.setValues(minX, minY, maxX-minX, maxY-minY);
};
/**
* Indicates whether the display object has any mouse event listeners or a cursor.
* @method _isMouseOpaque
* @return {Boolean}
* @protected
**/
p.<API key> = function() {
var evts = DisplayObject._MOUSE_EVENTS;
for (var i= 0, l=evts.length; i<l; i++) {
if (this.hasEventListener(evts[i])) { return true; }
}
return !!this.cursor;
};
createjs.DisplayObject = createjs.promote(DisplayObject, "EventDispatcher");
}());
//
// Container.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* A Container is a nestable display list that allows you to work with compound display elements. For example you could
* group arm, leg, torso and head {{#crossLink "Bitmap"}}{{/crossLink}} instances together into a Person Container, and
* transform them as a group, while still being able to move the individual parts relative to each other. Children of
* containers have their <code>transform</code> and <code>alpha</code> properties concatenated with their parent
* Container.
*
* For example, a {{#crossLink "Shape"}}{{/crossLink}} with x=100 and alpha=0.5, placed in a Container with <code>x=50</code>
* and <code>alpha=0.7</code> will be rendered to the canvas at <code>x=150</code> and <code>alpha=0.35</code>.
* Containers have some overhead, so you generally shouldn't create a Container to hold a single child.
*
* <h4>Example</h4>
*
* var container = new createjs.Container();
* container.addChild(bitmapInstance, shapeInstance);
* container.x = 100;
*
* @class Container
* @extends DisplayObject
* @constructor
**/
function Container() {
this.<API key>();
// public properties:
/**
* The array of children in the display list. You should usually use the child management methods such as
* {{#crossLink "Container/addChild"}}{{/crossLink}}, {{#crossLink "Container/removeChild"}}{{/crossLink}},
* {{#crossLink "Container/swapChildren"}}{{/crossLink}}, etc, rather than accessing this directly, but it is
* included for advanced uses.
* @property children
* @type Array
* @default null
**/
this.children = [];
/**
* Indicates whether the children of this container are independently enabled for mouse/pointer interaction.
* If false, the children will be aggregated under the container - for example, a click on a child shape would
* trigger a click event on the container.
* @property mouseChildren
* @type Boolean
* @default true
**/
this.mouseChildren = true;
/**
* If false, the tick will not be propagated to children of this Container. This can provide some performance benefits.
* In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates
* on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling).
* @property tickChildren
* @type Boolean
* @default true
**/
this.tickChildren = true;
}
var p = createjs.extend(Container, createjs.DisplayObject);
// getter / setters:
/**
* Use the {{#crossLink "Container/numChildren:property"}}{{/crossLink}} property instead.
* @method getNumChildren
* @return {Number}
* @deprecated
**/
p.getNumChildren = function() {
return this.children.length;
};
/**
* Returns the number of children in the container.
* @property numChildren
* @type {Number}
* @readonly
**/
try {
Object.defineProperties(p, {
numChildren: { get: p.getNumChildren }
});
} catch (e) {}
// public methods:
/**
* Constructor alias for backwards compatibility. This method will be removed in future versions.
* Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}.
* @method initialize
* @deprecated in favour of `createjs.promote()`
**/
p.initialize = Container; // TODO: deprecated.
/**
* Returns true or false indicating whether the display object would be visible if drawn to a canvas.
* This does not account for whether it would be visible within the boundaries of the stage.
*
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method isVisible
* @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas
**/
p.isVisible = function() {
var hasContent = this.cacheCanvas || this.children.length;
return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent);
};
/**
* Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform.
* Returns true if the draw was handled (useful for overriding functionality).
*
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method draw
* @param {<API key>} ctx The canvas 2D context object to draw into.
* @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache.
* For example, used for drawing the cache (to prevent it from simply drawing an existing cache back
* into itself).
**/
p.draw = function(ctx, ignoreCache) {
if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; }
// this ensures we don't have issues with display list changes that occur during a draw:
var list = this.children.slice();
for (var i=0,l=list.length; i<l; i++) {
var child = list[i];
if (!child.isVisible()) { continue; }
// draw the child:
ctx.save();
child.updateContext(ctx);
child.draw(ctx);
ctx.restore();
}
return true;
};
/**
* Adds a child to the top of the display list.
*
* <h4>Example</h4>
*
* container.addChild(bitmapInstance);
*
* You can also add multiple children at once:
*
* container.addChild(bitmapInstance, shapeInstance, textInstance);
*
* @method addChild
* @param {DisplayObject} child The display object to add.
* @return {DisplayObject} The child that was added, or the last child if multiple children were added.
**/
p.addChild = function(child) {
if (child == null) { return child; }
var l = arguments.length;
if (l > 1) {
for (var i=0; i<l; i++) { this.addChild(arguments[i]); }
return arguments[l-1];
}
if (child.parent) { child.parent.removeChild(child); }
child.parent = this;
this.children.push(child);
child.dispatchEvent("added");
return child;
};
/**
* Adds a child to the display list at the specified index, bumping children at equal or greater indexes up one, and
* setting its parent to this Container.
*
* <h4>Example</h4>
*
* addChildAt(child1, index);
*
* You can also add multiple children, such as:
*
* addChildAt(child1, child2, ..., index);
*
* The index must be between 0 and numChildren. For example, to add myShape under otherShape in the display list,
* you could use:
*
* container.addChildAt(myShape, container.getChildIndex(otherShape));
*
* This would also bump otherShape's index up by one. Fails silently if the index is out of range.
*
* @method addChildAt
* @param {DisplayObject} child The display object to add.
* @param {Number} index The index to add the child at.
* @return {DisplayObject} Returns the last child that was added, or the last child if multiple children were added.
**/
p.addChildAt = function(child, index) {
var l = arguments.length;
var indx = arguments[l-1]; // can't use the same name as the index param or it replaces arguments[1]
if (indx < 0 || indx > this.children.length) { return arguments[l-2]; }
if (l > 2) {
for (var i=0; i<l-1; i++) { this.addChildAt(arguments[i], indx+i); }
return arguments[l-2];
}
if (child.parent) { child.parent.removeChild(child); }
child.parent = this;
this.children.splice(index, 0, child);
child.dispatchEvent("added");
return child;
};
/**
* Removes the specified child from the display list. Note that it is faster to use removeChildAt() if the index is
* already known.
*
* <h4>Example</h4>
*
* container.removeChild(child);
*
* You can also remove multiple children:
*
* removeChild(child1, child2, ...);
*
* Returns true if the child (or children) was removed, or false if it was not in the display list.
* @method removeChild
* @param {DisplayObject} child The child to remove.
* @return {Boolean} true if the child (or children) was removed, or false if it was not in the display list.
**/
p.removeChild = function(child) {
var l = arguments.length;
if (l > 1) {
var good = true;
for (var i=0; i<l; i++) { good = good && this.removeChild(arguments[i]); }
return good;
}
return this.removeChildAt(createjs.indexOf(this.children, child));
};
/**
* Removes the child at the specified index from the display list, and sets its parent to null.
*
* <h4>Example</h4>
*
* container.removeChildAt(2);
*
* You can also remove multiple children:
*
* container.removeChild(2, 7, ...)
*
* Returns true if the child (or children) was removed, or false if any index was out of range.
* @method removeChildAt
* @param {Number} index The index of the child to remove.
* @return {Boolean} true if the child (or children) was removed, or false if any index was out of range.
**/
p.removeChildAt = function(index) {
var l = arguments.length;
if (l > 1) {
var a = [];
for (var i=0; i<l; i++) { a[i] = arguments[i]; }
a.sort(function(a, b) { return b-a; });
var good = true;
for (var i=0; i<l; i++) { good = good && this.removeChildAt(a[i]); }
return good;
}
if (index < 0 || index > this.children.length-1) { return false; }
var child = this.children[index];
if (child) { child.parent = null; }
this.children.splice(index, 1);
child.dispatchEvent("removed");
return true;
};
/**
* Removes all children from the display list.
*
* <h4>Example</h4>
*
* container.removeAllChildren();
*
* @method removeAllChildren
**/
p.removeAllChildren = function() {
var kids = this.children;
while (kids.length) { this.removeChildAt(0); }
};
/**
* Returns the child at the specified index.
*
* <h4>Example</h4>
*
* container.getChildAt(2);
*
* @method getChildAt
* @param {Number} index The index of the child to return.
* @return {DisplayObject} The child at the specified index. Returns null if there is no child at the index.
**/
p.getChildAt = function(index) {
return this.children[index];
};
/**
* Returns the child with the specified name.
* @method getChildByName
* @param {String} name The name of the child to return.
* @return {DisplayObject} The child with the specified name.
**/
p.getChildByName = function(name) {
var kids = this.children;
for (var i=0,l=kids.length;i<l;i++) {
if(kids[i].name == name) { return kids[i]; }
}
return null;
};
/**
* Performs an array sort operation on the child list.
*
* <h4>Example: Display children with a higher y in front.</h4>
*
* var sortFunction = function(obj1, obj2, options) {
* if (obj1.y > obj2.y) { return 1; }
* if (obj1.y < obj2.y) { return -1; }
* return 0;
* }
* container.sortChildren(sortFunction);
*
* @method sortChildren
* @param {Function} sortFunction the function to use to sort the child list. See JavaScript's <code>Array.sort</code>
* documentation for details.
**/
p.sortChildren = function(sortFunction) {
this.children.sort(sortFunction);
};
/**
* Returns the index of the specified child in the display list, or -1 if it is not in the display list.
*
* <h4>Example</h4>
*
* var index = container.getChildIndex(child);
*
* @method getChildIndex
* @param {DisplayObject} child The child to return the index of.
* @return {Number} The index of the specified child. -1 if the child is not found.
**/
p.getChildIndex = function(child) {
return createjs.indexOf(this.children, child);
};
/**
* Swaps the children at the specified indexes. Fails silently if either index is out of range.
* @method swapChildrenAt
* @param {Number} index1
* @param {Number} index2
**/
p.swapChildrenAt = function(index1, index2) {
var kids = this.children;
var o1 = kids[index1];
var o2 = kids[index2];
if (!o1 || !o2) { return; }
kids[index1] = o2;
kids[index2] = o1;
};
/**
* Swaps the specified children's depth in the display list. Fails silently if either child is not a child of this
* Container.
* @method swapChildren
* @param {DisplayObject} child1
* @param {DisplayObject} child2
**/
p.swapChildren = function(child1, child2) {
var kids = this.children;
var index1,index2;
for (var i=0,l=kids.length;i<l;i++) {
if (kids[i] == child1) { index1 = i; }
if (kids[i] == child2) { index2 = i; }
if (index1 != null && index2 != null) { break; }
}
if (i==l) { return; } // TODO: throw error?
kids[index1] = child2;
kids[index2] = child1;
};
/**
* Changes the depth of the specified child. Fails silently if the child is not a child of this container, or the index is out of range.
* @param {DisplayObject} child
* @param {Number} index
* @method setChildIndex
**/
p.setChildIndex = function(child, index) {
var kids = this.children, l=kids.length;
if (child.parent != this || index < 0 || index >= l) { return; }
for (var i=0;i<l;i++) {
if (kids[i] == child) { break; }
}
if (i==l || i == index) { return; }
kids.splice(i,1);
kids.splice(index,0,child);
};
/**
* Returns true if the specified display object either is this container or is a descendent (child, grandchild, etc)
* of this container.
* @method contains
* @param {DisplayObject} child The DisplayObject to be checked.
* @return {Boolean} true if the specified display object either is this container or is a descendent.
**/
p.contains = function(child) {
while (child) {
if (child == this) { return true; }
child = child.parent;
}
return false;
};
/**
* Tests whether the display object intersects the specified local point (ie. draws a pixel with alpha > 0 at the
* specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all
* transform properties including regX/Y.
* @method hitTest
* @param {Number} x The x position to check in the display object's local coordinates.
* @param {Number} y The y position to check in the display object's local coordinates.
* @return {Boolean} A Boolean indicating whether there is a visible section of a DisplayObject that overlaps the specified
* coordinates.
**/
p.hitTest = function(x, y) {
// TODO: optimize to use the fast cache check where possible.
return (this.getObjectUnderPoint(x, y) != null);
};
/**
* Returns an array of all display objects under the specified coordinates that are in this container's display
* list. This routine ignores any display objects with {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}}
* set to `false`. The array will be sorted in order of visual depth, with the top-most display object at index 0.
* This uses shape based hit detection, and can be an expensive operation to run, so it is best to use it carefully.
* For example, if testing for objects under the mouse, test on tick (instead of on {{#crossLink "DisplayObject/mousemove:event"}}{{/crossLink}}),
* and only if the mouse's position has changed.
*
* <ul>
* <li>By default (mode=0) this method evaluates all display objects.</li>
* <li>By setting the `mode` parameter to `1`, the {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}}
* and {{#crossLink "mouseChildren:property"}}{{/crossLink}} properties will be respected.</li>
* <li>Setting the `mode` to `2` additionally excludes display objects that do not have active mouse event
* listeners or a {{#crossLink "DisplayObject:cursor:property"}}{{/crossLink}} property. That is, only objects
* that would normally intercept mouse interaction will be included. This can significantly improve performance
* in some cases by reducing the number of display objects that need to be tested.</li>
* </li>
*
* This method accounts for both {{#crossLink "DisplayObject/hitArea:property"}}{{/crossLink}} and {{#crossLink "DisplayObject/mask:property"}}{{/crossLink}}.
* @method <API key>
* @param {Number} x The x position in the container to test.
* @param {Number} y The y position in the container to test.
* @param {Number} [mode=0] The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects.
* @return {Array} An Array of DisplayObjects under the specified coordinates.
**/
p.<API key> = function(x, y, mode) {
var arr = [];
var pt = this.localToGlobal(x, y);
this.<API key>(pt.x, pt.y, arr, mode>0, mode==1);
return arr;
};
/**
* Similar to {{#crossLink "Container/<API key>"}}{{/crossLink}}, but returns only the top-most display
* object. This runs significantly faster than <code><API key>()</code>, but is still potentially an expensive
* operation. See {{#crossLink "Container/<API key>"}}{{/crossLink}} for more information.
* @method getObjectUnderPoint
* @param {Number} x The x position in the container to test.
* @param {Number} y The y position in the container to test.
* @param {Number} mode The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects.
* @return {DisplayObject} The top-most display object under the specified coordinates.
**/
p.getObjectUnderPoint = function(x, y, mode) {
var pt = this.localToGlobal(x, y);
return this.<API key>(pt.x, pt.y, null, mode>0, mode==1);
};
/**
* Docced in superclass.
*/
p.getBounds = function() {
return this._getBounds(null, true);
};
/**
* Docced in superclass.
*/
p.<API key> = function() {
return this._getBounds();
};
/**
* Returns a clone of this Container. Some properties that are specific to this instance's current context are
* reverted to their defaults (for example .parent).
* @method clone
* @param {Boolean} [recursive=false] If true, all of the descendants of this container will be cloned recursively. If false, the
* properties of the container will be cloned, but the new instance will not have any children.
* @return {Container} A clone of the current Container instance.
**/
p.clone = function(recursive) {
var o = this._cloneProps(new Container());
if (recursive) { this._cloneChildren(o); }
return o;
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Container (name="+ this.name +")]";
};
// private methods:
/**
* @method _tick
* @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs.
* @protected
**/
p._tick = function(evtObj) {
if (this.tickChildren) {
for (var i=this.children.length-1; i>=0; i
var child = this.children[i];
if (child.tickEnabled && child._tick) { child._tick(evtObj); }
}
}
this.DisplayObject__tick(evtObj);
};
/**
* Recursively clones all children of this container, and adds them to the target container.
* @method cloneChildren
* @protected
* @param {Container} o The target container.
**/
p._cloneChildren = function(o) {
if (o.children.length) { o.removeAllChildren(); }
var arr = o.children;
for (var i=0, l=this.children.length; i<l; i++) {
var clone = this.children[i].clone(true);
clone.parent = o;
arr.push(clone);
}
};
/**
* @method <API key>
* @param {Number} x
* @param {Number} y
* @param {Array} arr
* @param {Boolean} mouse If true, it will respect mouse interaction properties like mouseEnabled, mouseChildren, and active listeners.
* @param {Boolean} activeListener If true, there is an active mouse event listener on a parent object.
* @param {Number} currentDepth Indicates the current depth of the search.
* @return {DisplayObject}
* @protected
**/
p.<API key> = function(x, y, arr, mouse, activeListener, currentDepth) {
currentDepth = currentDepth || 0;
if (!currentDepth && !this._testMask(this, x, y)) { return null; }
var mtx, ctx = createjs.DisplayObject._hitTestContext;
activeListener = activeListener || (mouse&&this.<API key>());
// draw children one at a time, and check if we get a hit:
var children = this.children, l = children.length;
for (var i=l-1; i>=0; i
var child = children[i];
var hitArea = child.hitArea;
if (!child.visible || (!hitArea && !child.isVisible()) || (mouse && !child.mouseEnabled)) { continue; }
if (!hitArea && !this._testMask(child, x, y)) { continue; }
// if a child container has a hitArea then we only need to check its hitArea, so we can treat it as a normal DO:
if (!hitArea && child instanceof Container) {
var result = child.<API key>(x, y, arr, mouse, activeListener, currentDepth+1);
if (!arr && result) { return (mouse && !this.mouseChildren) ? this : result; }
} else {
if (mouse && !activeListener && !child.<API key>()) { continue; }
// TODO: can we pass displayProps forward, to avoid having to calculate this backwards every time? It's kind of a mixed bag. When we're only hunting for DOs with event listeners, it may not make sense.
var props = child.<API key>(child._props);
mtx = props.matrix;
if (hitArea) {
mtx.appendMatrix(hitArea.getMatrix(hitArea._props.matrix));
props.alpha = hitArea.alpha;
}
ctx.globalAlpha = props.alpha;
ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y);
(hitArea||child).draw(ctx);
if (!this._testHit(ctx)) { continue; }
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, 2, 2);
if (arr) { arr.push(child); }
else { return (mouse && !this.mouseChildren) ? this : child; }
}
}
return null;
};
/**
* @method _testMask
* @param {DisplayObject} target
* @param {Number} x
* @param {Number} y
* @return {Boolean} Indicates whether the x/y is within the masked region.
* @protected
**/
p._testMask = function(target, x, y) {
var mask = target.mask;
if (!mask || !mask.graphics || mask.graphics.isEmpty()) { return true; }
var mtx = this._props.matrix, parent = target.parent;
mtx = parent ? parent.<API key>(mtx) : mtx.identity();
mtx = mask.getMatrix(mask._props.matrix).prependMatrix(mtx);
var ctx = createjs.DisplayObject._hitTestContext;
ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y);
// draw the mask as a solid fill:
mask.graphics.drawAsPath(ctx);
ctx.fillStyle = "#000";
ctx.fill();
if (!this._testHit(ctx)) { return false; }
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, 2, 2);
return true;
};
/**
* @method _getBounds
* @param {Matrix2D} matrix
* @param {Boolean} ignoreTransform If true, does not apply this object's transform.
* @return {Rectangle}
* @protected
**/
p._getBounds = function(matrix, ignoreTransform) {
var bounds = this.<API key>();
if (bounds) { return this._transformBounds(bounds, matrix, ignoreTransform); }
var mtx = this._props.matrix;
mtx = ignoreTransform ? mtx.identity() : this.getMatrix(mtx);
if (matrix) { mtx.prependMatrix(matrix); }
var l = this.children.length, rect=null;
for (var i=0; i<l; i++) {
var child = this.children[i];
if (!child.visible || !(bounds = child._getBounds(mtx))) { continue; }
if (rect) { rect.extend(bounds.x, bounds.y, bounds.width, bounds.height); }
else { rect = bounds.clone(); }
}
return rect;
};
createjs.Container = createjs.promote(Container, "DisplayObject");
}());
//
// Stage.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* A stage is the root level {{#crossLink "Container"}}{{/crossLink}} for a display list. Each time its {{#crossLink "Stage/tick"}}{{/crossLink}}
* method is called, it will render its display list to its target canvas.
*
* <h4>Example</h4>
* This example creates a stage, adds a child to it, then uses {{#crossLink "Ticker"}}{{/crossLink}} to update the child
* and redraw the stage using {{#crossLink "Stage/update"}}{{/crossLink}}.
*
* var stage = new createjs.Stage("canvasElementId");
* var image = new createjs.Bitmap("imagePath.png");
* stage.addChild(image);
* createjs.Ticker.addEventListener("tick", handleTick);
* function handleTick(event) {
* image.x += 10;
* stage.update();
* }
*
* @class Stage
* @extends Container
* @constructor
* @param {HTMLCanvasElement | String | Object} canvas A canvas object that the Stage will render to, or the string id
* of a canvas object in the current document.
**/
function Stage(canvas) {
this.<API key>();
// public properties:
/**
* Indicates whether the stage should automatically clear the canvas before each render. You can set this to <code>false</code>
* to manually control clearing (for generative art, or when pointing multiple stages at the same canvas for
* example).
*
* <h4>Example</h4>
*
* var stage = new createjs.Stage("canvasId");
* stage.autoClear = false;
*
* @property autoClear
* @type Boolean
* @default true
**/
this.autoClear = true;
/**
* The canvas the stage will render to. Multiple stages can share a single canvas, but you must disable autoClear for all but the
* first stage that will be ticked (or they will clear each other's render).
*
* When changing the canvas property you must disable the events on the old canvas, and enable events on the
* new canvas or mouse events will not work as expected. For example:
*
* myStage.enableDOMEvents(false);
* myStage.canvas = anotherCanvas;
* myStage.enableDOMEvents(true);
*
* @property canvas
* @type HTMLCanvasElement | Object
**/
this.canvas = (typeof canvas == "string") ? document.getElementById(canvas) : canvas;
/**
* The current mouse X position on the canvas. If the mouse leaves the canvas, this will indicate the most recent
* position over the canvas, and mouseInBounds will be set to false.
* @property mouseX
* @type Number
* @readonly
**/
this.mouseX = 0;
/**
* The current mouse Y position on the canvas. If the mouse leaves the canvas, this will indicate the most recent
* position over the canvas, and mouseInBounds will be set to false.
* @property mouseY
* @type Number
* @readonly
**/
this.mouseY = 0;
/**
* Specifies the area of the stage to affect when calling update. This can be use to selectively
* re-draw specific regions of the canvas. If null, the whole canvas area is drawn.
* @property drawRect
* @type {Rectangle}
*/
this.drawRect = null;
/**
* Indicates whether display objects should be rendered on whole pixels. You can set the
* {{#crossLink "DisplayObject/snapToPixel"}}{{/crossLink}} property of
* display objects to false to enable/disable this behaviour on a per instance basis.
* @property snapToPixelEnabled
* @type Boolean
* @default false
**/
this.snapToPixelEnabled = false;
/**
* Indicates whether the mouse is currently within the bounds of the canvas.
* @property mouseInBounds
* @type Boolean
* @default false
**/
this.mouseInBounds = false;
/**
* If true, tick callbacks will be called on all display objects on the stage prior to rendering to the canvas.
* @property tickOnUpdate
* @type Boolean
* @default true
**/
this.tickOnUpdate = true;
/**
* If true, mouse move events will continue to be called when the mouse leaves the target canvas. See
* {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}}, and {{#crossLink "MouseEvent"}}{{/crossLink}}
* x/y/rawX/rawY.
* @property mouseMoveOutside
* @type Boolean
* @default false
**/
this.mouseMoveOutside = false;
/**
* Prevents selection of other elements in the html page if the user clicks and drags, or double clicks on the canvas.
* This works by calling `preventDefault()` on any mousedown events (or touch equivalent) originating on the canvas.
* @property preventSelection
* @type Boolean
* @default true
**/
this.preventSelection = true;
/**
* The hitArea property is not supported for Stage.
* @property hitArea
* @type {DisplayObject}
* @default null
*/
// private properties:
/**
* Holds objects with data for each active pointer id. Each object has the following properties:
* x, y, event, target, overTarget, overX, overY, inBounds, posEvtObj (native event that last updated position)
* @property _pointerData
* @type {Object}
* @private
*/
this._pointerData = {};
/**
* Number of active pointers.
* @property _pointerCount
* @type {Object}
* @private
*/
this._pointerCount = 0;
/**
* The ID of the primary pointer.
* @property _primaryPointerID
* @type {Object}
* @private
*/
this._primaryPointerID = null;
/**
* @property <API key>
* @protected
* @type Number
**/
this.<API key> = null;
/**
* @property _nextStage
* @protected
* @type Stage
**/
this._nextStage = null;
/**
* @property _prevStage
* @protected
* @type Stage
**/
this._prevStage = null;
// initialize:
this.enableDOMEvents(true);
}
var p = createjs.extend(Stage, createjs.Container);
/**
* <strong>REMOVED</strong>. Removed in favor of using `<API key>`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// events:
/**
* Dispatched when the user moves the mouse over the canvas.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event stagemousemove
* @since 0.6.0
*/
/**
* Dispatched when the user presses their left mouse button on the canvas. See the {{#crossLink "MouseEvent"}}{{/crossLink}}
* class for a listing of event properties.
* @event stagemousedown
* @since 0.6.0
*/
/**
* Dispatched when the user the user presses somewhere on the stage, then releases the mouse button anywhere that the page can detect it (this varies slightly between browsers).
* You can use {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}} to check whether the mouse is currently within the stage bounds.
* See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties.
* @event stagemouseup
* @since 0.6.0
*/
/**
* Dispatched when the mouse moves from within the canvas area (mouseInBounds == true) to outside it (mouseInBounds == false).
* This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}}
* class for a listing of event properties.
* @event mouseleave
* @since 0.7.0
*/
/**
* Dispatched when the mouse moves into the canvas area (mouseInBounds == false) from outside it (mouseInBounds == true).
* This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}}
* class for a listing of event properties.
* @event mouseenter
* @since 0.7.0
*/
/**
* Dispatched each update immediately before the tick event is propagated through the display list.
* You can call preventDefault on the event object to cancel propagating the tick event.
* @event tickstart
* @since 0.7.0
*/
/**
* Dispatched each update immediately after the tick event is propagated through the display list. Does not fire if
* tickOnUpdate is false. Precedes the "drawstart" event.
* @event tickend
* @since 0.7.0
*/
/**
* Dispatched each update immediately before the canvas is cleared and the display list is drawn to it.
* You can call preventDefault on the event object to cancel the draw.
* @event drawstart
* @since 0.7.0
*/
/**
* Dispatched each update immediately after the display list is drawn to the canvas and the canvas context is restored.
* @event drawend
* @since 0.7.0
*/
// getter / setters:
/**
* Specifies a target stage that will have mouse / touch interactions relayed to it after this stage handles them.
* This can be useful in cases where you have multiple layered canvases and want user interactions
* events to pass through. For example, this would relay mouse events from topStage to bottomStage:
*
* topStage.nextStage = bottomStage;
*
* To disable relaying, set nextStage to null.
*
* MouseOver, MouseOut, RollOver, and RollOut interactions are also passed through using the mouse over settings
* of the top-most stage, but are only processed if the target stage has mouse over interactions enabled.
* Considerations when using roll over in relay targets:<OL>
* <LI> The top-most (first) stage must have mouse over interactions enabled (via enableMouseOver)</LI>
* <LI> All stages that wish to participate in mouse over interaction must enable them via enableMouseOver</LI>
* <LI> All relay targets will share the frequency value of the top-most stage</LI>
* </OL>
* To illustrate, in this example the targetStage would process mouse over interactions at 10hz (despite passing
* 30 as it's desired frequency):
* topStage.nextStage = targetStage;
* topStage.enableMouseOver(10);
* targetStage.enableMouseOver(30);
*
* If the target stage's canvas is completely covered by this stage's canvas, you may also want to disable its
* DOM events using:
*
* targetStage.enableDOMEvents(false);
*
* @property nextStage
* @type {Stage}
**/
p._get_nextStage = function() {
return this._nextStage;
};
p._set_nextStage = function(value) {
if (this._nextStage) { this._nextStage._prevStage = null; }
if (value) { value._prevStage = this; }
this._nextStage = value;
};
try {
Object.defineProperties(p, {
nextStage: { get: p._get_nextStage, set: p._set_nextStage }
});
} catch (e) {} // TODO: use Log
// public methods:
p.update = function(props) {
if (!this.canvas) { return; }
if (this.tickOnUpdate) { this.tick(props); }
if (this.dispatchEvent("drawstart", false, true) === false) { return; }
createjs.DisplayObject._snapToPixelEnabled = this.snapToPixelEnabled;
var r = this.drawRect, ctx = this.canvas.getContext("2d");
ctx.setTransform(1, 0, 0, 1, 0, 0);
if (this.autoClear) {
if (r) { ctx.clearRect(r.x, r.y, r.width, r.height); }
else { ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1); }
}
ctx.save();
if (this.drawRect) {
ctx.beginPath();
ctx.rect(r.x, r.y, r.width, r.height);
ctx.clip();
}
this.updateContext(ctx);
this.draw(ctx, false);
ctx.restore();
this.dispatchEvent("drawend");
};
p.tick = function(props) {
if (!this.tickEnabled || this.dispatchEvent("tickstart", false, true) === false) { return; }
var evtObj = new createjs.Event("tick");
if (props) {
for (var n in props) {
if (props.hasOwnProperty(n)) { evtObj[n] = props[n]; }
}
}
this._tick(evtObj);
this.dispatchEvent("tickend");
};
/**
* Default event handler that calls the Stage {{#crossLink "Stage/update"}}{{/crossLink}} method when a {{#crossLink "DisplayObject/tick:event"}}{{/crossLink}}
* event is received. This allows you to register a Stage instance as a event listener on {{#crossLink "Ticker"}}{{/crossLink}}
* directly, using:
*
* Ticker.addEventListener("tick", myStage");
*
* Note that if you subscribe to ticks using this pattern, then the tick event object will be passed through to
* display object tick handlers, instead of <code>delta</code> and <code>paused</code> parameters.
* @property handleEvent
* @type Function
**/
p.handleEvent = function(evt) {
if (evt.type == "tick") { this.update(evt); }
};
/**
* Clears the target canvas. Useful if {{#crossLink "Stage/autoClear:property"}}{{/crossLink}} is set to `false`.
* @method clear
**/
p.clear = function() {
if (!this.canvas) { return; }
var ctx = this.canvas.getContext("2d");
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1);
};
/**
* Returns a data url that contains a Base64-encoded image of the contents of the stage. The returned data url can
* be specified as the src value of an image element.
* @method toDataURL
* @param {String} [backgroundColor] The background color to be used for the generated image. Any valid CSS color
* value is allowed. The default value is a transparent background.
* @param {String} [mimeType="image/png"] The MIME type of the image format to be create. The default is "image/png". If an unknown MIME type
* is passed in, or if the browser does not support the specified MIME type, the default value will be used.
* @return {String} a Base64 encoded image.
**/
p.toDataURL = function(backgroundColor, mimeType) {
var data, ctx = this.canvas.getContext('2d'), w = this.canvas.width, h = this.canvas.height;
if (backgroundColor) {
data = ctx.getImageData(0, 0, w, h);
var compositeOperation = ctx.<API key>;
ctx.<API key> = "destination-over";
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, w, h);
}
var dataURL = this.canvas.toDataURL(mimeType||"image/png");
if(backgroundColor) {
ctx.putImageData(data, 0, 0);
ctx.<API key> = compositeOperation;
}
return dataURL;
};
/**
* Enables or disables (by passing a frequency of 0) mouse over ({{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}}
* and {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}) and roll over events ({{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}}
* and {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}) for this stage's display list. These events can
* be expensive to generate, so they are disabled by default. The frequency of the events can be controlled
* independently of mouse move events via the optional `frequency` parameter.
*
* <h4>Example</h4>
*
* var stage = new createjs.Stage("canvasId");
* stage.enableMouseOver(10); // 10 updates per second
*
* @method enableMouseOver
* @param {Number} [frequency=20] Optional param specifying the maximum number of times per second to broadcast
* mouse over/out events. Set to 0 to disable mouse over events completely. Maximum is 50. A lower frequency is less
* responsive, but uses less CPU.
**/
p.enableMouseOver = function(frequency) {
if (this.<API key>) {
clearInterval(this.<API key>);
this.<API key> = null;
if (frequency == 0) {
this._testMouseOver(true);
}
}
if (frequency == null) { frequency = 20; }
else if (frequency <= 0) { return; }
var o = this;
this.<API key> = setInterval(function(){ o._testMouseOver(); }, 1000/Math.min(50,frequency));
};
/**
* Enables or disables the event listeners that stage adds to DOM elements (window, document and canvas). It is good
* practice to disable events when disposing of a Stage instance, otherwise the stage will continue to receive
* events from the page.
*
* When changing the canvas property you must disable the events on the old canvas, and enable events on the
* new canvas or mouse events will not work as expected. For example:
*
* myStage.enableDOMEvents(false);
* myStage.canvas = anotherCanvas;
* myStage.enableDOMEvents(true);
*
* @method enableDOMEvents
* @param {Boolean} [enable=true] Indicates whether to enable or disable the events. Default is true.
**/
p.enableDOMEvents = function(enable) {
if (enable == null) { enable = true; }
var n, o, ls = this._eventListeners;
if (!enable && ls) {
for (n in ls) {
o = ls[n];
o.t.removeEventListener(n, o.f, false);
}
this._eventListeners = null;
} else if (enable && !ls && this.canvas) {
var t = window.addEventListener ? window : document;
var _this = this;
ls = this._eventListeners = {};
ls["mouseup"] = {t:t, f:function(e) { _this._handleMouseUp(e)} };
ls["mousemove"] = {t:t, f:function(e) { _this._handleMouseMove(e)} };
ls["dblclick"] = {t:this.canvas, f:function(e) { _this._handleDoubleClick(e)} };
ls["mousedown"] = {t:this.canvas, f:function(e) { _this._handleMouseDown(e)} };
for (n in ls) {
o = ls[n];
o.t.addEventListener(n, o.f, false);
}
}
};
/**
* Stage instances cannot be cloned.
* @method clone
**/
p.clone = function() {
throw("Stage cannot be cloned.");
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Stage (name="+ this.name +")]";
};
// private methods:
/**
* @method _getElementRect
* @protected
* @param {HTMLElement} e
**/
p._getElementRect = function(e) {
var bounds;
try { bounds = e.<API key>(); } // this can fail on disconnected DOM elements in IE9
catch (err) { bounds = {top: e.offsetTop, left: e.offsetLeft, width:e.offsetWidth, height:e.offsetHeight}; }
var offX = (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || document.body.clientLeft || 0);
var offY = (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || document.body.clientTop || 0);
var styles = window.getComputedStyle ? getComputedStyle(e,null) : e.currentStyle; // IE <9 compatibility.
var padL = parseInt(styles.paddingLeft)+parseInt(styles.borderLeftWidth);
var padT = parseInt(styles.paddingTop)+parseInt(styles.borderTopWidth);
var padR = parseInt(styles.paddingRight)+parseInt(styles.borderRightWidth);
var padB = parseInt(styles.paddingBottom)+parseInt(styles.borderBottomWidth);
// note: in some browsers bounds properties are read only.
return {
left: bounds.left+offX+padL,
right: bounds.right+offX-padR,
top: bounds.top+offY+padT,
bottom: bounds.bottom+offY-padB
}
};
/**
* @method _getPointerData
* @protected
* @param {Number} id
**/
p._getPointerData = function(id) {
var data = this._pointerData[id];
if (!data) { data = this._pointerData[id] = {x:0,y:0}; }
return data;
};
/**
* @method _handleMouseMove
* @protected
* @param {MouseEvent} e
**/
p._handleMouseMove = function(e) {
if(!e){ e = window.event; }
this._handlePointerMove(-1, e, e.pageX, e.pageY);
};
/**
* @method _handlePointerMove
* @protected
* @param {Number} id
* @param {Event} e
* @param {Number} pageX
* @param {Number} pageY
* @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage.
**/
p._handlePointerMove = function(id, e, pageX, pageY, owner) {
if (this._prevStage && owner === undefined) { return; } // redundant listener.
if (!this.canvas) { return; }
var nextStage=this._nextStage, o=this._getPointerData(id);
var inBounds = o.inBounds;
this.<API key>(id, e, pageX, pageY);
if (inBounds || o.inBounds || this.mouseMoveOutside) {
if (id === -1 && o.inBounds == !inBounds) {
this._dispatchMouseEvent(this, (inBounds ? "mouseleave" : "mouseenter"), false, id, o, e);
}
this._dispatchMouseEvent(this, "stagemousemove", false, id, o, e);
this._dispatchMouseEvent(o.target, "pressmove", true, id, o, e);
}
nextStage&&nextStage._handlePointerMove(id, e, pageX, pageY, null);
};
/**
* @method <API key>
* @protected
* @param {Number} id
* @param {Event} e
* @param {Number} pageX
* @param {Number} pageY
**/
p.<API key> = function(id, e, pageX, pageY) {
var rect = this._getElementRect(this.canvas);
pageX -= rect.left;
pageY -= rect.top;
var w = this.canvas.width;
var h = this.canvas.height;
pageX /= (rect.right-rect.left)/w;
pageY /= (rect.bottom-rect.top)/h;
var o = this._getPointerData(id);
if (o.inBounds = (pageX >= 0 && pageY >= 0 && pageX <= w-1 && pageY <= h-1)) {
o.x = pageX;
o.y = pageY;
} else if (this.mouseMoveOutside) {
o.x = pageX < 0 ? 0 : (pageX > w-1 ? w-1 : pageX);
o.y = pageY < 0 ? 0 : (pageY > h-1 ? h-1 : pageY);
}
o.posEvtObj = e;
o.rawX = pageX;
o.rawY = pageY;
if (id === this._primaryPointerID || id === -1) {
this.mouseX = o.x;
this.mouseY = o.y;
this.mouseInBounds = o.inBounds;
}
};
/**
* @method _handleMouseUp
* @protected
* @param {MouseEvent} e
**/
p._handleMouseUp = function(e) {
this._handlePointerUp(-1, e, false);
};
/**
* @method _handlePointerUp
* @protected
* @param {Number} id
* @param {Event} e
* @param {Boolean} clear
* @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage.
**/
p._handlePointerUp = function(id, e, clear, owner) {
var nextStage = this._nextStage, o = this._getPointerData(id);
if (this._prevStage && owner === undefined) { return; } // redundant listener.
var target=null, oTarget = o.target;
if (!owner && (oTarget || nextStage)) { target = this.<API key>(o.x, o.y, null, true); }
if (o.down) { this._dispatchMouseEvent(this, "stagemouseup", false, id, o, e, target); o.down = false; }
if (target == oTarget) { this._dispatchMouseEvent(oTarget, "click", true, id, o, e); }
this._dispatchMouseEvent(oTarget, "pressup", true, id, o, e);
if (clear) {
if (id==this._primaryPointerID) { this._primaryPointerID = null; }
delete(this._pointerData[id]);
} else { o.target = null; }
nextStage&&nextStage._handlePointerUp(id, e, clear, owner || target && this);
};
/**
* @method _handleMouseDown
* @protected
* @param {MouseEvent} e
**/
p._handleMouseDown = function(e) {
this._handlePointerDown(-1, e, e.pageX, e.pageY);
};
/**
* @method _handlePointerDown
* @protected
* @param {Number} id
* @param {Event} e
* @param {Number} pageX
* @param {Number} pageY
* @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage.
**/
p._handlePointerDown = function(id, e, pageX, pageY, owner) {
//change by wangx
if (this.preventSelection) { e.preventDefault(); }
if (this._primaryPointerID == null || id === -1) { this._primaryPointerID = id; } // mouse always takes over.
if (pageY != null) { this.<API key>(id, e, pageX, pageY); }
var target = null, nextStage = this._nextStage, o = this._getPointerData(id);
if (!owner) { target = o.target = this.<API key>(o.x, o.y, null, true); }
if (o.inBounds) { this._dispatchMouseEvent(this, "stagemousedown", false, id, o, e, target); o.down = true; }
this._dispatchMouseEvent(target, "mousedown", true, id, o, e);
nextStage&&nextStage._handlePointerDown(id, e, pageX, pageY, owner || target && this);
};
/**
* @method _testMouseOver
* @param {Boolean} clear If true, clears the mouseover / rollover (ie. no target)
* @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage.
* @param {Stage} eventTarget The stage that the cursor is actively over.
* @protected
**/
p._testMouseOver = function(clear, owner, eventTarget) {
if (this._prevStage && owner === undefined) { return; } // redundant listener.
var nextStage = this._nextStage;
if (!this.<API key>) {
// not enabled for mouseover, but should still relay the event.
nextStage&&nextStage._testMouseOver(clear, owner, eventTarget);
return;
}
var o = this._getPointerData(-1);
// only update if the mouse position has changed. This provides a lot of optimization, but has some trade-offs.
if (!o || (!clear && this.mouseX == this._mouseOverX && this.mouseY == this._mouseOverY && this.mouseInBounds)) { return; }
var e = o.posEvtObj;
var isEventTarget = eventTarget || e&&(e.target == this.canvas);
var target=null, common = -1, cursor="", t, i, l;
if (!owner && (clear || this.mouseInBounds && isEventTarget)) {
target = this.<API key>(this.mouseX, this.mouseY, null, true);
this._mouseOverX = this.mouseX;
this._mouseOverY = this.mouseY;
}
var oldList = this._mouseOverTarget||[];
var oldTarget = oldList[oldList.length-1];
var list = this._mouseOverTarget = [];
// generate ancestor list and check for cursor:
t = target;
while (t) {
list.unshift(t);
if (!cursor) { cursor = t.cursor; }
t = t.parent;
}
this.canvas.style.cursor = cursor;
if (!owner && eventTarget) { eventTarget.canvas.style.cursor = cursor; }
// find common ancestor:
for (i=0,l=list.length; i<l; i++) {
if (list[i] != oldList[i]) { break; }
common = i;
}
if (oldTarget != target) {
this._dispatchMouseEvent(oldTarget, "mouseout", true, -1, o, e, target);
}
for (i=oldList.length-1; i>common; i
this._dispatchMouseEvent(oldList[i], "rollout", false, -1, o, e, target);
}
for (i=list.length-1; i>common; i
this._dispatchMouseEvent(list[i], "rollover", false, -1, o, e, oldTarget);
}
if (oldTarget != target) {
this._dispatchMouseEvent(target, "mouseover", true, -1, o, e, oldTarget);
}
nextStage&&nextStage._testMouseOver(clear, owner || target && this, eventTarget || isEventTarget && this);
};
/**
* @method _handleDoubleClick
* @protected
* @param {MouseEvent} e
* @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage.
**/
p._handleDoubleClick = function(e, owner) {
var target=null, nextStage=this._nextStage, o=this._getPointerData(-1);
if (!owner) {
target = this.<API key>(o.x, o.y, null, true);
this._dispatchMouseEvent(target, "dblclick", true, -1, o, e);
}
nextStage&&nextStage._handleDoubleClick(e, owner || target && this);
};
/**
* @method _dispatchMouseEvent
* @protected
* @param {DisplayObject} target
* @param {String} type
* @param {Boolean} bubbles
* @param {Number} pointerId
* @param {Object} o
* @param {MouseEvent} [nativeEvent]
* @param {DisplayObject} [relatedTarget]
**/
p._dispatchMouseEvent = function(target, type, bubbles, pointerId, o, nativeEvent, relatedTarget) {
// TODO: might be worth either reusing MouseEvent instances, or adding a willTrigger method to avoid GC.
if (!target || (!bubbles && !target.hasEventListener(type))) { return; }
/*
// TODO: account for stage transformations?
this._mtx = this.<API key>(this._mtx).invert();
var pt = this._mtx.transformPoint(o.x, o.y);
var evt = new createjs.MouseEvent(type, bubbles, false, pt.x, pt.y, nativeEvent, pointerId, pointerId==this._primaryPointerID || pointerId==-1, o.rawX, o.rawY);
*/
var evt = new createjs.MouseEvent(type, bubbles, false, o.x, o.y, nativeEvent, pointerId, pointerId === this._primaryPointerID || pointerId === -1, o.rawX, o.rawY, relatedTarget);
target.dispatchEvent(evt);
};
createjs.Stage = createjs.promote(Stage, "Container");
}());
//
// Shape.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* A Shape allows you to display vector art in the display list. It composites a {{#crossLink "Graphics"}}{{/crossLink}}
* instance which exposes all of the vector drawing methods. The Graphics instance can be shared between multiple Shape
* instances to display the same vector graphics with different positions or transforms.
*
* If the vector art will not
* change between draws, you may want to use the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method to reduce the
* rendering cost.
*
* <h4>Example</h4>
*
* var graphics = new createjs.Graphics().beginFill("#ff0000").drawRect(0, 0, 100, 100);
* var shape = new createjs.Shape(graphics);
*
* //Alternatively use can also use the graphics property of the Shape class to renderer the same as above.
* var shape = new createjs.Shape();
* shape.graphics.beginFill("#ff0000").drawRect(0, 0, 100, 100);
*
* @class Shape
* @extends DisplayObject
* @constructor
* @param {Graphics} graphics Optional. The graphics instance to display. If null, a new Graphics instance will be created.
**/
function Shape(graphics) {
this.<API key>();
// public properties:
/**
* The graphics instance to display.
* @property graphics
* @type Graphics
**/
this.graphics = graphics ? graphics : new createjs.Graphics();
}
var p = createjs.extend(Shape, createjs.DisplayObject);
// TODO: deprecated
// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.
// public methods:
/**
* Returns true or false indicating whether the Shape would be visible if drawn to a canvas.
* This does not account for whether it would be visible within the boundaries of the stage.
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method isVisible
* @return {Boolean} Boolean indicating whether the Shape would be visible if drawn to a canvas
**/
p.isVisible = function() {
var hasContent = this.cacheCanvas || (this.graphics && !this.graphics.isEmpty());
return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent);
};
/**
* Draws the Shape into the specified context ignoring its visible, alpha, shadow, and transform. Returns true if
* the draw was handled (useful for overriding functionality).
*
* <i>NOTE: This method is mainly for internal use, though it may be useful for advanced uses.</i>
* @method draw
* @param {<API key>} ctx The canvas 2D context object to draw into.
* @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example,
* used for drawing the cache (to prevent it from simply drawing an existing cache back into itself).
* @return {Boolean}
**/
p.draw = function(ctx, ignoreCache) {
if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; }
this.graphics.draw(ctx, this);
return true;
};
/**
* Returns a clone of this Shape. Some properties that are specific to this instance's current context are reverted to
* their defaults (for example .parent).
* @method clone
* @param {Boolean} recursive If true, this Shape's {{#crossLink "Graphics"}}{{/crossLink}} instance will also be
* cloned. If false, the Graphics instance will be shared with the new Shape.
**/
p.clone = function(recursive) {
var g = (recursive && this.graphics) ? this.graphics.clone() : this.graphics;
return this._cloneProps(new Shape(g));
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Shape (name="+ this.name +")]";
};
createjs.Shape = createjs.promote(Shape, "DisplayObject");
}());
//
// Touch.js
//
//this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor:
/**
* Global utility for working with multi-touch enabled devices in EaselJS. Currently supports W3C Touch API (iOS and
* modern Android browser) and the Pointer API (IE), including ms-prefixed events in IE10, and unprefixed in IE11.
*
* Ensure that you {{#crossLink "Touch/disable"}}{{/crossLink}} touch when cleaning up your application. You do not have
* to check if touch is supported to enable it, as it will fail gracefully if it is not supported.
*
* <h4>Example</h4>
*
* var stage = new createjs.Stage("canvasId");
* createjs.Touch.enable(stage);
*
* <strong>Note:</strong> It is important to disable Touch on a stage that you are no longer using:
*
* createjs.Touch.disable(stage);
*
* @class Touch
* @static
**/
function Touch() {
throw "Touch cannot be instantiated";
}
// public static methods:
/**
* Returns `true` if touch is supported in the current browser.
* @method isSupported
* @return {Boolean} Indicates whether touch is supported in the current browser.
* @static
**/
Touch.isSupported = function() {
return !!('ontouchstart' in window); // iOS & Android; // IE11+
};
Touch.isMove=false;
/**
* Enables touch interaction for the specified EaselJS {{#crossLink "Stage"}}{{/crossLink}}. Currently supports iOS
* (and compatible browsers, such as modern Android browsers), and IE10/11. Supports both single touch and
* multi-touch modes. Extends the EaselJS {{#crossLink "MouseEvent"}}{{/crossLink}} model, but without support for
* double click or over/out events. See the MouseEvent {{#crossLink "MouseEvent/pointerId:property"}}{{/crossLink}}
* for more information.
* @method enable
* @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to enable touch on.
* @param {Boolean} [singleTouch=false] If `true`, only a single touch will be active at a time.
* @param {Boolean} [allowDefault=false] If `true`, then default gesture actions (ex. scrolling, zooming) will be
* allowed when the user is interacting with the target canvas.
* @return {Boolean} Returns `true` if touch was successfully enabled on the target stage.
* @static
**/
Touch.enable = function(stage, singleTouch, allowDefault) {
if (!stage || !stage.canvas || !Touch.isSupported()) { return false; }
if (stage.__touch) { return true; }
// inject required properties on stage:
stage.__touch = {pointers:{}, multitouch:!singleTouch, preventDefault:!allowDefault, count:0};
// note that in the future we may need to disable the standard mouse event model before adding
// these to prevent duplicate calls. It doesn't seem to be an issue with iOS devices though.
if ('ontouchstart' in window) { Touch._IOS_enable(stage); }
return true;
};
/**
* Removes all listeners that were set up when calling `Touch.enable()` on a stage.
* @method disable
* @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to disable touch on.
* @static
**/
Touch.disable = function(stage) {
if (!stage) { return; }
if ('ontouchstart' in window) { Touch._IOS_disable(stage); }
delete stage.__touch;
};
// Private static methods:
/**
* @method _IOS_enable
* @protected
* @param {Stage} stage
* @static
**/
Touch._IOS_enable = function(stage) {
var canvas = stage.canvas;
var f = stage.__touch.f = function(e) { Touch._IOS_handleEvent(stage,e); };
canvas.addEventListener("touchstart", f, false);
canvas.addEventListener("touchmove", f, false);
canvas.addEventListener("touchend", f, false);
canvas.addEventListener("touchcancel", f, false);
};
/**
* @method _IOS_disable
* @protected
* @param {Stage} stage
* @static
**/
Touch._IOS_disable = function(stage) {
var canvas = stage.canvas;
if (!canvas) { return; }
var f = stage.__touch.f;
canvas.removeEventListener("touchstart", f, false);
canvas.removeEventListener("touchmove", f, false);
canvas.removeEventListener("touchend", f, false);
canvas.removeEventListener("touchcancel", f, false);
};
/**
* @method _IOS_handleEvent
* @param {Stage} stage
* @param {Object} e The event to handle
* @protected
* @static
**/
Touch._IOS_handleEvent = function(stage, e) {
if (!stage) { return; }
//if (stage.__touch.preventDefault) { e.preventDefault&&e.preventDefault(); }
var touches = e.changedTouches;
var type = e.type;
for (var i= 0,l=touches.length; i<l; i++) {
var touch = touches[i];
var id = touch.identifier;
if (touch.target != stage.canvas) { continue; }
if (type == "touchstart") {
this._handleStart(stage, id, e, touch.pageX, touch.pageY);
} else if (type == "touchmove") {
this._handleMove(stage, id, e, touch.pageX, touch.pageY);
} else if (type == "touchend" || type == "touchcancel") {
this._handleEnd(stage, id, e, touch.pageX, touch.pageY);
}
}
};
/**
* @method _handleStart
* @param {Stage} stage
* @param {String|Number} id
* @param {Object} e
* @param {Number} x
* @param {Number} y
* @protected
**/
Touch._handleStart = function(stage, id, e, x, y) {
this.isMove=false;
};
/**
* @method _handleMove
* @param {Stage} stage
* @param {String|Number} id
* @param {Object} e
* @param {Number} x
* @param {Number} y
* @protected
**/
Touch._handleMove = function(stage, id, e, x, y) {
this.isMove=true;
};
/**
* @method _handleEnd
* @param {Stage} stage
* @param {String|Number} id
* @param {Object} e
* @protected
**/
Touch._handleEnd = function(stage, id, e,x,y) {
if(!this.isMove){
var _this=stage;
if (_this._primaryPointerID == null || id === -1) { _this._primaryPointerID = id; } // mouse always takes over.
if (y != null) { _this.<API key>(id, e, x, y); }
var target = null, o = _this._getPointerData(id);
target = o.target = _this.<API key>(o.x, o.y, null, true);
if (target) { _this._dispatchMouseEvent(target, "click", true, id, o, e); }
_this=null;
target=null;
o=null;
}
};
createjs.Touch = Touch;
}());
//
// version.js
//
//this.createjs = this.createjs || {};
(function() {
"use strict";
/**
* Static class holding library specific information such as the version and buildDate of
* the library.
* @class EaselJS
**/
var s = createjs.EaselJS = createjs.EaselJS || {};
/**
* The version string for this release.
* @property version
* @type String
* @static
**/
s.version = /*=version*/"0.8.1"; // injected by build process
/**
* The build date for this release in UTC format.
* @property buildDate
* @type String
* @static
**/
s.buildDate = /*=date*/"Tue, 22 Dec 2015 08:26:22 GMT"; // injected by build process
})();
if ( typeof module != 'undefined' && module.exports ) {
module.exports = createjs;
} else {
window.createjs = createjs;
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt-->
<title>Method Assets.refresh</title>
<link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/>
<link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/>
<script type="text/javascript" src="../../scripts/jquery.js"></script>
<script type="text/javascript" src="../../prettify/prettify.js"></script>
<script type="text/javascript" src="../../scripts/ddox.js"></script>
</head>
<body onload="prettyPrint(); setupDdox();">
<nav id="main-nav"><!-- using block navigation in layout.dt-->
<ul class="tree-view">
<li class=" tree-view">
<a href="#" class="package">components</a>
<ul class="tree-view">
<li>
<a href="../../components/animation.html" class=" module">animation</a>
</li>
<li>
<a href="../../components/assets.html" class="selected module">assets</a>
</li>
<li>
<a href="../../components/camera.html" class=" module">camera</a>
</li>
<li>
<a href="../../components/component.html" class=" module">component</a>
</li>
<li>
<a href="../../components/lights.html" class=" module">lights</a>
</li>
<li>
<a href="../../components/material.html" class=" module">material</a>
</li>
<li>
<a href="../../components/mesh.html" class=" module">mesh</a>
</li>
<li>
<a href="../../components/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">core</a>
<ul class="tree-view">
<li>
<a href="../../core/dgame.html" class=" module">dgame</a>
</li>
<li>
<a href="../../core/gameobject.html" class=" module">gameobject</a>
</li>
<li>
<a href="../../core/prefabs.html" class=" module">prefabs</a>
</li>
<li>
<a href="../../core/properties.html" class=" module">properties</a>
</li>
<li>
<a href="../../core/reflection.html" class=" module">reflection</a>
</li>
<li>
<a href="../../core/scene.html" class=" module">scene</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">graphics</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">adapters</a>
<ul class="tree-view">
<li>
<a href="../../graphics/adapters/adapter.html" class=" module">adapter</a>
</li>
<li>
<a href="../../graphics/adapters/linux.html" class=" module">linux</a>
</li>
<li>
<a href="../../graphics/adapters/mac.html" class=" module">mac</a>
</li>
<li>
<a href="../../graphics/adapters/win32.html" class=" module">win32</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">shaders</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">glsl</a>
<ul class="tree-view">
<li>
<a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/shaders/glsl.html" class=" module">glsl</a>
</li>
<li>
<a href="../../graphics/shaders/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/adapters.html" class=" module">adapters</a>
</li>
<li>
<a href="../../graphics/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../graphics/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">utility</a>
<ul class="tree-view">
<li>
<a href="../../utility/awesomium.html" class=" module">awesomium</a>
</li>
<li>
<a href="../../utility/concurrency.html" class=" module">concurrency</a>
</li>
<li>
<a href="../../utility/config.html" class=" module">config</a>
</li>
<li>
<a href="../../utility/filepath.html" class=" module">filepath</a>
</li>
<li>
<a href="../../utility/input.html" class=" module">input</a>
</li>
<li>
<a href="../../utility/output.html" class=" module">output</a>
</li>
<li>
<a href="../../utility/resources.html" class=" module">resources</a>
</li>
<li>
<a href="../../utility/string.html" class=" module">string</a>
</li>
<li>
<a href="../../utility/tasks.html" class=" module">tasks</a>
</li>
<li>
<a href="../../utility/time.html" class=" module">time</a>
</li>
</ul>
</li>
<li>
<a href="../../components.html" class=" module">components</a>
</li>
<li>
<a href="../../core.html" class=" module">core</a>
</li>
<li>
<a href="../../graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../utility.html" class=" module">utility</a>
</li>
</ul>
<noscript>
<p style="color: red">The search functionality needs JavaScript enabled</p>
</noscript>
<div id="symbolSearchPane" style="display: none">
<p>
<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
</p>
<ul id="symbolSearchResults" style="display: none"></ul>
<script type="application/javascript" src="../../symbols.js"></script>
<script type="application/javascript">
//< by Facebook.
Note: tests may not run with io.js |
Twig is a branch code coverage tool for Rubinius.
Usage
==
To run code coverage on the application started by `app.rb`, run the following:
twig app.rb |
package com.onelogin.saml2.util;
/**
* Constants class of OneLogin's Java Toolkit.
*
* A class that contains several constants related to the SAML protocol
*/
public final class Constants {
/**
* Value added to the current time in time condition validations.
*/
public static final Integer ALOWED_CLOCK_DRIFT = 180; // 3 min in seconds
// NameID Formats
public static final String <API key> = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
public static final String <API key> = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName";
public static final String <API key> = "urn:oasis:names:tc:SAML:1.1:nameid-format:<API key>";
public static final String NAMEID_UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified";
public static final String NAMEID_KERBEROS = "urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos";
public static final String NAMEID_ENTITY = "urn:oasis:names:tc:SAML:2.0:nameid-format:entity";
public static final String NAMEID_TRANSIENT = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient";
public static final String NAMEID_PERSISTENT = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent";
public static final String NAMEID_ENCRYPTED = "urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted";
// Attribute Name Formats
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified";
public static final String ATTRNAME_FORMAT_URI = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic";
// Namespaces
public static final String NS_SAML = "urn:oasis:names:tc:SAML:2.0:assertion";
public static final String NS_SAMLP = "urn:oasis:names:tc:SAML:2.0:protocol";
public static final String NS_SOAP = "http://schemas.xmlsoap.org/soap/envelope/";
public static final String NS_MD = "urn:oasis:names:tc:SAML:2.0:metadata";
public static final String NS_XS = "http:
public static final String NS_XSI = "http:
public static final String NS_XENC = "http://www.w3.org/2001/04/xmlenc
public static final String NS_DS = "http://www.w3.org/2000/09/xmldsig
// Bindings
public static final String BINDING_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact";
public static final String BINDING_SOAP = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
public static final String BINDING_DEFLATE = "urn:oasis:names:tc:SAML:2.0:bindings:URL-Encoding:DEFLATE";
// Auth Context Class
public static final String AC_UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified";
public static final String AC_PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password";
public static final String AC_X509 = "urn:oasis:names:tc:SAML:2.0:ac:classes:X509";
public static final String AC_SMARTCARD = "urn:oasis:names:tc:SAML:2.0:ac:classes:Smartcard";
public static final String AC_KERBEROS = "urn:oasis:names:tc:SAML:2.0:ac:classes:Kerberos";
// Subject Confirmation
public static final String CM_BEARER = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
public static final String CM_HOLDER_KEY = "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key";
public static final String CM_SENDER_VOUCHES = "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches";
// Status Codes
public static final String STATUS_SUCCESS = "urn:oasis:names:tc:SAML:2.0:status:Success";
public static final String STATUS_REQUESTER = "urn:oasis:names:tc:SAML:2.0:status:Requester";
public static final String STATUS_RESPONDER = "urn:oasis:names:tc:SAML:2.0:status:Responder";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:VersionMismatch";
// Status Second-level Codes
public static final String STATUS_AUTHNFAILED = "urn:oasis:names:tc:SAML:2.0:status:AuthnFailed";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:<API key>";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP";
public static final String STATUS_NO_PASSIVE = "urn:oasis:names:tc:SAML:2.0:status:NoPassive";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:NoSupportedIDP";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:PartialLogout";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:RequestDenied";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:<API key>";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:<API key>";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:<API key>";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:<API key>";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:TooManyResponses";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:UnknownAttrProfile";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal";
public static final String <API key> = "urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding";
// Contact types
public static final String <API key> = "technical";
public static final String <API key> = "support";
public static final String <API key> = "administrative";
public static final String <API key> = "billing";
public static final String CONTACT_TYPE_OTHER = "other";
// Canonization
public static final String C14N = "http:
public static final String C14N_WC = "http://www.w3.org/TR/2001/<API key>#WithComments";
public static final String C14N11 = "http:
public static final String C14N11_WC = "http://www.w3.org/2006/12/xml-c14n11#WithComments";
public static final String C14NEXC = "http://www.w3.org/2001/10/xml-exc-c14n
public static final String C14NEXC_WC = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
// Sign & Crypt
// https://www.w3.org/TR/xmlenc-core/#<API key>
// https://www.w3.org/TR/xmlsec-algorithms/#<API key>
public static final String SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1";
public static final String SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256";
public static final String SHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384";
public static final String SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512";
public static final String DSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
public static final String RSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
public static final String RSA_SHA256 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
public static final String RSA_SHA384 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384";
public static final String RSA_SHA512 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
public static final String TRIPLEDES_CBC = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
public static final String AES128_CBC = "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
public static final String AES192_CBC = "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
public static final String AES256_CBC = "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
public static final String A128KW = "http://www.w3.org/2001/04/xmlenc#kw-aes128";
public static final String A192KW = "http://www.w3.org/2001/04/xmlenc#kw-aes192";
public static final String A256KW = "http://www.w3.org/2001/04/xmlenc#kw-aes256";
public static final String RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
public static final String RSA_OAEP_MGF1P = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
public static final String ENVSIG = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
private Constants() {
//not called
}
} |
// HSLocationSearch.h
// Hot Spot
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface HSLocationSearchVC : UIViewController
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end |
<div class="commune_descr limited">
<p>
Saint-Martin-d'Oydes est
un village
situé dans le département de l'Ariège en Midi-Pyrénées. Elle comptait 248 habitants en 2008.</p>
<p>La commune offre quelques aménagements, elle propose entre autres un terrain de tennis et une boucle de randonnée.</p>
<p>Le nombre d'habitations, à Saint-Martin-d'Oydes, se décomposait en 2011 en quatorze appartements et 128 maisons soit
un marché plutôt équilibré.</p>
<p>Si vous envisagez de demenager à Saint-Martin-d'Oydes, vous pourrez facilement trouver une maison à vendre. </p>
<p>À coté de Saint-Martin-d'Oydes sont localisées les communes de
<a href="{{VLROOT}}/immobilier/escosse_09116/">Escosse</a> située à 6 km, 397 habitants,
<a href="{{VLROOT}}/immobilier/brie_09067/">Brie</a> située à 4 km, 164 habitants,
<a href="{{VLROOT}}/immobilier/bezac_09056/">Bézac</a> à 6 km, 270 habitants,
<a href="{{VLROOT}}/immobilier/<API key>/">Villeneuve-du-Latou</a> à 6 km, 107 habitants,
<a href="{{VLROOT}}/immobilier/justiniac_09146/">Justiniac</a> située à 4 km, 52 habitants,
<a href="{{VLROOT}}/immobilier/esplas_09117/">Esplas</a> à 1 km, 90 habitants,
entre autres. De plus, Saint-Martin-d'Oydes est située à seulement 29 km de <a href="{{VLROOT}}/immobilier/<API key>/">Fort-de-France</a>.</p>
</div> |
meta-title: JS Frameworks
title: JS Frameworks
layout: blank
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>The European Bioinformatics Institute < EMBL-EBI</title>
<meta name="description" content="EMBL-EBI" /><!-- Describe what this page is about -->
<meta name="keywords" content="bioinformatics, europe, institute" /><!-- 3 to 10 keywords about the content of this page (not the whole project) -->
<meta name="author" content="EMBL-EBI" /><!-- Your [project-name] here -->
<meta name="HandheldFriendly" content="true" />
<meta name="MobileOptimized" content="width" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="theme-color" content="#70BDBD" /> <!-- Android Chrome mobile browser tab color -->
<!-- Add information on the life cycle of this page -->
<meta name="ebi:owner" content="John Doe" /> <!-- Who should be contacted about changes -->
<meta name="ebi:review-cycle" content="30" /> <!-- In days, how often should the content be reviewed -->
<meta name="ebi:last-review" content="2015-12-20" /> <!-- The last time the content was reviewed -->
<meta name="ebi:expiry" content="2016-01-20" /> <!-- When this content is no longer relevant -->
<!-- If you link to any other sites frequently, consider optimising performance with a DNS prefetch -->
<link rel="dns-prefetch" href="
<!-- If you have custom icon, replace these as appropriate.
You can generate them at <API key>.net
<link rel="icon" type="image/x-icon" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/favicon.ico" />
<link rel="icon" type="image/png" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="192x192" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/<API key>.png" /> <!-- Android (192px) -->
<link rel="<API key>" sizes="114x114" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/apple-icon-114x114.png" /> <!-- For iPhone 4 Retina display (114px) -->
<link rel="<API key>" sizes="72x72" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/apple-icon-72x72.png" /> <!-- For iPad (72px) -->
<link rel="<API key>" sizes="144x144" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/apple-icon-144x144.png" /> <!-- For iPad retinat (144px) -->
<link rel="<API key>" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/apple-icon-57x57.png" /> <!-- For iPhone (57px) -->
<link rel="mask-icon" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/safari-pinned-tab.svg" color="#ffffff" /> <!-- Safari icon for pinned tab -->
<meta name="<API key>" content="#2b5797" /> <!-- MS Icons -->
<meta name="<API key>" content="//dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/images/logos/EMBL-EBI/favicons/mstile-144x144.png" />
<!-- CSS: implied media=all -->
<!-- CSS concatenated and minified via ant build script-->
<link rel="stylesheet" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/css/ebi-global.css" type="text/css" media="all" />
<link rel="stylesheet" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Icon-fonts/v1.2/fonts.css" type="text/css" media="all" />
<!-- Use this CSS file for any custom styling -->
<!
<link rel="stylesheet" href="css/custom.css" type="text/css" media="all" />
<!-- If you have a custom header image or colour -->
<!
<meta name="ebi:masthead-color" content="#000" />
<meta name="ebi:masthead-image" content="
<!-- also inform ES so we can host your colour palette file -->
<link rel="stylesheet" href="https://dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/css/theme-embl-petrol.css" type="text/css" media="all" />
<!-- end CSS-->
</head>
<body class="level2"><!-- add any of your classes or IDs -->
<div id="skip-to">
<a href="#content">Skip to main content</a>
</div>
<header id="masthead-black-bar" class="clearfix masthead-black-bar">
</header>
<div id="content">
<div <API key>>
<header id="masthead" class="masthead" data-sticky data-sticky-on="large" data-top-anchor="content:top" data-btm-anchor="content:bottom">
<div class="masthead-inner row">
<!-- local-title -->
<div class="columns medium-12" id="local-title">
<h1><a href="../../" title="Back to [service-name] homepage">EBI Framework</a></h1>
</div>
<!-- /local-title -->
<!-- local-nav -->
<nav >
<ul id="local-nav" class="dropdown menu float-left" data-description="navigational">
<li><a href="../../">Overview</a></li>
<li><a data-open="modal-download">Download</a></li>
<li><a href="#">Support <i class="icon icon-generic" data-icon="x"></i></a></li>
</ul>
</nav>
<!-- /local-nav -->
</div>
</header>
</div>
<!-- Suggested layout containers -->
<section id="main-content-area" class="row" role="main">
<!-- Your menu structure should make a breadcrumb redundant, but if a breadcrumb is needed uncomment the below -->
<nav aria-label="You are here:" role="navigation">
<ul class="breadcrumbs columns">
<li><a href="../../">EBI Framework</a></li>
<li><a href="../">Sample pages</a></li>
<li>
<span class="show-for-sr">Current: </span> Blank boilerplate
</li>
</ul>
</nav>
<div class="columns">
<section>
This is a stub. <a href="https://docs.google.com/document/d/<API key>/edit?usp=sharing" class="readmore">For now see the daft guidance</a>
</section>
</div>
</section>
<!
<footer id="local-footer" class="local-footer" role="local-footer">
<div class="row">
<span class="reference">How to reference this page: ...</span>
</div>
</footer>
<!-- End optional local footer -->
</div>
<!-- End suggested layout containers / #content -->
<footer>
<div id="global-footer" class="global-footer">
<nav id="global-nav-expanded" class="global-nav-expanded row">
<!-- Footer will be automatically inserted by footer.js -->
</nav>
<section id="ebi-footer-meta" class="ebi-footer-meta row">
<!-- Footer meta will be automatically inserted by footer.js -->
</section>
</div>
</footer>
<!-- JavaScript -->
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!
<script>window.jQuery || document.write('<script src="../js/libs/jquery-1.10.2.min.js"><\/script>')</script>
<script defer="defer" src="//dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/js/script.js"></script>
<!-- The Foundation theme JavaScript -->
<script src="//dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/libraries/foundation-6/js/foundation.js"></script>
<script src="//dev.ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.4/js/foundationExtendEBI.js"></script>
<script type="text/JavaScript">$(document).foundation();</script>
<script type="text/JavaScript">$(document).foundationExtendEBI();</script>
<!-- Google Analytics details... -->
<!-- Change UA-XXXXX-X to be your site's ID -->
<script type="text/javascript">!function(e,a,n,t,i,o,c){e.<API key>=i,e[i]=e[i]||function(){(e[i].q=e[i].q||[]).push(arguments)},e[i].l=1*new Date,o=a.createElement(n),c=a.<API key>(n)[0],o.async=1,o.src="
</body>
</html> |
angular.module('addonsApp')
.directive('addon', ['AddonsService', function(AddonsService) {
return {
restrict: 'E',
scope: {
addon: '='
},
link: function(scope, element, attrs) {
var addonsManager = AddonsService.manager;
var localAddonIndex = utils.findItem(AddonsService.manager.database.local, "name", scope.addon.name);
scope.localAddon = (localAddonIndex >= 0) ? addonsManager.database.local[localAddonIndex] : null;
scope.type = attrs.type;
scope.splitStrings = function(s, nb) {
if (!s) {
return '';
}
var array = s.split('<br>');
var result = array[nb];
return result;
};
scope.openUrlInBrowser = function(url) {
window.open(url, '_blank');
};
scope.getDependencyName = function(dependencyName) {
if (!addonsManager.catalog[dependencyName]) {
return dependencyName;
}
return addonsManager.catalog[dependencyName].title;
};
function noticePopup(options) {
if (options.message) {
$("#freeow").freeow("Installation Info", options.message, {
classes: ["gray", options.type || "notice"],
autoHide: options.type === "error" ? "false" : "true"
});
}
}
scope.install = function() {
addonsManager.install(scope.addon).then(function(installMessage) {
noticePopup({
message: installMessage
});
}).catch(function(err) {
noticePopup({
message: String(err),
type: "error"
});
});
};
scope.update = function() {
addonsManager.update(scope.addon).then(function(updateMessage) {
noticePopup({
message: updateMessage
});
}).catch(function(err) {
noticePopup({
message: String(err),
type: "error"
});
});
};
scope.retry = function() {
addonsManager.retry();
};
scope.remove = function() {
addonsManager.remove(scope.addon).then(function(removeMessage) {
noticePopup({
message: removeMessage
});
}).catch(function(err) {
noticePopup({
message: String(err),
type: "error"
});
});
};
},
templateUrl: './app/directives/addon/addonDirective.html'
}
}]); |
<?php
namespace Tech\TBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\<API key>;
use Symfony\Component\OptionsResolver\<API key>;
class PersonarelformType extends AbstractType
{
/**
* @param <API key> $builder
* @param array $options
*/
public function buildForm(<API key> $builder, array $options)
{
$builder
->add('idPersona')
->add('idFormul')
;
}
/**
* @param <API key> $resolver
*/
public function setDefaultOptions(<API key> $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Tech\TBundle\Entity\Personarelform'
));
}
/**
* @return string
*/
public function getName()
{
return '<API key>';
}
} |
title: Extraterm v0.29.1 released
date: 2017-10-01 16:50:00 +0100
categories: release
This minor release fixes a recently introduced bug which broke the `from` command
Download it from [Github](https://github.com/sedwards2009/extraterm/releases/tag/v0.29.1) |
#pragma once
#ifndef <API key>
#define <API key>
#include <MACE/Core/Constants.h>
#include <MACE/Core/Interfaces.h>
#include <MACE/Graphics/Window.h>
#include <MACE/Utility/Color.h>
#include <memory>
#include <map>
#include <string>
#include <functional>
#ifdef MACE_OPENCV
# include <opencv2/opencv.hpp>
#endif//MACE_OPENCV
namespace mc {
namespace gfx {
class Renderer;
/**
Thrown when an error occured trying to read or write an image
*/
MACE__DECLARE_ERROR(BadImage);
/**
Thrown when a format is invalid
*/
MACE__DECLARE_ERROR(BadFormat);
enum class PixelStorage: Byte {
ALIGNMENT,
ROW_LENGTH
};
enum class ImageFormat: Byte {
//each enum is equal to how many components in that type of image
//the image load/save functions use swizzle masks to differentiate
//between LUMINANCE and R, LUMINANCE_ALPHA and RG
LUMINANCE = 1,
LUMINANCE_ALPHA = 2,
INTENSITY = 1,
R = 1,
RG = 2,
RGB = 3,
RGBA = 4,
DONT_CARE = 0
};
enum class PrimitiveType: short int {
//these draw modes were chosen because they exist in both OpenGL 3.3 and Direct3D
POINTS = 0,
LINES = 1,
LINES_ADJACENCY = 2,
LINES_STRIP = 3,
<API key> = 4,
TRIANGLES = 5,
TRIANGLES_ADJACENCY = 6,
TRIANGLES_STRIP = 7,
<API key> = 8,
//TRIANGLES_FAN does not exist in DirectX 10+ because of performance issues. It is not included in this list
};
enum class TextureSlot: Byte {
FOREGROUND = 0,
BACKGROUND = 1,
MASK = 2
};
class MACE_NOVTABLE ModelImpl: public Initializable, public Bindable {
friend class Model;
public:
virtual void init() override = 0;
virtual void destroy() override = 0;
virtual void bind() const override = 0;
virtual void unbind() const override = 0;
virtual void draw() const = 0;
virtual void <API key>(const unsigned int dataSize, const float* data) = 0;
virtual void loadVertices(const unsigned int verticeSize, const float* vertices) = 0;
virtual void loadIndices(const unsigned int indiceNum, const unsigned int* indiceData) = 0;
virtual bool isCreated() const = 0;
bool operator==(const ModelImpl& other) const;
bool operator!=(const ModelImpl& other) const;
protected:
PrimitiveType primitiveType = PrimitiveType::TRIANGLES;
};
class Model: public Initializable, public Bindable {
public:
static Model& getQuad();
Model();
Model(const std::shared_ptr<ModelImpl> mod);
Model(const Model& other);
~Model() = default;
void init() override;
void destroy() override;
void bind() const override;
void unbind() const override;
void <API key>(const unsigned int dataSize, const float* data);
template<const unsigned int N>
void <API key>(const float(&data)[N]) {
<API key>(N, data);
}
void createVertices(const unsigned int verticeSize, const float* vertices, const PrimitiveType& prim);
template<const unsigned int N>
void createVertices(const float(&vertices)[N], const PrimitiveType& prim) {
createVertices(N, vertices, prim);
}
void createIndices(const unsigned int indiceNum, const unsigned int* indiceData);
template<const unsigned int N>
void createIndices(const unsigned int(&indiceData)[N]) {
createIndices(N, indiceData);
}
PrimitiveType getPrimitiveType();
const PrimitiveType getPrimitiveType() const;
void draw() const;
bool isCreated() const;
bool operator==(const Model& other) const;
bool operator!=(const Model& other) const;
private:
std::shared_ptr<ModelImpl> model;
};
struct TextureDesc {
enum class Type: short int {
UNSIGNED_BYTE,
BYTE,
UNSIGNED_SHORT,
SHORT,
UNSIGNED_INT,
INT,
FLOAT,
UNSIGNED_BYTE_3_3_2,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
};
enum class Format: short int {
RED,
RG,
RGB,
RGBA,
BGR,
BGRA,
RED_INTEGER,
RG_INTEGER,
RGB_INTEGER,
BGR_INTEGER,
RGBA_INTEGER,
BGRA_INTEGER,
STENCIL,
DEPTH,
DEPTH_STENCIL,
LUMINANCE,
LUMINANCE_ALPHA,
INTENSITY
};
enum class InternalFormat: Enum {
DEPTH,
DEPTH_STENCIL,
RED,
RG,
RGB,
RGBA,
R8,
R16,
RGB8,
RGBA8,
SRGB,
SRGB8,
SRGB_ALPHA
};
enum class Filter: Byte {
//MIPMAP_LINEAR and MIPMAP_NEAREST automatically
//generate mipmaps in OpenGL renderer.
//They cant be used for the magnication filter,
//only the minification filter
MIPMAP_LINEAR,
MIPMAP_NEAREST,
NEAREST,
LINEAR,
ANISOTROPIC
};
enum class Wrap: Byte {
CLAMP,
WRAP,
MIRROR,
BORDER
};
TextureDesc() = default;
TextureDesc(const unsigned int w, const unsigned int h, const Format form = Format::RGBA);
Filter minFilter = Filter::LINEAR;
Filter magFilter = Filter::LINEAR;
Type type = Type::FLOAT;
Format format = Format::RGBA;
InternalFormat internalFormat = InternalFormat::RGBA;
unsigned int width = 0, height = 0;
Wrap wrapS = Wrap::CLAMP;
Wrap wrapT = Wrap::CLAMP;
Color borderColor = Colors::INVISIBLE;
};
class MACE_NOVTABLE TextureImpl: public Bindable {
friend class Texture;
public:
TextureImpl(const TextureDesc& t);
virtual ~TextureImpl() = default;
virtual void bind() const override = 0;
virtual void bind(const TextureSlot slot) const = 0;
virtual void unbind() const override = 0;
virtual bool isCreated() const = 0;
virtual void setData(const void* data, const int mipmap) = 0;
virtual void <API key>(const PixelStorage hint, const int value) = 0;
virtual void setPackStorageHint(const PixelStorage hint, const int value) = 0;
virtual void readPixels(void* data) const = 0;
protected:
const TextureDesc desc;
};
class Texture: public Bindable {
public:
static Texture create(const Color& col, const unsigned int width = 1, const unsigned int height = 1);
static Texture createFromFile(const std::string& file, const ImageFormat format = ImageFormat::DONT_CARE, const TextureDesc::Wrap wrap = TextureDesc::Wrap::CLAMP);
static Texture createFromFile(const char* file, const ImageFormat format = ImageFormat::DONT_CARE, const TextureDesc::Wrap wrap = TextureDesc::Wrap::CLAMP);
static Texture createFromMemory(const unsigned char* c, const int size);
static Texture& getSolidColor();
/**
- Vertical gradient
- Darker part on bottom
- Height is 100
*/
static Texture& getGradient();
Texture();
Texture(const TextureDesc& d);
Texture(const Color& col);
Texture(const std::shared_ptr<TextureImpl> tex, const Color& col = Color(0.0f, 0.0f, 0.0f, 0.0f));
Texture(const Texture& tex, const Color& col = Color(0.0, 0.0f, 0.0f, 0.0f));
void init(const TextureDesc& desc);
void destroy();
bool isCreated() const;
const TextureDesc& getDesc() const;
unsigned int getWidth();
const unsigned int getWidth() const;
unsigned int getHeight();
const unsigned int getHeight() const;
#ifdef MACE_EXPOSE_OPENGL
std::shared_ptr<TextureImpl> getImpl() {
return texture;
}
const std::shared_ptr<TextureImpl> getImpl() const {
return texture;
}
#endif
//this needs to be defined in the header file to prevent linker conflicts, because Entity.cpp does not have opencv included ever.
# ifdef MACE_OPENCV
Texture(cv::Mat mat) : Texture() {
TextureDesc desc = TextureDesc(mat.rows, mat.cols);
if (mat.channels() == 1) {
desc.format = TextureDesc::Format::RED;
desc.internalFormat = TextureDesc::InternalFormat::RED;
} else if (mat.channels() == 2) {
desc.format = TextureDesc::Format::RG;
desc.internalFormat = TextureDesc::InternalFormat::RG;
} else if (mat.channels() == 3) {
desc.format = TextureDesc::Format::BGR;
desc.internalFormat = TextureDesc::InternalFormat::RGB;
} else if (mat.channels() == 4) {
desc.format = TextureDesc::Format::BGRA;
desc.internalFormat = TextureDesc::InternalFormat::RGBA;
}
desc.type = TextureDesc::Type::UNSIGNED_BYTE;
if (mat.depth() == CV_8S) {
desc.type = TextureDesc::Type::BYTE;
} else if (mat.depth() == CV_16U) {
desc.type = TextureDesc::Type::UNSIGNED_SHORT;
} else if (mat.depth() == CV_16S) {
desc.type = TextureDesc::Type::SHORT;
} else if (mat.depth() == CV_32S) {
desc.type = TextureDesc::Type::INT;
} else if (mat.depth() == CV_32F) {
desc.type = TextureDesc::Type::FLOAT;
} else if (mat.depth() == CV_64F) {
MACE__THROW(BadFormat, "Unsupported cv::Mat depth: CV_64F");
}
init(desc);
resetPixelStorage();
setPackStorageHint(PixelStorage::ALIGNMENT, (mat.step & 3) ? 1 : 4);
setPackStorageHint(PixelStorage::ROW_LENGTH, static_cast<int>(mat.step / mat.elemSize()));
setData(mat.ptr());
}
cv::Mat toMat() {
cv::Mat img(getHeight(), getWidth(), CV_8UC3);
resetPixelStorage();
setPackStorageHint(PixelStorage::ALIGNMENT, (img.step & 3) ? 1 : 4);
setPackStorageHint(PixelStorage::ROW_LENGTH, static_cast<int>(img.step / img.elemSize()));
bind();
readPixels(img.data);
cv::flip(img, img, 0);
return img;
}
# endif//MACE_OPENCV
Color & getHue();
const Color & getHue() const;
void setHue(const Color & col);
Vector<float, 4> & getTransform();
const Vector<float, 4> & getTransform() const;
void setTransform(const Vector<float, 4> & trans);
void bind() const override;
void bind(const TextureSlot slot) const;
void unbind() const override;
void resetPixelStorage();
void setData(const void* data, const int mipmap = 0);
template<typename T, unsigned int W, unsigned int H>
void setData(const T(&data)[W][H], const int mipmap = 0) {
MACE_STATIC_ASSERT(W != 0, "Width of Texture can not be 0!");
MACE_STATIC_ASSERT(H != 0, "Height of Texture can not be 0!");
MACE_IF_CONSTEXPR(W != texture->desc.width || H != texture->desc.height) {
MACE__THROW(AssertionFailed, "Input data is not equal to Texture width and height");
}
setData(static_cast<const void*>(data[0]), mipmap);
}
void <API key>(const PixelStorage hint, const int value);
void setPackStorageHint(const PixelStorage hint, const int value);
void readPixels(void* data) const;
bool operator==(const Texture & other) const;
bool operator!=(const Texture & other) const;
private:
std::shared_ptr<TextureImpl> texture;
Color hue = Colors::INVISIBLE;
Vector<float, 4> transform{0.0f, 0.0f, 1.0f, 1.0f};
};//Texture
struct RenderTargetDesc {
public:
unsigned int width = 128, height = 128;
};
class MACE_NOVTABLE RenderTargetImpl: public Initializable {
};//RenderTargetImpl
class GraphicsContext: public Initializable {
friend class Texture;
friend class Model;
public:
using <API key> = std::function<Texture()>;
using ModelCreateCallback = std::function<Model()>;
GraphicsContext(gfx::WindowModule* win);
//prevent copying
GraphicsContext(const GraphicsContext& other) = delete;
virtual ~GraphicsContext() = default;
void init() override;
void render();
void destroy() override;
virtual Renderer* getRenderer() const = 0;
gfx::WindowModule* getWindow();
const gfx::WindowModule* getWindow() const;
Texture& createTexture(const std::string& name, const Texture& texture = Texture());
Texture& getOrCreateTexture(const std::string& name, const <API key> create);
Texture& <API key>(const std::string& name, const std::string& path);
Model& createModel(const std::string& name, const Model& texture = Model());
Model& getOrCreateModel(const std::string& name, const ModelCreateCallback create);
bool hasTexture(const std::string& name) const;
bool hasModel(const std::string& name) const;
void setTexture(const std::string& name, const Texture& texture);
Texture& getTexture(const std::string& name);
const Texture& getTexture(const std::string& name) const;
void setModel(const std::string& name, const Model& model);
Model& getModel(const std::string& name);
const Model& getModel(const std::string& name) const;
std::map<std::string, Texture>& getTextures();
const std::map<std::string, Texture>& getTextures() const;
std::map<std::string, Model>& getModels();
const std::map<std::string, Model>& getModels() const;
protected:
gfx::WindowModule* window;
/*
Reasoning behind returning a std::shared_ptr and not a std::unique_ptr...
Each Model and Texture class needs to have it's own Impl.
Each Impl acts as a pointer to a resource, whether it be in GPU memory
or whatever. However, Model and Texture needs the ability to be moved,
like so:
Model model = Model();
Model newModel = m;
Both Model objects will share the same resource, as it is simply a
pointer to the actual data. However, with std::unique_ptr, this move
semantic because near impossible. Because multiple Model objects
may have to own the same pointer to data, they have to use std::shared_ptr
*/
virtual std::shared_ptr<ModelImpl> createModelImpl() const = 0;
virtual std::shared_ptr<TextureImpl> createTextureImpl(const TextureDesc& desc) const = 0;
virtual void onInit(gfx::WindowModule* win) = 0;
virtual void onRender(gfx::WindowModule* win) = 0;
virtual void onDestroy(gfx::WindowModule* win) = 0;
private:
std::map<std::string, Texture> textures{};
std::map<std::string, Model> models{};
};
}
}
#endif//<API key> |
package com.maximejunger.react;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.<API key>;
import android.bluetooth.<API key>;
import android.bluetooth.<API key>;
import android.bluetooth.<API key>;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.ParcelUuid;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.<API key>;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.<API key>;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.<API key>;
import java.io.<API key>;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import javax.annotation.Nullable;
public class RNBLEModule extends <API key> implements BluetoothAdapter.LeScanCallback {
private Map<String, BluetoothDevice> mPeripherals;
private BluetoothAdapter mBluetoothAdapter;
private <API key> <API key>;
private static final UUID <API key> = UUID.fromString("<API key>");
// Options
private boolean <API key> = true;
public RNBLEModule(<API key> reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "RNBLE";
}
// use this as an inner class like here or as a top-level class
// public class MyBroadCastReceiver extends BroadcastReceiver {
// <API key> <API key>;
// @Override
// public void onReceive(Context context, Intent intent) {
// // do something
// String action = intent.getAction();
// if (BluetoothAdapter.<API key>.equals(action)) {
// int extraCode = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
// WritableMap params = Arguments.createMap();
// switch (extraCode) {
// case BluetoothAdapter.STATE_OFF:
// params.putString("state", "poweredOff");
// break;
// case BluetoothAdapter.STATE_ON:
// params.putString("state", "poweredOn");
// break;
// if (params.hasKey("state") && params.getString("state") != null) {
// sendEvent(this.<API key>, "stateChange", params);
// } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// // Create a new device item
// int i = 0;
// System.out.print(device.getName());
// ParcelUuid[] pcl = device.getUuids();
// System.out.println(device.getAddress());
// System.out.println(device.getType());
// // DeviceItem newDevice = new DeviceItem(device.getName(), device.getAddress(), "false");
// // Add it to our adapter
// // mAdapter.add(newDevice);
// } else if (BluetoothDevice.ACTION_UUID.equals(action)) {
// BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Parcelable[] uuids = intent.<API key>(BluetoothDevice.EXTRA_UUID);
// System.out.print("JE SUIS LA EHEHHEHE");
// for (Parcelable ep : uuids) {
// System.out.print("UUID Records : " + ep.toString());
// //Utilities.print("UUID records : "+ ep.toString());
// public MyBroadCastReceiver(<API key> <API key>) {
// <API key> = <API key>;
/**
* Send events to Javascript
*
* @param reactContext context of react
* @param eventName name of event that Javascript is listening
* @param params WritableMap of params
*/
private void sendEvent(ReactContext reactContext,
String eventName,
@Nullable WritableMap params) {
reactContext
.getJSModule(<API key>.<API key>.class)
.emit(eventName, params);
}
/**
* Prepare the Bluetooth and set the stateChange handler
* Send event of the current Bluetooth state to React
*/
@ReactMethod
public void getState() {
mPeripherals = new HashMap<String, BluetoothDevice>();
BluetoothManager manager = (BluetoothManager) this.<API key>().getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = manager.getAdapter();
WritableMap params = Arguments.createMap();
if (mBluetoothAdapter == null || !this.<API key>().getPackageManager().hasSystemFeature(PackageManager.<API key>)) {
params.putString("state", "unsupported");
} else {
if (!mBluetoothAdapter.isEnabled()) {
params.putString("state", "poweredOff");
} else {
params.putString("state", "poweredOn");
}
}
sendEvent(this.<API key>(), "ble.stateChange", params);
// this.mReceiver = new MyBroadCastReceiver(this.<API key>());
// this.<API key>().registerReceiver(this.mReceiver, new IntentFilter(BluetoothAdapter.<API key>));
}
/**
* Start scanning for needed uuids
* @param uuids UUIDS needed
* @param allowDuplicates true/false
*/
@ReactMethod
public void startScanning(ReadableArray uuids, Boolean allowDuplicates) {
this.mPeripherals.clear();
UUID[] arrayUUIDS = new UUID[uuids.size()];
for (int i = 0; i < uuids.size(); i++) {
arrayUUIDS[i] = BluetoothUUIDHelper.shortUUIDToLong(uuids.getString(i));
}
this.<API key> = allowDuplicates;
this.mBluetoothAdapter.startLeScan(arrayUUIDS, this);
}
/**
* Stop Scanning for LE
*/
@ReactMethod
public void stopScanning() {
this.mBluetoothAdapter.stopLeScan(this);
}
/**
* Called when a device is found
* @param device device found
* @param rssi Signal strength
* @param scanRecord record
*/
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
WritableMap params = Arguments.createMap();
if (!this.mPeripherals.containsKey(device.getAddress()))
this.mPeripherals.put(device.getAddress(), device);
else {
if (!this.<API key>) return;
}
params.putString("name", device.getName());
params.putString("peripheralUuid", device.getAddress());
params.putString("address", device.getAddress());
params.putInt("rssi", rssi);
params.putBoolean("connectable", true);
sendEvent(this.<API key>(), "ble.discover", params);
}
/**
* Connect to device
* @param address of the device
*/
@ReactMethod
public void connect(String address) {
BluetoothDevice device = this.mPeripherals.get(address);
WritableMap params = Arguments.createMap();
if (<API key> != null && <API key>.getmBluetoothGatt() != null) {
<API key>.getmBluetoothGatt().close();
<API key> = null;
}
if (device != null) {
<API key> = new <API key>(this.<API key>());
device.connectGatt(this.<API key>(), true, <API key>);
} else {
params.putString("error", "Device not found");
sendEvent(this.<API key>(), "ble.connect", params);
}
}
@ReactMethod
public void disconnect(String address) {
BluetoothDevice device = this.mPeripherals.get(address);
WritableMap params = Arguments.createMap();
if (device != null) {
if (this.<API key> != null) {
this.<API key>.getmBluetoothGatt().close();
params.putString("peripheralUuid", device.getAddress());
sendEvent(this.<API key>(), "ble.disconnect", params);
}
}
}
/**
* Discover services of device
* @param address of the device
* @param uuids wanted
*/
@ReactMethod
public void discoverServices(String address, ReadableArray uuids) {
BluetoothDevice device = this.mPeripherals.get(address);
WritableMap params = Arguments.createMap();
List<String> uuidsList = new ArrayList<>();
for (int i = 0; i < uuids.size(); i++) {
uuidsList.add(uuids.getString(i));
}
<API key>.<API key>(uuidsList);
if (device != null && this.<API key>.getmBluetoothGatt().getDevice().getAddress().equals(device.getAddress())) {
this.<API key>.getmBluetoothGatt().discoverServices();
} else {
params.putString("error", "Device not found");
sendEvent(this.<API key>(), "ble.servicesDiscover", params);
}
}
/**
* Discover Characteristics for service
* @param address of device
* @param serviceUUID UUID of service where characteristics are
* @param <API key> Characteristics wanted
*/
@ReactMethod
public void <API key>(String address, String serviceUUID, ReadableArray <API key>) {
BluetoothDevice device = this.mPeripherals.get(address);
WritableMap params = Arguments.createMap();
WritableArray characteristics = Arguments.createArray();
if (device != null && this.<API key>.getmBluetoothGatt().getDevice().getAddress().equals(device.getAddress())) {
<API key> service = <API key>.getmBluetoothGatt().getService(BluetoothUUIDHelper.shortUUIDToLong(serviceUUID));
if (service != null) {
params.putString("peripheralUuid", address);
params.putString("serviceUuid", serviceUUID);
if (<API key>.size() == 0) {
List<<API key>> characs = service.getCharacteristics();
for (<API key> blc : characs) {
String uuidStr = BluetoothUUIDHelper.longUUIDToShort(blc.getUuid().toString()).toUpperCase();
characteristics.pushString(uuidStr);
}
} else {
for (int i = 0; i < <API key>.size(); i++) {
UUID uuid = BluetoothUUIDHelper.shortUUIDToLong(<API key>.getString(i));
<API key> charac = service.getCharacteristic(uuid);
if (charac != null) {
UUID characteristicUuid = charac.getUuid();
String uuidStr = BluetoothUUIDHelper.longUUIDToShort(characteristicUuid.toString()).toUpperCase();
WritableMap map = Arguments.createMap();
map.putString("uuid", uuidStr);
characteristics.pushMap(map);
}
}
}
params.putArray("characteristics", characteristics);
sendEvent(this.<API key>(), "ble.<API key>", params);
} else {
params.putString("error", "Device not found");
sendEvent(this.<API key>(), "ble.<API key>", params);
}
}
}
/**
* Read value of characteristic
* @param address of the device
* @param serviceUUID UUID of service where characteristic is
* @param characteristicUUID Characteristic we want to read
*/
@ReactMethod
public void read(String address, String serviceUUID, String characteristicUUID) {
BluetoothDevice device = this.mPeripherals.get(address);
WritableMap params = Arguments.createMap();
if (device == null) {
params.putString("error", "Device not found");
return;
}
<API key> service = this.<API key>.getmBluetoothGatt().getService(BluetoothUUIDHelper.shortUUIDToLong(serviceUUID));
if (service == null) {
params.putString("error", "Service not found");
return;
}
<API key> characteristic = service.getCharacteristic(BluetoothUUIDHelper.shortUUIDToLong(characteristicUUID));
if (characteristic == null) {
params.putString("error", "Characteristic not found");
return;
}
this.<API key>.getmBluetoothGatt().readCharacteristic(characteristic);
}
@ReactMethod
public void notify(String address, String serviceUUID, String characteristicUUID, boolean notify) {
WritableMap params = Arguments.createMap();
BluetoothDevice device = this.mPeripherals.get(address);
if (device == null) {
params.putString("error", "Device not found");
return;
}
<API key> service = this.<API key>.getmBluetoothGatt().getService(BluetoothUUIDHelper.shortUUIDToLong(serviceUUID));
if (service == null) {
params.putString("error", "Service not found");
return;
}
<API key> characteristic = service.getCharacteristic(BluetoothUUIDHelper.shortUUIDToLong(characteristicUUID));
if (characteristic == null) {
params.putString("error", "Characteristic not found");
return;
}
// Check characteristic property
final int properties = characteristic.getProperties();
if ((properties & <API key>.PROPERTY_NOTIFY) == 0)
return;
this.<API key>.getmBluetoothGatt().<API key>(characteristic, notify);
final <API key> descriptor = characteristic.getDescriptor(<API key>);
if (descriptor != null) {
descriptor.setValue(<API key>.<API key>);
this.<API key>.getmBluetoothGatt().writeDescriptor(descriptor);
}
}
@ReactMethod
public void test() {
Log.i("TEST", "TEST HELLO");
}
} |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataFactory::Mgmt::V2018_06_01
module Models
# This activity executes inner activities until the specified boolean
# expression results to true or timeout is reached, whichever is earlier.
class UntilActivity < ControlActivity
include MsRestAzure
def initialize
@type = "Until"
end
attr_accessor :type
# @return [Expression] An expression that would evaluate to Boolean. The
# loop will continue until this expression evaluates to true
attr_accessor :expression
# @return Specifies the timeout for the activity to run. If there is no
# value specified, it takes the value of TimeSpan.FromDays(7) which is 1
# week as default. Type: string (or Expression with resultType string),
# pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). Type:
# string (or Expression with resultType string), pattern:
# ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
attr_accessor :timeout
# @return [Array<Activity>] List of activities to execute.
attr_accessor :activities
# Mapper for UntilActivity class as Ruby Hash.
# This will be used for serialization/deserialization.
def self.mapper()
{
<API key>: true,
required: false,
serialized_name: 'Until',
type: {
name: 'Composite',
class_name: 'UntilActivity',
model_properties: {
<API key>: {
<API key>: true,
required: false,
type: {
name: 'Dictionary',
value: {
<API key>: true,
required: false,
serialized_name: 'ObjectElementType',
type: {
name: 'Object'
}
}
}
},
name: {
<API key>: true,
required: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
description: {
<API key>: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
depends_on: {
<API key>: true,
required: false,
serialized_name: 'dependsOn',
type: {
name: 'Sequence',
element: {
<API key>: true,
required: false,
serialized_name: '<API key>',
type: {
name: 'Composite',
class_name: 'ActivityDependency'
}
}
}
},
user_properties: {
<API key>: true,
required: false,
serialized_name: 'userProperties',
type: {
name: 'Sequence',
element: {
<API key>: true,
required: false,
serialized_name: '<API key>',
type: {
name: 'Composite',
class_name: 'UserProperty'
}
}
}
},
type: {
<API key>: true,
required: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
expression: {
<API key>: true,
required: true,
serialized_name: 'typeProperties.expression',
default_value: {},
type: {
name: 'Composite',
class_name: 'Expression'
}
},
timeout: {
<API key>: true,
required: false,
serialized_name: 'typeProperties.timeout',
type: {
name: 'Object'
}
},
activities: {
<API key>: true,
required: true,
serialized_name: 'typeProperties.activities',
type: {
name: 'Sequence',
element: {
<API key>: true,
required: false,
serialized_name: 'ActivityElementType',
type: {
name: 'Composite',
<API key>: 'type',
uber_parent: 'Activity',
class_name: 'Activity'
}
}
}
}
}
}
}
end
end
end
end |
# AutoHtml
AutoHtml is a collection of filters that transforms plain text into HTML code. See [live demo](https://autohtml.rors.org).
## Installation
Add this line to your application's Gemfile:
ruby
gem 'auto_html'
And then execute:
sh
$ bundle
Or install it yourself as:
sh
$ gem install auto_html
## Abstract
AutoHtml uses concepts found in "Pipes and Filters" processing design pattern:
* `Filter` - transforms an input. In AutoHtml context, this is any object that does the transformation through `#call(String)` method. Filter options should be passed in initializer. AutoHtml provides some filters already, ie Link, Image, Markdown, etc.
* `Pipeline` - a composition of filters that transforms input by passing the output of one filter as input for the next filter in line. In AutoHtml context, this is the `AutoHtml::Pipeline` class. Since the same interface (method `#call`) is used to pass input, we can say that Pipeline is just another Filter, which means it can be used as a building block for other Pipelines, in a mix with other filters.
## Examples
ruby
link_filter = AutoHtml::Link.new(target: '_blank')
link_filter.call('Checkout out my blog: http://rors.org')
emoji_filter = AutoHtml::Emoji.new
emoji_filter.call(':point_left: yo!')
# => '<img src="/images/emoji/unicode/1f448.png" class="emoji" title=":point_left:" alt=":point_left:" height="20" witdh="20" align="absmiddle" /> yo!'
# Use Pipeline to combine filters
base_format = AutoHtml::Pipeline.new(link_filter, emoji_filter)
base_format.call('Checkout out my blog: http://rors.org :point_left: yo!')
# A pipeline can be reused in another pipeline. Note that the order of filters is important - ie you want
# `Image` before `Link` filter so that URL of the image gets transformed to `img` tag and not `a` tag.
comment_format = AutoHtml::Pipeline.new(AutoHtml::Markdown.new, AutoHtml::Image.new, base_format)
comment_format.call("Hello!\n\n Checkout out my blog: http:
## Bundled filters
Bellow is the list of bundled filters along with their optional arguments on initialization and their default values.
* `AutoHtml::Emoji`
* `AutoHtml::HtmlEscape`
* `AutoHtml::Image`, proxy: nil, alt: nil
* `AutoHtml::Link`, target: nil, rel: nil
* `AutoHtml::Markdown`
* `AutoHtml::SimpleFormat`
## Using AutoHtml with ActiveRecord
For performance reasons it's a good idea to store the formated output in the database, in a separate column, to avoid generating the same content on each access.
This can be acomplished simply by overriding the attribute writter:
ruby
class Comment < ActiveRecord::Base
FORMAT = AutoHtml::Pipeline.new(
AutoHtml::HtmlEscape.new,
AutoHtml::Markdown.new
)
def text=(t)
super(t)
self[:text_html] = FORMAT.call(t)
end
end
Now, every time `text` attribute is set, `text_html` will be set as well:
Ruby
comment = Comment.new(text: 'Hey!')
comment.text_html # => '<p>Hey!</p>'
## Licence
AutoHtml is released under the [MIT License](https: |
<?php
return array (
'id' => 'zte_2118_ver1',
'fallback' => 'generic_xhtml',
'capabilities' =>
array (
'model_name' => '2118',
'brand_name' => 'ZTE',
'wml_1_2' => 'true',
'preferred_markup' => 'wml_1_2',
'max_image_width' => '128',
'resolution_height' => '160',
'resolution_width' => '128',
'max_image_height' => '160',
'png' => 'true',
'voices' => '40',
'mmf' => 'true',
'<API key>' => 'none',
),
); |
package screepsws
import "fmt"
func (ws *webSocket) SubscribeRoom(shard, room string) (<-chan RoomResponse, error) {
channel := fmt.Sprintf(roomFormat, shard, room)
dataChan, err := ws.Subscribe(channel)
if err != nil {
return nil, fmt.Errorf("failed to subscribe to '%s'", channel)
}
respChan := make(chan RoomResponse)
go func() {
defer close(respChan)
for data := range dataChan {
resp := RoomResponse{}
closed := UnmarshalResponse(data, &resp)
if closed {
return
}
respChan <- resp
}
}()
return respChan, nil
}
func (ws *webSocket) UnsubscribeRoom(shard, room string) error {
return ws.Unsubscribe(fmt.Sprintf(roomFormat, shard, room))
}
func (ws *webSocket) SubscribeRoomMap(shard, room string) (<-chan RoomMapResponse, error) {
channel := fmt.Sprintf(roomMapFormat, shard, room)
dataChan, err := ws.Subscribe(channel)
if err != nil {
return nil, fmt.Errorf("failed to subscribe to '%s'", channel)
}
respChan := make(chan RoomMapResponse)
go func() {
defer close(respChan)
for data := range dataChan {
resp := RoomMapResponse{}
closed := UnmarshalResponse(data, &resp)
if closed {
return
}
respChan <- resp
}
}()
return respChan, nil
}
func (ws *webSocket) UnsubscribeRoomMap(shard, room string) error {
return ws.Unsubscribe(fmt.Sprintf(roomMapFormat, shard, room))
} |
package solved;
import tasks.ITask;
import tasks.Tester;
//Answer : 1.710637717
public class Task_197 implements ITask {
public void solving() {
// double u = -1;
// while (true) {
// System.out.println(u);
// u = floor(exp((30.403243784-u*u) * log(2))) * 1e-9;
//just notice, that sequence quickly came to alternating these two values
System.out.println(1.029461839 + 0.681175878);
}
public static void main(String[] args) {
Tester.test(new Task_197());
}
} |
<?php
namespace Services\CVS;
use Services\CVS\Entities\Interfaces\Versionable;
use \Exception as Exception;
use Entities\TemplateRepository;
use Services\Shell;
use DB\EntityManager;
class CVS
{
private $_repositoryPath;
private $_origin;
private $_branch;
private $_templateRepo;
private $_entityManager;
public function __construct ($configArray, TemplateRepository $templateRepo, EntityManager $em)
{
$this->_repositoryPath = $configArray['repositoryPath'];
$this->_origin = $configArray['originName'];
$this->_branch = $configArray['branchName'];
$this->_templateRepo = $templateRepo;
$this->_entityManager = $em;
}
public function commit (Versionable $entity)
{
if (!$entity instanceof Versionable) return;
if (!$this->_isLastVersion($entity)) {
throw new Exception('Other user changed this entity before you.');
}
$this->_writeFile($entity);
try{
$this->_doCommit($entity);
try{
$this->_doPush();
} catch (Exception $ex) {
//throw $ex;
}
} catch (Exception $ex) {
throw $ex;
}
$entity-><API key>();
}
public function <API key> ()
{
if (!$this-><API key>()) {
throw new Exception('Local repository can not be updated.');
}
try{
$this->_doPull();
try{
return $this->_importFiles();
} catch (Exception $ex) {
//throw $ex;
}
} catch (Exception $ex) {
throw $ex;
}
return [];
}
public function <API key> ()
{
$localRepoRev = $this-><API key>();
return (Boolean)preg_match('~[1-9]+[0-9]*\s+[1-9]+[0-9]*~', $localRepoRev);
}
public function <API key> ()
{
$localRepoRev = $this-><API key>();
return (Boolean)preg_match('~[1-9]+[0-9]*\s+0~', $localRepoRev);
}
private function _isLastVersion(Versionable $entity)
{
$savedEntity = $this->_templateRepo->byId($entity->getId());
return $savedEntity->isCompatible($entity);
}
private function _getFileName(Versionable $entity)
{
return sprintf('%s/%s.txt', $this->_repositoryPath , $entity->getName());
}
private function _writeFile(Versionable $entity)
{
file_put_contents($this->_getFileName($entity), $entity->getCode());
}
private function _importFiles()
{ |
from multihash import SHA1, SHA2_256, SHA2_512, SHA3, BLAKE2B, BLAKE2S, \
decode, encode, is_valid_code, is_app_code |
#pragma once
// Async Logger implementation
// Use an async_sink (queue per logger) to perform the logging in a worker thread
#include "spdlog/details/async_log_helper.h"
#include "spdlog/async_logger.h"
#include <string>
#include <functional>
#include <chrono>
#include <memory>
template<class It>
inline spdlog::async_logger::async_logger(const std::string& logger_name,
const It& begin,
const It& end,
size_t queue_size,
const <API key> overflow_policy,
const std::function<void()>& worker_warmup_cb,
const std::chrono::milliseconds& flush_interval_ms,
const std::function<void()>& worker_teardown_cb) :
logger(logger_name, begin, end),
_async_log_helper(new details::async_log_helper(_formatter, _sinks, queue_size, _err_handler, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb))
{
}
inline spdlog::async_logger::async_logger(const std::string& logger_name,
sinks_init_list sinks_list,
size_t queue_size,
const <API key> overflow_policy,
const std::function<void()>& worker_warmup_cb,
const std::chrono::milliseconds& flush_interval_ms,
const std::function<void()>& worker_teardown_cb) :
async_logger(logger_name, sinks_list.begin(), sinks_list.end(), queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {}
inline spdlog::async_logger::async_logger(const std::string& logger_name,
sink_ptr single_sink,
size_t queue_size,
const <API key> overflow_policy,
const std::function<void()>& worker_warmup_cb,
const std::chrono::milliseconds& flush_interval_ms,
const std::function<void()>& worker_teardown_cb) :
async_logger(logger_name,
{
single_sink
}, queue_size, overflow_policy, worker_warmup_cb, flush_interval_ms, worker_teardown_cb) {}
inline void spdlog::async_logger::flush()
{
_async_log_helper->flush(true);
}
// Error handler
inline void spdlog::async_logger::set_error_handler(spdlog::log_err_handler err_handler)
{
_err_handler = err_handler;
_async_log_helper->set_error_handler(err_handler);
}
inline spdlog::log_err_handler spdlog::async_logger::error_handler()
{
return _err_handler;
}
inline void spdlog::async_logger::_set_formatter(spdlog::formatter_ptr msg_formatter)
{
_formatter = msg_formatter;
_async_log_helper->set_formatter(_formatter);
}
inline void spdlog::async_logger::_set_pattern(const std::string& pattern)
{
_formatter = std::make_shared<pattern_formatter>(pattern);
_async_log_helper->set_formatter(_formatter);
}
inline void spdlog::async_logger::_sink_it(details::log_msg& msg)
{
try
{
#if defined(<API key>)
msg.msg_id = _msg_counter.fetch_add(1, std::<API key>);
#endif
_async_log_helper->log(msg);
if (_should_flush_on(msg))
_async_log_helper->flush(false); // do async flush
}
catch (const std::exception &ex)
{
_err_handler(ex.what());
}
catch (...)
{
_err_handler("Unknown exception");
}
} |
{{<govuk_template}}
{{$head}}
{{>includes/head}}
{{/head}}
{{$propositionHeader}}
{{/propositionHeader}}
{{$headerClass}}with-proposition{{/headerClass}}
{{$content}}
<main id="content" role="main">
{{>includes/phase_banner}}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="form-title heading-xlarge">
Personal Independence Payment (<abbr>PIP</abbr>)
</h1>
<aside>
<div class="inner">
<nav role="navigation" class="page-navigation" aria-label="parts to this guide">
<ol class="list-number grid-row">
<div class="column-half">
<li class="font-xsmall">
<a href="overview-2" title="Part 1: Overview">Overview</a>
</li>
<li class="font-xsmall">
<a href="eligibility-2" title="Part 2: Eligibility">Eligibility</a>
</li>
<li class="font-xsmall">
<a href="<API key>" title="Part 3: How you're assessed">How you're assessed</a>
</li>
</div>
<div class="column-half">
<li class="font-xsmall">
<a href="apply-2" title="Part 4: Apply">Apply</a>
</li>
<li class="font-xsmall">
<a href="report-a-change-2" title="Part 5: Report a change in circumstances">Report a change in circumstances</a>
</li>
</div>
</ol>
</nav>
</div>
</aside>
<div class="inner-block">
<header>
<h1 class="heading-medium">2. Eligibility</h1>
</header>
<article>
<p>To get a Personal Independence Payment, you must:</p>
<ul class="list-bullet">
<li>be aged 16 to 64 </li>
<li>be in Great Britain when you claim, unless you're a member of the Armed Forces or their family</li>
<li>be free from <a rel="external" href="http:
<li>live in the UK, Ireland, Isle of Man or the Channel Islands - or, depending on your circumstances, <a href="/<API key>/<API key>">in another <abbr title="European Economic Area">EEA</abbr> country or Switzerland</a></li>
</ul>
<p>Your health condition or disability doesn't have to be permanent but must be expected to last for at least 12 months in total. It must affect your ability to do at least one of the following:</p>
<ul class="list-bullet">
<li>prepare food, eat or drink</li>
<li>wash, bathe or go to the toilet</li>
<li>dress yourself</li>
<li>read or write</li>
<li>take medicine or treatments</li>
<li>manage your money</li>
<li>get on with other people</li>
<li>go out or move around unaided</li>
</ul>
</article>
</div>
</div>
<div class="column-third">
<div>
<h2 class="heading-medium" style="border-top: 10px solid #005ea5; padding-top: 15px;">Carers and disability benefits</h2>
<nav role="navigation" aria-labelledby="parent-subsection">
<ul class="font-xsmall" style="list-style-type: none;">
<li style="padding-bottom: 0.7em;">
<a href="http:
</li>
<li style="padding-bottom: 0.7em;">
<a href="http:
</li>
<li style="padding-bottom: 0.7em;">
<a href="http:
</li>
<li style="padding-bottom: 0.7em;">
<a href="http:
</li>
<li class="related-topic">
<a href="http:
</li>
</ul>
</nav>
</div>
<div>
<h2 class="heading-medium">Benefits</h2>
<nav role="navigation" aria-labelledby="parent-section">
<ul class="font-xsmall" style="list-style-type: none;">
<li style="padding-bottom: 0.7em;">
<a href="http:
</li>
<li class="related-topic">
<a href="http:
</li>
</ul>
</nav>
</div>
<div>
<h2 class="heading-medium">Elsewhere on GOV.UK</h2>
<nav role="navigation" aria-labelledby="parent-other">
<ul class="font-xsmall" style="list-style-type: none;">
<li style="padding-bottom: 0.7em;">
<a href="http:
</li>
<li>
<a href="http:
</li>
</ul>
</nav>
</div>
<div>
<h2 class="heading-medium">Elsewhere on the web</h2>
<nav role="navigation" aria-labelledby="<API key>">
<ul class="font-xsmall" style="list-style-type: none;">
<li style="padding-bottom: 0.7em;">
<a href="https:
</li>
</ul>
</nav>
</div>
<div class="inner group">
<a class="return-to-top font-xsmall" href="
</div>
</div>
</div>
</main><!-- / #page-container -->
{{/content}}
{{$bodyEnd}}
{{>includes/elements_scripts}}
{{/bodyEnd}}
{{/govuk_template}} |
<?php
session_start();
$con = mysql_connect($_SESSION['DBHOST'],$_SESSION['usr'],$_SESSION['rpw']);
if (!$con){
echo 'Uh oh!';
die('Error connecting to SQL Server, could not connect due to: ' . mysql_error() . '; username=' . $_SESSION["username"]);
}
else if($con){
if(!mysql_select_db($_SESSION['DBNAME'])){header('Location: ../login.php');} // or die("<h1>Error ".mysql_errno() ."</h1><br />check access (privileges) to the SQL server db CKXU for this user <br /><br /><hr />Error details:<br />" .mysql_error() . "<br /><br /><a href=login.php>Return</a>");
$sql="SELECT callsign, stationname from STATION order by callsign";
$result=mysql_query($sql);
$options="";//<OPTION VALUE=0>Choose</option>";
while ($row=mysql_fetch_array($result)) {
$name=$row["stationname"];
$callsign=$row["callsign"];
$options.="<OPTION VALUE=\"$callsign\">".$name."</option>";
}
}
else{
echo 'ERROR!';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../../css/phpstyle.css" />
<title>Station Insertion</title>
</head>
<body>
<div class="topbar">
Welcome, <?php echo(strtoupper($_SESSION['usr'])); ?>
</div>
<table width="1000">
<tr><td colspan="3">
<img src="../<?php echo $_SESSION['logo'];?>" alt="logo"/>
</td></tr></table><table width="1000" style="background-color:white;">
<tr><td colspan="100%"><h2>View Station</h2></td></tr>
<tr><th colspan="100%">
Direct Selection
</th></tr>
<tr><td colspan="2">
<form action="p2viewstation.php" name="callsign" method="POST">
<select name="callsign">
<?php echo $options;?>
</select>
</td><td width="100%">
<input type="submit" value="View" />
</form>
</td></tr>
<tr><td colspan="100%" height="20">
<hr/>
</td></tr>
<tr>
<td>
<form name="logout" action="../logout.php" method="POST">
<input type="submit" value="Logout">
</form>
</td>
<td>
<form name="return" action="../masterpage.php" method="POST">
<input type="submit" value="Return">
</form>
</td>
<td></td>
<td style="text-align:right;" width="100%">
<img src="../images/mysqls.png" alt="MySQL Powered" />
</td>
</tr>
</table>
</body>
</html> |
published: true
title: Docker
tags: docker
> Docker uses the Linux kernel and features of the kernel, like Cgroups and namespaces, to segregate processes so they can run independently as if they were running on separate system. - [What is Docker?](https:
- [x11docker](https://github.com/mviereck/x11docker) - un GUI applications in Docker ?
{% highlight bash %}
export DISPLAY=:0.0
xhost +local:docker
docker run .. --env DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix
{% endhighlight %}
[Atlernative on Pi](https://dev.to/elalemanyo/<API key>) should work as well
{% highlight bash %}
curl -sSL https://get.docker.com | sh # install
sudo usermod -aG docker $USER
docker run hello-world # test
{% endhighlight %}
Or
{% highlight bash %}
sudo apt install docker.io
# sudo systemctl unmask docker
sudo systemctl enable --now docker
sudo usermod -aG docker $LOGNAME
docker --version
{% endhighlight %}
Test that docker works
{% highlight bash %}
docker run hello-world
{% endhighlight %}
Finally check that docker is [using overlay2](https://docs.docker.com/storage/storagedriver/overlayfs-driver/)
{% highlight bash %}
docker info | grep -A 5 -i storage
{% endhighlight %}
> AMD recommends using 'overlay2', whose dependencies are met by the ROCm kernel - [ROCm](https://github.com/RadeonOpenCompute/ROCm-docker/blob/master/quick-start.md)
if necessary, see above.
[move docker's default /var/lib/docker to another directory](https://linuxconfig.org/<API key>debian-linux)
- need to move /var/lib/docker folder as a whole
- or pass argument to daemon
{% highlight bash %}
sudo systemctl stop docker # stop docker
{% endhighlight %}
Edit /etc/docker/daemon.json
{% highlight json %}
{
"storage-driver": "overlay2"
}
{% endhighlight %}
{% highlight bash %}
sudo systemctl start docker # start docker
{% endhighlight %}
Verify that the daemon is using the overlay2 storage driver.
{% highlight bash %}
docker info
{% endhighlight %}
- [Dealing with dynamically created devices](https://docs.docker.com/engine/reference/commandline/create/
## Alternatives
- [podman](https://podman.io/) - daemonless container engine - `Simply put: alias docker=podman`
- [containerd](https:
- [nerdctl](https://github.com/containerd/nerdctl) - a Docker-compatible CLI for containerd.
- [LXC](https://news.ycombinator.com/item?id=30385580) |
package in.twizmwaz.cardinal.module.modules.hill;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.event.ScoreUpdateEvent;
import in.twizmwaz.cardinal.module.GameObjective;
import in.twizmwaz.cardinal.module.TaskedModule;
import in.twizmwaz.cardinal.module.modules.matchTimer.MatchTimer;
import in.twizmwaz.cardinal.module.modules.regions.RegionModule;
import in.twizmwaz.cardinal.module.modules.score.ScoreModule;
import in.twizmwaz.cardinal.module.modules.proximity.<API key>;
import in.twizmwaz.cardinal.module.modules.scoreboard.<API key>;
import in.twizmwaz.cardinal.module.modules.team.TeamModule;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.util.Vector;
import java.util.HashSet;
import java.util.Set;
public class HillObjective implements TaskedModule, GameObjective {
private final String name, id;
private final int captureTime, points;
private final double pointsGrowth, timeMultiplier;
private final CaptureRule captureRule;
private final boolean showProgress, neutralState, incremental, permanent, show, required;
private final RegionModule capture, progress, captured;
private final Set<Player> capturingPlayers;
private TeamModule team, capturingTeam;
private double controlTime;
private <API key> scoreboardHandler;
private <API key> proximityHandler;
private int seconds = 1;
private int tempPoints;
protected HillObjective(final TeamModule team, final String name, final String id, final int captureTime, final int points, final double pointsGrowth, final CaptureRule captureRule, final double timeMultiplier, final boolean showProgress, final boolean neutralState, final boolean incremental, final boolean permanent, final boolean show, final boolean required, final RegionModule capture, final RegionModule progress, final RegionModule captured) {
this.team = team;
this.name = name;
this.id = id;
this.captureTime = captureTime;
this.points = points;
this.pointsGrowth = pointsGrowth;
this.captureRule = captureRule;
this.timeMultiplier = timeMultiplier;
this.showProgress = showProgress;
this.neutralState = neutralState;
this.incremental = incremental;
this.permanent = permanent;
this.show = show;
this.required = required;
this.capture = capture;
this.progress = progress;
this.captured = captured;
this.capturingTeam = null;
this.controlTime = 0;
scoreboardHandler = new <API key>(this);
proximityHandler = new <API key>(new Vector(0,0,0), false, false, <API key>.ProximityMetric.NULL_PROXIMITY);
proximityHandler.setObjective(this);
this.capturingPlayers = new HashSet<>();
this.tempPoints = points;
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
if (capture.contains(event.getTo()) && !capturingPlayers.contains(event.getPlayer()))
capturingPlayers.add(event.getPlayer());
if (!capture.contains(event.getTo()) && capturingPlayers.contains(event.getPlayer()))
capturingPlayers.remove(event.getPlayer());
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
if (capturingPlayers.contains(event.getEntity())) capturingPlayers.remove(event.getEntity());
}
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
if (capturingPlayers.contains(event.getPlayer())) capturingPlayers.remove(event.getPlayer());
}
@EventHandler
public void onPlayerLeave(PlayerKickEvent event) {
if (capturingPlayers.contains(event.getPlayer())) capturingPlayers.remove(event.getPlayer());
}
@Override
public TeamModule getTeam() {
return this.team;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getId() {
return this.id;
}
@Override
public boolean isTouched() {
return this.controlTime > 0 && (controlTime / captureTime) < 1;
}
@Override
public boolean isComplete() {
return (controlTime / captureTime) >= 1;
}
@Override
public boolean showOnScoreboard() {
return show;
}
@Override
public boolean isRequired() {
return required;
}
@Override
public void unload() {
HandlerList.unregisterAll(this);
capturingPlayers.clear();
}
@Override
public <API key> <API key>() {
return scoreboardHandler;
}
@Override
public <API key> getProximityHandler() {
return proximityHandler;
}
public double getPointsGrowth() {
return pointsGrowth;
}
public int getPoints() {
return points;
}
public int getCaptureTime() {
return captureTime;
}
public boolean showProgress() {
return showProgress;
}
public TeamModule getCapturingTeam() {
return capturingTeam;
}
public int getPercent() {
return (int) ((controlTime / captureTime) * 100 > 100 ? 100 : (controlTime / captureTime) * 100);
}
@Override
public void run() {
if (GameHandler.getGameHandler().getMatch().isRunning()) {
if (seconds <= MatchTimer.getTimeInSeconds()) {
seconds++;
if (team != null) {
if (seconds % pointsGrowth == 0) {
tempPoints = (int) Math.pow(tempPoints, 2);
}
if (ScoreModule.matchHasScoring()) {
for (ScoreModule score : GameHandler.getGameHandler().getMatch().getModules().getModules(ScoreModule.class)) {
if (score.getTeam() == team) {
score.setScore(score.getScore() + tempPoints);
Bukkit.getServer().getPluginManager().callEvent(new ScoreUpdateEvent(score));
}
}
}
}
}
}
}
} |
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>A Pen by Arne Hallvard Halleraker</title>
</head>
<body>
<h1>Unit 1</h1>
<h2>What a Web Page is</h2>
<p>
A web page is a text document written in a language called HTML. Web browsers read these documents, and then interpret and display them.
</p>
<h2>How Coding Works</h2>
<p>
Coding happens when programmers write text in a language that a computer can understand. The computer can then follow the instructions the programmer wrote. For example, the computer might do this by making text like this:
<br>
I'm <em>learning</em> to code!
<br>
look like this:
<br>
I'm learning to code!
</p>
<h2>Computers are Stupid</h2>
<p>
Programmers need to write exactly the way a computer understands (also known as writing with correct "syntax").
For example, if you forget to close a <b> tag, the computer won't be able to figure out what you had intended to make bold. This "stupidity" can be very frustrating, but it also gives programmers incredible power: if you know how to talk to a computer than you can tell it to do anything you want.
</p>
<h2>Programmers Can't Remember Everything </h2>
<p>
There are too many details to keep everything in your head. And that's okay. If you forget how to make text italic in HTML, you can always just look it up.
</p>
<h2>Basic HTML Vocabulary</h2>
<p>
You will be using HTML in the next few lessons, so it will be helpful if you're comfortable with the jargon. <br>
<b>Tag:</b><br> An HTML tag is always contained within angled brackets. Most tags have an opening tag (<p> for example) and a closing tag, (</p>). Some tags (called "void" tags) do not require a closing tag (like the <br> tag). <br>
<b>Element</b><br> An HTML element refers to everything within a set of opening and closing tags. <br>
<b>Attribute:</b><br> This is a property of an HTML element. For example, to set the href attribute of an anchor tag to the Udacity URL, you would write <a href="www.udacity.com"><br>
</p>
</body>
</html> |
'use strict';
angular.module('travelPlannerApp')
.controller('indexUsersCtrl', function($scope, $rootScope, $location, $translate, userService, $q, ROLES, toaster, DTOptionsBuilder, DTColumnBuilder, $compile, sweetAlertService) {
$scope.blockActions = false;
function createdRow(row) {
// Recompiling so we can bind Angular directive to the DT
$compile(angular.element(row).contents())($scope);
}
function isAdmin(user){
return user.roles.data.filter(function(role) {
return role.level === ROLES.ADMIN;
}).length > 0;
}
function actionsHtml(data) {
return '<a ng-if="adminAccess" uib-tooltip="' + $translate.instant('toggle_admin_role') + '" ng-disabled="blockActions" ng-click="toggleAdminRole(\'' + data.id + '\')"><img src="images/svg/user-2.svg"></a>' +
'<a ng-if="' + !isAdmin(data) + '" uib-tooltip="' + $translate.instant('edit') + '" ng-disabled="blockActions" ng-click="edit(\'' + data.id + '\')"><img src="images/svg/edit.svg"></a>' +
'<a ng-if="' + !isAdmin(data) + '" uib-tooltip="' + $translate.instant('delete') + '" ng-disabled="blockActions" ng-click="destroy(\'' + data.id + '\')"><img src="images/svg/trash.svg"></a>';
}
function registerDate(date) {
return moment(date).format('DD/MM/YYYY');
}
function roles(user){
return user.roles.data.map(function(role) {
return '<img style="width: 20px;" uib-tooltip="' + $translate.instant(role.name) + '" src="images/svg/role-' + role.level + '.svg">';
});
}
$scope.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
var defer = $q.defer();
userService.index().promise
.then(function(response) {
defer.resolve(response.data.data);
},
function(error) {
toaster.pop('error', $translate.instant('error'));
console.log(error);
defer.resolve([]);
});
return defer.promise;
})
.withPaginationType('full_numbers')
.withDOM('frtip')
.withOption('createdRow', createdRow)
.withLanguage(datatable_es);
$scope.dtColumns = [
DTColumnBuilder.newColumn('name').withTitle($translate('name')).withOption('sWidth', '25%'),
DTColumnBuilder.newColumn('email').withTitle($translate('email')).withOption('sWidth', '35%'),
DTColumnBuilder.newColumn('created_at').withTitle($translate('register_date')).renderWith(registerDate).withOption('sWidth', '20%'),
DTColumnBuilder.newColumn(null).withTitle($translate('roles')).renderWith(roles).withOption('sWidth', '10%'),
DTColumnBuilder.newColumn(null).withTitle($translate('action')).renderWith(actionsHtml).withClass('text-center actions').withOption('sWidth', '10%').notSortable()
];
$scope.dtInstance = {};
$scope.edit = function(id) {
$location.path('/users/edit/' + id);
};
$scope.destroy = function(id) {
sweetAlertService.confirm({ title: $translate.instant('users.question_delete'), type: 'warning' }, function(isConfirm) {
if (isConfirm) {
destroy(id);
}
});
};
$scope.toggleAdminRole = function(id) {
toggleAdminRole(id);
}
function toggleAdminRole(id) {
$scope.blockActions = true;
userService.toggleAdminRole({ id: id }).promise
.then(function(response) {
$scope.blockActions = false;
toaster.pop('success', $translate.instant('done'));
$scope.dtInstance.reloadData();
},
function(error) {
$scope.blockActions = false;
toaster.pop('error', $translate.instant('error'));
console.log(error);
});
}
function destroy(id) {
$scope.blockActions = true;
userService.destroy({ id: id }).promise
.then(function(response) {
$scope.blockActions = false;
toaster.pop('success', $translate.instant('done'));
$scope.dtInstance.reloadData();
},
function(error) {
$scope.blockActions = false;
toaster.pop('error', $translate.instant('error'));
console.log(error);
});
}
}); |
package main.java.Ionex;
import javax.swing.JTextField;
import java.awt.Event;
class ConcenTextField extends JTextField {
String lastValue;
public ConcenTextField(String string) {
super(string);
}
public boolean keyUp(Event evt, int key) {
//if the field is now empty, it's OK
String strText = getText().trim();
if (strText.equals("")) {
lastValue = getText();
return true;
}
//if the key is the return or tab or an action key, don't handle it
if ((key == 9) || (key == 10) || (evt.id == Event.KEY_ACTION_RELEASE)) {
return false;
}
//if the key pressed isn't a digit or a period or backspace, don't keep it
if (((key >= 48) && (key <= 57)) ||
(key == 46) || (key == 8) || (key == 127)) {
try {
float fValue = Float.valueOf(getText().trim()).floatValue();
if ((fValue >= 0.0) && (fValue <= 1.0)) {
lastValue = getText();
return true;
}
} catch (<API key> e) {
setText(lastValue);
// Toolkit.getDefaultToolkit().beep();
}
}
//invalid value entered
setText(lastValue);
// Toolkit.getDefaultToolkit().beep();
return true;
}
} |
<?php
namespace Ufo\Security;
use Ufo\User\User as User;
/**
* Child Exceptions.
*/
class <API key> extends <API key> {} //Thrown when brute-force attack is detected
class <API key>
{
/**
* ID of current user.
* @var string
*/
protected $userID = null;
/**
* Time after which the temporary password generated for the current user must expire.
* @var int
*/
public static $tempPassExpiryTime = 900; //15 min
/**
* It denotes the # of maximum attempts for login using the password. If this limit exceeds and this happens within a very short amount of time (which is defined by $<API key>), then it is considered as a brute force attack.
* @var int
*/
public static $<API key> = 5;
/**
* It denotes the amount of time in seconds between which no two wrong passwords must be entered. If this happens, then it is considered that a bot is trying to hack the account using brute-force.
* @var int
*/
public static $<API key> = 1; //1 SEC - This defines the time-period after which next login attempt must be carried out. E.g if the time is 1 sec, then time-period between two login attempts must minimum be 1 sec. Assuming that user will take atleast 1 sec time to type between two passwords.
/**
* It denotes the amount of time in seconds within which total number of attempts ($<API key>) must not exceed its maximum value. If this happens , then it is considered as a brute force attack.
* @var int
*/
public static $<API key> =25; //This tells that if ($<API key>) login attempts are made within ($<API key>) time then it will be a brute force.
/**
* In a summary, a brute force is when:
* 1) Two attempts are made within time specified by $<API key> i.e. for e.g. two failed login attempts must not be made within 1 second. If this behaviour is seen, then it must be a bot because humans cant make login attempts this fast.
* 2) If more than {$<API key>} login attempts are made within {$<API key>} time span. i.e. for e.g. if more than 5 failed login attempts are made within a span of 25 seconds, then it will be an odd behaviour that a human can't show. That means its a brute force attack.
*/
/**
* Constructor for the <API key> Class.
* @param String $userID //The ID of the user.
* @param String $pass //The password of the user.
* @param boolean $bruteLock //True enables brute force detection. False disables this functionality
* @throws <API key> Will be thrown if brute-force attack is detected
* @throws <API key> Will be thrown if the given password does not matches the old password stored in the DB
*/
public function __construct($userID, $pass, $bruteLock = false)
{
try
{
$this->userID = $userID;
User::existingUserObject($userID, $pass); //try to get the object of the user
}
catch(\phpsec\<API key> $e) //will be thrown if wrong password is entered
{
if ($bruteLock == true) //If brute-force detection is enabled, then check for brute-force
{
if ($this->isBruteForce($userID)) //If brute-force detected, throw the exception
throw new <API key>($e->getMessage ( ) . "\nWARNING: Brute Force Attack Detected. We Recommend you use captcha.");
}
else //If brute-force is disabled, then just throw the exception
throw $e;
}
if (! <API key>::checkIfUserExists($userID)) //If this user's record is NOT present in the PASSWORD table, then insert the new record for this user
SQL('INSERT INTO `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` (`PWD_TEMP_PASS`, `PWD_USE_FLAG`, `PWD_TEMP_TIME`, `USR_ID`) VALUES (?, ?, ?, ?)', array(randstr(10), 1, 0, $userID));
}
/**
* Function to check if the user exists in PASSWORD table or not.
* @param string $userID The userID of the user
* @return boolean Returns true if the record is present. False otherwise
*/
protected static function checkIfUserExists($userID)
{
$result = SQL('SELECT USR_ID FROM `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` WHERE USR_ID = ?', array($userID));
if(count($result) == 0)
return FALSE;
else
return TRUE;
}
/**
* Function to detect brute-force attacks.
* @param string $userID The userID of the user
* @return boolean Returns True if brute-force is detected. False otherwise
*/
protected function isBruteForce($userID)
{
$currentTime = \Ufo\Core\Init\time();
$result = SQL('SELECT `<API key>`, `<API key>`, `<API key>` FROM `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` WHERE USR_ID = ?', array($userID));
//if first_login_attempt OR last_login_attempt are not set, then set them and return false.
if ( ($result[0]['<API key>'] == 0) || ($result[0]['<API key>'] == 0) )
{
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET `<API key>` = `<API key>` + 1, `<API key>` = ?, `<API key>` = ? WHERE USR_ID = ?', array($currentTime, $currentTime, $userID));
return FALSE;
}
//if two failed login attempts are made within $<API key> time period, then reset the counters and return true to declare this a brute force attack.
if ( ($currentTime - $result[0]['<API key>']) <= <API key>::$<API key> )
{
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET `<API key>` = ?, `<API key>` = ?, `<API key>` = ? WHERE USR_ID = ?', array(0, 0, 0, $userID));
return TRUE;
}
//check if two subsequent requests are made within $<API key> time-period.
if ( ($currentTime - $result[0]['<API key>']) <= <API key>::$<API key> )
{
// To check how many total failed attempts have happened. If more than $<API key> attempts have happened, then that is an attack. Hence we reset the counters and return TRUE.
if ($result[0]['<API key>'] >= <API key>::$<API key>)
{
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET `<API key>` = ?, `<API key>` = ?, `<API key>` = ? WHERE USR_ID = ?', array(0, 0, 0, $userID));
return TRUE;
}
else //since the total login attempts have not crossed $<API key>, this is not a brute force attack. Hence we just update our counters.
{
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET `<API key>` = `<API key>` + 1, `<API key>` = ? WHERE USR_ID = ?', array($currentTime, $userID));
return FALSE;
}
}
else //since difference between two failed login requests are out of $<API key> time period, we can safely reset all the counters and TELL THAT THIS IS NOT A BRUTE FORCE ATTACK.
{
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET `<API key>` = ?, `<API key>` = ?, `<API key>` = ? WHERE USR_ID = ?', array(0, 0, 0, $userID));
return FALSE;
}
}
/**
* To check if the temporary password has expired.
* @return boolean Returns false if time not expired, else returns true.
*/
public static function <API key>($userID)
{
$result = SQL('SELECT `PWD_TEMP_TIME` FROM `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` WHERE `USR_ID` = ?', array($userID));
if (count($result) == 1)
{
if ( (time() - $result[0]['PWD_TEMP_TIME']) < <API key>::$tempPassExpiryTime)
return FALSE;
}
return TRUE;
}
/**
* Function to generate and validate a temporary password. To create a new temporary password, call this function without the second argument and the value returned will be the temporary password that will be sent to the user. To validate a temporary password, pass the temporary password to this function and will will return TRUE for valid passwords and FALSE for invalid/non-existent one's.
* @param string $userID The userID of the user
* @param string $tempPass The temporary password that needs to be checked if valid or not
* @return boolean | string Returns True if temporary password provided is valid. False otherwise. Can also return temporary password in case where the temporary password needs to be set
*/
public static function tempPassword($userID, $tempPass = "")
{
//If a temp password has not been provided, then create a temp password.
if ($tempPass == "")
{
$tempPass = hash(<API key>::$hashAlgo, \Ufo\Core\Init\randstr(128));
$time = \Ufo\Core\Init\time();
//If record is not present in the DB
if (! <API key>::checkIfUserExists($userID))
SQL('INSERT INTO `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` (`PWD_TEMP_PASS`, `PWD_USE_FLAG`, `PWD_TEMP_TIME`, USR_ID) VALUES (?, ?, ?, ?)', array($tempPass, 0, $time, $userID));
else //If record is present in the DB
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET `PWD_TEMP_PASS` = ?, `PWD_USE_FLAG` = ?, `PWD_TEMP_TIME` = ? WHERE USR_ID = ?', array($tempPass, 0, $time, $userID));
return $tempPass;
}
else //If a temp pass is provided, then check if it is not expired and it correct.
{
$result = SQL('SELECT `PWD_TEMP_PASS`, `PWD_USE_FLAG` FROM `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` WHERE `USR_ID` = ?', array($userID));
if (count($result) == 1)
{
//temporary password has not expired
if ( ($result[0]['PWD_USE_FLAG'] == 0) && (! $a = <API key>::<API key>($userID)) )
{
if ( $result[0]['PWD_TEMP_PASS'] === $tempPass ) //the provided password and the one stored in DB, matches. Hence return True
{
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET PWD_TEMP_PASS = ?, PWD_USE_FLAG = ?, PWD_TEMP_TIME = ? WHERE USR_ID = ?', array(randstr(10), 1, 0, $userID));
return TRUE;
}
}
else //temporary password has expired
{
SQL('UPDATE `'._UFO_RBAC_SCHEMA_.'`.`'.$db->manageCase('T_PASSWORD_PWD').'` SET PWD_TEMP_PASS = ?, PWD_USE_FLAG = ?, PWD_TEMP_TIME = ? WHERE USR_ID = ?', array(randstr(10), 1, 0, $userID));
return FALSE;
}
}
//record not found
return FALSE;
}
}
}
?> |
module CIL.Cecil
{
"use strict";
export const enum ModuleKind
{
Dll,
Console,
Windows,
NetModule
}
export const enum TargetArchitecture
{
I386,
AMD64,
IA64,
ARMv7
}
export const enum ModuleAttributes
{
ILOnly = 1,
Require32Bit = 2,
StrongNameSigned = 8,
Preferred32Bit = 0x00020000
}
export const enum <API key>
{
HighEntropyVA = 0x0020,
DynamicBase = 0x0040,
NoSEH = 0x0400,
NXCompat = 0x0100,
AppContainer = 0x1000,
TerminalServerAware = 0x8000,
}
} |
<?php
declare(strict_types=1);
namespace Tests\Localization;
class SrCyrlBaTest extends <API key>
{
const LOCALE = 'sr_Cyrl_BA'; // Serbian
const CASES = [
// Carbon::parse('2018-01-04 00:00:00')->addDays(1)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Tomorrow at 12:00 AM'
'сутра у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Saturday at 12:00 AM'
'у суботу у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Sunday at 12:00 AM'
'у недељу у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->addDays(4)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Monday at 12:00 AM'
'у понедељак у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->addDays(5)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Tuesday at 12:00 AM'
'у уторак у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Wednesday at 12:00 AM'
'у среду у 00:00',
// Carbon::parse('2018-01-05 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-05 00:00:00'))
// 'Thursday at 12:00 AM'
'у четвртак у 00:00',
// Carbon::parse('2018-01-06 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-06 00:00:00'))
// 'Friday at 12:00 AM'
'у петак у 00:00',
// Carbon::parse('2018-01-07 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00'))
// 'Tuesday at 12:00 AM'
'у уторак у 00:00',
// Carbon::parse('2018-01-07 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-01-07 00:00:00'))
// 'Wednesday at 12:00 AM'
'у среду у 00:00',
// Carbon::parse('2018-01-07 00:00:00')->addDays(4)->calendar(Carbon::parse('2018-01-07 00:00:00'))
// 'Thursday at 12:00 AM'
'у четвртак у 00:00',
// Carbon::parse('2018-01-07 00:00:00')->addDays(5)->calendar(Carbon::parse('2018-01-07 00:00:00'))
// 'Friday at 12:00 AM'
'у петак у 00:00',
// Carbon::parse('2018-01-07 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-07 00:00:00'))
// 'Saturday at 12:00 AM'
'у суботу у 00:00',
// Carbon::now()->subDays(2)->calendar()
// 'Last Sunday at 8:49 PM'
'прошле недеље у 20:49',
// Carbon::parse('2018-01-04 00:00:00')->subHours(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Yesterday at 10:00 PM'
'јуче у 22:00',
// Carbon::parse('2018-01-04 12:00:00')->subHours(2)->calendar(Carbon::parse('2018-01-04 12:00:00'))
// 'Today at 10:00 AM'
'данас у 10:00',
// Carbon::parse('2018-01-04 00:00:00')->addHours(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Today at 2:00 AM'
'данас у 02:00',
// Carbon::parse('2018-01-04 23:00:00')->addHours(2)->calendar(Carbon::parse('2018-01-04 23:00:00'))
// 'Tomorrow at 1:00 AM'
'сутра у 01:00',
// Carbon::parse('2018-01-07 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00'))
// 'Tuesday at 12:00 AM'
'у уторак у 00:00',
// Carbon::parse('2018-01-08 00:00:00')->subDay()->calendar(Carbon::parse('2018-01-08 00:00:00'))
// 'Yesterday at 12:00 AM'
'јуче у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->subDays(1)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Yesterday at 12:00 AM'
'јуче у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->subDays(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Last Tuesday at 12:00 AM'
'прошлог уторка у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->subDays(3)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Last Monday at 12:00 AM'
'прошлог понедељка у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->subDays(4)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Last Sunday at 12:00 AM'
'прошле недеље у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->subDays(5)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Last Saturday at 12:00 AM'
'прошле суботе у 00:00',
// Carbon::parse('2018-01-04 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-04 00:00:00'))
// 'Last Friday at 12:00 AM'
'прошлог петка у 00:00',
// Carbon::parse('2018-01-03 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-03 00:00:00'))
// 'Last Thursday at 12:00 AM'
'прошлог четвртка у 00:00',
// Carbon::parse('2018-01-02 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-02 00:00:00'))
// 'Last Wednesday at 12:00 AM'
'прошле среде у 00:00',
// Carbon::parse('2018-01-07 00:00:00')->subDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00'))
// 'Last Friday at 12:00 AM'
'прошлог петка у 00:00',
// Carbon::parse('2018-01-01 00:00:00')->isoFormat('Qo Mo Do Wo wo')
// '1st 1st 1st 1st 1st'
'1. 1. 1. 1. 1.',
// Carbon::parse('2018-01-02 00:00:00')->isoFormat('Do wo')
// '2nd 1st'
'2. 1.',
// Carbon::parse('2018-01-03 00:00:00')->isoFormat('Do wo')
// '3rd 1st'
'3. 1.',
// Carbon::parse('2018-01-04 00:00:00')->isoFormat('Do wo')
// '4th 1st'
'4. 1.',
// Carbon::parse('2018-01-05 00:00:00')->isoFormat('Do wo')
// '5th 1st'
'5. 1.',
// Carbon::parse('2018-01-06 00:00:00')->isoFormat('Do wo')
// '6th 1st'
'6. 1.',
// Carbon::parse('2018-01-07 00:00:00')->isoFormat('Do wo')
// '7th 2nd'
'7. 1.',
// Carbon::parse('2018-01-11 00:00:00')->isoFormat('Do wo')
// '11th 2nd'
'11. 2.',
// Carbon::parse('2018-02-09 00:00:00')->isoFormat('DDDo')
// '40th'
'40.',
// Carbon::parse('2018-02-10 00:00:00')->isoFormat('DDDo')
// '41st'
'41.',
// Carbon::parse('2018-04-10 00:00:00')->isoFormat('DDDo')
// '100th'
'100.',
// Carbon::parse('2018-02-10 00:00:00', 'Europe/Paris')->isoFormat('h:mm a z')
// '12:00 am CET'
'12:00 ам CET',
// Carbon::parse('2018-02-10 00:00:00')->isoFormat('h:mm A, h:mm a')
// '12:00 AM, 12:00 am'
'12:00 АМ, 12:00 ам',
// Carbon::parse('2018-02-10 01:30:00')->isoFormat('h:mm A, h:mm a')
// '1:30 AM, 1:30 am'
'1:30 АМ, 1:30 ам',
// Carbon::parse('2018-02-10 02:00:00')->isoFormat('h:mm A, h:mm a')
// '2:00 AM, 2:00 am'
'2:00 АМ, 2:00 ам',
// Carbon::parse('2018-02-10 06:00:00')->isoFormat('h:mm A, h:mm a')
// '6:00 AM, 6:00 am'
'6:00 АМ, 6:00 ам',
// Carbon::parse('2018-02-10 10:00:00')->isoFormat('h:mm A, h:mm a')
// '10:00 AM, 10:00 am'
'10:00 АМ, 10:00 ам',
// Carbon::parse('2018-02-10 12:00:00')->isoFormat('h:mm A, h:mm a')
// '12:00 PM, 12:00 pm'
'12:00 ПМ, 12:00 пм',
// Carbon::parse('2018-02-10 17:00:00')->isoFormat('h:mm A, h:mm a')
// '5:00 PM, 5:00 pm'
'5:00 ПМ, 5:00 пм',
// Carbon::parse('2018-02-10 21:30:00')->isoFormat('h:mm A, h:mm a')
// '9:30 PM, 9:30 pm'
'9:30 ПМ, 9:30 пм',
// Carbon::parse('2018-02-10 23:00:00')->isoFormat('h:mm A, h:mm a')
// '11:00 PM, 11:00 pm'
'11:00 ПМ, 11:00 пм',
// Carbon::parse('2018-01-01 00:00:00')->ordinal('hour')
// '0th'
'0.',
// Carbon::now()->subSeconds(1)->diffForHumans()
// '1 second ago'
'пре 1 секунд',
// Carbon::now()->subSeconds(1)->diffForHumans(null, false, true)
// '1s ago'
'пре 1 сек.',
// Carbon::now()->subSeconds(2)->diffForHumans()
// '2 seconds ago'
'пре 2 секунде',
// Carbon::now()->subSeconds(2)->diffForHumans(null, false, true)
// '2s ago'
'пре 2 сек.',
// Carbon::now()->subMinutes(1)->diffForHumans()
// '1 minute ago'
'пре 1 минут',
// Carbon::now()->subMinutes(1)->diffForHumans(null, false, true)
// '1m ago'
'пре 1 мин.',
// Carbon::now()->subMinutes(2)->diffForHumans()
// '2 minutes ago'
'пре 2 минута',
// Carbon::now()->subMinutes(2)->diffForHumans(null, false, true)
// '2m ago'
'пре 2 мин.',
// Carbon::now()->subHours(1)->diffForHumans()
// '1 hour ago'
'пре 1 сат',
// Carbon::now()->subHours(1)->diffForHumans(null, false, true)
// '1h ago'
'пре 1 ч.',
// Carbon::now()->subHours(2)->diffForHumans()
// '2 hours ago'
'пре 2 сата',
// Carbon::now()->subHours(2)->diffForHumans(null, false, true)
// '2h ago'
'пре 2 ч.',
// Carbon::now()->subDays(1)->diffForHumans()
// '1 day ago'
'пре 1 дан',
// Carbon::now()->subDays(1)->diffForHumans(null, false, true)
// '1d ago'
'пре 1 д.',
// Carbon::now()->subDays(2)->diffForHumans()
// '2 days ago'
'пре 2 дана',
// Carbon::now()->subDays(2)->diffForHumans(null, false, true)
// '2d ago'
'пре 2 д.',
// Carbon::now()->subWeeks(1)->diffForHumans()
// '1 week ago'
'пре 1 недељу',
// Carbon::now()->subWeeks(1)->diffForHumans(null, false, true)
// '1w ago'
'пре 1 нед.',
// Carbon::now()->subWeeks(2)->diffForHumans()
// '2 weeks ago'
'пре 2 недеље',
// Carbon::now()->subWeeks(2)->diffForHumans(null, false, true)
// '2w ago'
'пре 2 нед.',
// Carbon::now()->subMonths(1)->diffForHumans()
// '1 month ago'
'пре 1 месец',
// Carbon::now()->subMonths(1)->diffForHumans(null, false, true)
// '1mo ago'
'пре 1 м.',
// Carbon::now()->subMonths(2)->diffForHumans()
// '2 months ago'
'пре 2 месеца',
// Carbon::now()->subMonths(2)->diffForHumans(null, false, true)
// '2mos ago'
'пре 2 м.',
// Carbon::now()->subYears(1)->diffForHumans()
// '1 year ago'
'пре 1 годину',
// Carbon::now()->subYears(1)->diffForHumans(null, false, true)
// '1yr ago'
'пре 1 г.',
// Carbon::now()->subYears(2)->diffForHumans()
// '2 years ago'
'пре 2 године',
// Carbon::now()->subYears(2)->diffForHumans(null, false, true)
// '2yrs ago'
'пре 2 г.',
// Carbon::now()->addSecond()->diffForHumans()
// '1 second from now'
'за 1 секунд',
// Carbon::now()->addSecond()->diffForHumans(null, false, true)
// '1s from now'
'за 1 сек.',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now())
// '1 second after'
'1 секунд након',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now(), false, true)
// '1s after'
'1 сек. након',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond())
// '1 second before'
'1 секунд пре',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond(), false, true)
// '1s before'
'1 сек. пре',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now(), true)
// '1 second'
'1 секунд',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now(), true, true)
'1 сек.',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond()->addSecond(), true)
// '2 seconds'
'2 секунде',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond()->addSecond(), true, true)
'2 сек.',
// Carbon::now()->addSecond()->diffForHumans(null, false, true, 1)
// '1s from now'
'за 1 сек.',
// Carbon::now()->addMinute()->addSecond()->diffForHumans(null, true, false, 2)
// '1 minute 1 second'
'1 минут 1 секунд',
// Carbon::now()->addYears(2)->addMonths(3)->addDay()->addSecond()->diffForHumans(null, true, true, 4)
// '2yrs 3mos 1d 1s'
'2 г. 3 м. 1 д. 1 сек.',
// Carbon::now()->addYears(3)->diffForHumans(null, null, false, 4)
// '3 years from now'
'за 3 године',
// Carbon::now()->subMonths(5)->diffForHumans(null, null, true, 4)
// '5mos ago'
'пре 5 м.',
// Carbon::now()->subYears(2)->subMonths(3)->subDay()->subSecond()->diffForHumans(null, null, true, 4)
// '2yrs 3mos 1d 1s ago'
'пре 2 г. 3 м. 1 д. 1 сек.',
// Carbon::now()->addWeek()->addHours(10)->diffForHumans(null, true, false, 2)
// '1 week 10 hours'
'1 недеља 10 сати',
// Carbon::now()->addWeek()->addDays(6)->diffForHumans(null, true, false, 2)
// '1 week 6 days'
'1 недеља 6 дана',
// Carbon::now()->addWeek()->addDays(6)->diffForHumans(null, true, false, 2)
// '1 week 6 days'
'1 недеља 6 дана',
// Carbon::now()->addWeek()->addDays(6)->diffForHumans(["join" => true, "parts" => 2])
// '1 week and 6 days from now'
'за 1 недељу и 6 дана',
// Carbon::now()->addWeeks(2)->addHour()->diffForHumans(null, true, false, 2)
// '2 weeks 1 hour'
'2 недеље 1 сат',
// Carbon::now()->addHour()->diffForHumans(["aUnit" => true])
// 'an hour from now'
'за 1 сат',
// CarbonInterval::days(2)->forHumans()
// '2 days'
'2 дана',
// CarbonInterval::create('P1DT3H')->forHumans(true)
// '1d 3h'
'1 д. 3 ч.',
];
} |
<?php return unserialize('a:2:{i:0;O:26:"Doctrine\\ORM\\Mapping\\Table":5:{s:4:"name";N;s:6:"schema";N;s:7:"indexes";N;s:17:"uniqueConstraints";N;s:7:"options";a:0:{}}i:1;O:27:"Doctrine\\ORM\\Mapping\\Entity":2:{s:15:"repositoryClass";s:46:"LBcrew\\MessagesBundle\\Entity\\messageRepository";s:8:"readOnly";b:0;}}'); |
(function () {
'use strict';
angular
.module("fc.configuration")
.provider("hierarchyConfigSvc", <API key>);
/* @ngInject */
function <API key>() {
// Available in config.
var cfg = this;
cfg.activateEndpoint = "activate";
cfg.deactivateEndpoint = "deactivate";
cfg.hierarchyConfigUrl = null;
cfg.hierarchyDataUrlTpl = null;
cfg.$get = hierarchyConfigSvc;
hierarchyConfigSvc.$inject = ["$http"];
function hierarchyConfigSvc($http) {
return {
<API key>: <API key>,
getHierarchyConfig: getHierarchyConfig
};
function <API key>(config) {
var url = cfg.hierarchyConfigUrl;
return $http.post(url, config).then(function (result) {
return result.data;
});
}
function getHierarchyConfig() {
var url = cfg.hierarchyConfigUrl;
return $http.get(url).then(function (result) {
return result.data;
});
}
}
}
})(); |
<html>
<head>
- CDC for Kettle
</head>
<body>
<script>
(function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','
ga('create', 'UA-73319123-1', 'auto');
ga('send', 'pageview');
ga('create', 'UA-XXXX-Y', { 'userId': 'haozhu123' });
ga('send', 'pageview');
</script>
<h1> - CDC for Kettle </h1>
<p>DIB()(Business Intelligence)
<p>DIBETLCDC(Change Data Capture)
<br><hr>
<p>
<script>
ga('send', {
hitType: 'event',
eventCategory: 'Videos',
eventAction: 'play',
eventLabel: 'Fall Campaign'
});
</script>
</body>
</html> |
package com.editize.editorkit;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.Vector;
import java.util.Iterator;
import com.editize.*;
/**
* Dialog to choose an image and its attributes.
*/
public class TableDialog extends JDialog implements ActionListener
{
public static final int OK = 0;
public static final int CANCEL = 1;
public static final int CLOSED = 2;
public static final String NOTABLECLASSLABEL = "none";
private JTextField rowsField;
private JTextField colsField;
private JTextField widthField;
private JTextField heightField;
private JTextField borderField;
private JComboBox alignBox;
private JButton advancedButton;
private JButton okButton;
private JButton cancelButton;
private JPanel tablePanel;
private JPanel sizePanel;
private JPanel stylePanel;
private JPanel buttonPanel;
private static WindowAdapter wa = new DialogAdapter();
private boolean showAdvanced = false;
private int exitType = CLOSED;
private JLabel classLabel;
private JComboBox classCombo;
public TableDialog(JEditorPane editor)
{
super(JOptionPane.<API key>(editor),"Insert Table",true);
layoutUI();
// Set defaults
colsField.setText("5");
rowsField.setText("2");
borderField.setText("1");
// Detect and load available table classes
EditizeDocument doc = (EditizeDocument)editor.getDocument();
Vector availClasses = doc.getTableClasses();
if (availClasses != null) {
Iterator it = availClasses.iterator();
while (it.hasNext()) {
classCombo.addItem(it.next());
}
} else {
classLabel.setVisible(false);
classCombo.setVisible(false);
}
eventWireup();
pack();
setResizable(true);
}
/**
* Gets the method used to close the dialog.
* @return OK, CANCEL, or CLOSED
*/
public int getCloseOption()
{
return exitType;
}
public String getRows()
{
String rows = rowsField.getText().trim();
if (rows.length() == 0) rows = "1";
return rows;
}
public void setRows(String value)
{
rowsField.setText(value);
}
public String getCols()
{
String cols = colsField.getText().trim();
if (cols.length() == 0) cols = "1";
return cols;
}
public void setCols(String value)
{
colsField.setText(value);
}
/**
* Gets the chosen table class.
* @return String The chosen table class, or null if none selected.
*/
public String getTableClass()
{
String tableClass = classCombo.getSelectedItem().toString();
if (tableClass.equals(NOTABLECLASSLABEL)) return null;
return tableClass.trim();
}
/**
* Sets the selected table class. Has no effect if the specified class is
* not available in the list of available classes.
* @param tableClass String The class name to select.
*/
public void setTableClass(String tableClass)
{
int c = classCombo.getItemCount();
for (int i = 0; i < c; i++)
{
if (classCombo.getItemAt(i).toString().equalsIgnoreCase(tableClass))
{
classCombo.setSelectedIndex(i);
break;
}
}
}
public String getTableBorder()
{
String border = borderField.getText().trim();
if (border.length() == 0) border = "0";
return border;
}
public void setTableBorder(String b)
{
borderField.setText(b);
}
public String getTableWidth()
{
String width = widthField.getText().trim();
if (width.length() == 0) width = null;
return width;
}
public void setTableWidth(String b)
{
widthField.setText(b);
}
public String getTableHeight()
{
String height = heightField.getText().trim();
if (height.length() == 0) height = null;
return height;
}
public void setTableHeight(String b)
{
heightField.setText(b);
}
public String getTableAlign()
{
String align = alignBox.getSelectedItem().toString();
if (align.equals("default")) return null;
else return align;
}
public void setTableAlign(String align)
{
int c = alignBox.getItemCount();
for (int i=0; i<c; i++)
{
if (alignBox.getItemAt(i).toString().equalsIgnoreCase(align))
{
alignBox.setSelectedIndex(i);
break;
}
}
}
public void actionPerformed(ActionEvent ev)
{
Object src = ev.getSource();
if (src == advancedButton)
{
showAdvanced = !showAdvanced;
stylePanel.setVisible(showAdvanced);
advancedButton.setText(showAdvanced ? "Simple" : "Advanced");
pack();
}
else if (src == okButton)
{
exitType = OK;
hide();
}
else if (src == cancelButton)
{
exitType = CANCEL;
hide();
}
}
protected void eventWireup()
{
advancedButton.addActionListener(this);
okButton.addActionListener(this);
cancelButton.addActionListener(this);
addWindowListener(wa);
}
protected void layoutUI()
{
Component c;
Container rootPane = getContentPane();
rootPane.setLayout(new BorderLayout());
JPanel root = new JPanel();
rootPane.add(root,BorderLayout.CENTER);
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
root.setLayout(gbl);
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.insets = new Insets(2,2,2,2);
layoutTablePanel();
c = tablePanel;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.weighty = 1;
gbl.setConstraints(c,gbc);
root.add(c);
layoutButtonPanel();
c = buttonPanel;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2,2,2,2);
gbl.setConstraints(c,gbc);
root.add(c);
}
protected void layoutTablePanel()
{
if (tablePanel == null)
{
Component c;
tablePanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
tablePanel.setLayout(gbl);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(0,0,0,0);
layoutSizePanel();
c = sizePanel;
gbl.setConstraints(c,gbc);
tablePanel.add(c);
layoutStylePanel();
c = stylePanel;
gbl.setConstraints(c,gbc);
tablePanel.add(c);
c.setVisible(showAdvanced);
}
}
protected void layoutSizePanel()
{
if (sizePanel == null)
{
Component c;
sizePanel = new JPanel();
sizePanel.setBorder(new TitledBorder("Table Size"));
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
sizePanel.setLayout(gbl);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(2,2,2,2);
c = new JLabel("Number of Rows:");
gbl.setConstraints(c,gbc);
sizePanel.add(c);
c = rowsField = new ClipTextField(new <API key>(),"1",5);
gbc.fill = GridBagConstraints.NONE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1.0;
gbl.setConstraints(c,gbc);
sizePanel.add(c);
c = new JLabel("Number of Columns:");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.weightx = 0.0;
gbl.setConstraints(c,gbc);
sizePanel.add(c);
c = colsField = new ClipTextField(new <API key>(),"1",5);
gbc.fill = GridBagConstraints.NONE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1.0;
gbl.setConstraints(c,gbc);
sizePanel.add(c);
}
}
protected void layoutStylePanel()
{
if (stylePanel == null)
{
Component c;
stylePanel = new JPanel();
stylePanel.setBorder(new TitledBorder("Table Style"));
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
stylePanel.setLayout(gbl);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(2,2,2,2);
c = classLabel = new JLabel("Class:");
gbc.gridwidth = 1;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = classCombo = new JComboBox(new Object[] {NOTABLECLASSLABEL});
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = new JLabel("Border size:");
gbc.gridwidth = 1;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = borderField = new ClipTextField(new <API key>(true),"0",3);
gbc.fill = GridBagConstraints.NONE;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = new JLabel("pixels");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = new JLabel("Width:");
gbc.gridwidth = 1;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = widthField = new ClipTextField(5);
gbc.fill = GridBagConstraints.NONE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = new JLabel("Height:");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = heightField = new ClipTextField(5);
gbc.fill = GridBagConstraints.NONE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = new JLabel("Alignment:");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
c = alignBox = new JComboBox(
new Object[] {"default","left","center","right"});
gbc.fill = GridBagConstraints.NONE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(c,gbc);
stylePanel.add(c);
}
}
protected void layoutButtonPanel()
{
if (buttonPanel == null)
{
buttonPanel = new JPanel();
buttonPanel.add(okButton = new JButton("OK"));
buttonPanel.add(cancelButton = new JButton("Cancel"));
buttonPanel.add(advancedButton = new JButton(
showAdvanced ? "Simple" : "Advanced"));
}
}
private static class DialogAdapter extends WindowAdapter
{
public void windowClosed(WindowEvent ev)
{
TableDialog src = (TableDialog)ev.getWindow();
src.exitType = CLOSED;
}
}
} |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class tweet {
private $_oauth = NULL;
function __construct()
{
$this->_oauth = new tweetOauth();
}
function __call($method, $args)
{
if ( method_exists($this, $method) )
{
return <API key>(array($this, $method), $args);
}
return <API key>(array($this->_oauth, $method), $args);
}
function logged_in()
{
return $this->_oauth->loggedIn();
}
function set_callback($url)
{
$this->_oauth->setCallback($url);
}
function login()
{
return $this->_oauth->login();
}
function logout()
{
return $this->_oauth->logout();
}
function get_tokens()
{
$tokens = array(
'oauth_token' => $this->_oauth->getAccessKey(),
'oauth_token_secret' => $this->_oauth->getAccessSecret()
);
return $tokens;
}
function set_tokens($tokens)
{
return $this->_oauth->setAccessTokens($tokens);
}
}
class tweetException extends Exception {
function __construct($string)
{
parent::__construct($string);
}
public function __toString() {
return "exception '".__CLASS__ ."' with message '".$this->getMessage()."' in ".$this->getFile().":".$this->getLine()."\nStack trace:\n".$this->getTraceAsString();
}
}
class tweetConnection {
// Allow multi-threading.
private $_mch = NULL;
private $_properties = array();
function __construct()
{
$this->_mch = curl_multi_init();
$this->_properties = array(
'code' => CURLINFO_HTTP_CODE,
'time' => CURLINFO_TOTAL_TIME,
'length' => <API key>,
'type' => <API key>
);
}
private function _initConnection($url)
{
$this->_ch = curl_init($url);
curl_setopt($this->_ch, <API key>, TRUE);
}
public function get($url, $params)
{
if ( count($params['request']) > 0 )
{
/*$url .= '?';
foreach( $params['request'] as $k => $v )
{
$url .= "{$k}={$v}&";
}
$url = substr($url, 0, -1);*/
$url = http_build_query($params);
}
$this->_initConnection($url);
$response = $this->_addCurl($url, $params);
return $response;
}
public function post($url, $params)
{
// Todo
$post = '';
foreach ( $params['request'] as $k => $v )
{
$post .= "{$k}={$v}&";
}
$post = substr($post, 0, -1);
$this->_initConnection($url, $params);
curl_setopt($this->_ch, CURLOPT_POST, 1);
curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $post);
$response = $this->_addCurl($url, $params);
return $response;
}
private function _addOauthHeaders(&$ch, $url, $oauthHeaders)
{
//$_h = array('Expect:');
$_h = array('Expect:', "Connection: Keep-Alive", "Cache-Control: no-cache", "User-Agent: " . $_SERVER['HTTP_USER_AGENT']);
$urlParts = parse_url($url);
$oauth = 'Authorization: OAuth realm="' . $urlParts['path'] . '",';
foreach ( $oauthHeaders as $name => $value )
{
$oauth .= "{$name}=\"{$value}\",";
}
// Additional headers
$_h[] = substr($oauth, 0, -1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $_h);
}
private function _addCurl($url, $params = array())
{
if ( !empty($params['oauth']) )
{
$this->_addOauthHeaders($this->_ch, $url, $params['oauth']);
}
$ch = $this->_ch;
$key = (string) $ch;
$this->_requests[$key] = $ch;
$response = <API key>($this->_mch, $ch);
if ( $response === CURLM_OK || $response === <API key> )
{
do {
$mch = curl_multi_exec($this->_mch, $active);
} while ( $mch === <API key> );
return $this->_getResponse($key);
}
else
{
return $response;
}
}
private function _getResponse($key = NULL)
{
if ( $key == NULL ) return FALSE;
if ( isset($this->_responses[$key]) )
{
return $this->_responses[$key];
}
$running = NULL;
do
{
$response = curl_multi_exec($this->_mch, $running_curl);
if ( $running !== NULL && $running_curl != $running )
{
$this->_setResponse($key);
if ( isset($this->_responses[$key]) )
{
$response = new tweetResponseOauth( (object) $this->_responses[$key] );
if ( $response->__resp->code !== 200 )
{
throw new tweetException($response->__resp->code.' | Request Failed: '.$response->__resp->data->request.' - '.$response->__resp->data->error);
}
return $response;
}
}
$running = $running_curl;
} while ( $running_curl > 0);
}
private function _setResponse($key)
{
while( $done = <API key>($this->_mch) )
{
$key = (string) $done['handle'];
$this->_responses[$key]['data'] = <API key>($done['handle']);
foreach ( $this->_properties as $curl_key => $value )
{
$this->_responses[$key][$curl_key] = curl_getinfo($done['handle'], $value);
<API key>($this->_mch, $done['handle']);
}
}
}
}
class tweetResponseOauth {
private $__construct;
public function __construct($resp)
{
$this->__resp = $resp;
if ( strpos($this->__resp->type, 'json') !== FALSE )
{
$this->__resp->data = json_decode($this->__resp->data);
}
}
public function __get($name)
{
if ($this->__resp->code < 200 || $this->__resp->code > 299) return FALSE;
if ( is_string($this->__resp->data ) )
{
parse_str($this->__resp->data, $result);
}
else
{
$result = $this->__resp->data;
}
foreach($result as $k => $v)
{
$this->$k = $v;
}
if ( $name === '_result')
{
return $result;
}
return $result[$name];
}
}
class tweetOauth extends tweetConnection {
private $_obj;
private $_tokens = array();
private $_authorizationUrl = 'https://api.twitter.com/oauth/authenticate';
private $_requestTokenUrl = 'http://api.twitter.com/oauth/request_token';
private $_accessTokenUrl = 'http://api.twitter.com/oauth/access_token';
private $_signatureMethod = 'HMAC-SHA1';
private $_version = '1.0';
private $_apiUrl = 'http://api.twitter.com/1';
private $_searchUrl = 'http://search.twitter.com/';
private $_uploadUrl = 'https://upload.twitter.com/1/';
private $_callback = NULL;
private $_errors = array();
private $_enable_debug = FALSE;
private $_multipart = FALSE;
function __construct()
{
parent::__construct();
$this->_obj =& get_instance();
$this->_obj->load->config('tweet');
$this->_obj->load->library('session');
$this->_obj->load->library('unit_test');
$this->_obj->load->helper('url');
$this->_tokens = array(
'consumer_key' => $this->_obj->config->item('tweet_consumer_key'),
'consumer_secret' => $this->_obj->config->item('<API key>'),
'access_key' => $this->_getAccessKey(),
'access_secret' => $this->_getAccessSecret()
);
$this->_checkLogin();
}
function __destruct()
{
if ( !$this->_enable_debug ) return;
if ( !empty($this->_errors) )
{
foreach ( $this->_errors as $key => $e )
{
echo '<pre>'.$e.'</pre>';
}
}
}
public function enable_debug($debug)
{
$debug = (bool) $debug;
$this->_enable_debug = $debug;
}
public function call($method, $path, $args = NULL)
{
$response = $this->_httpRequest(strtoupper($method), $this->_apiUrl.'/'.$path.'.json', $args);
// var_dump($response);
// die();
return ( $response === NULL ) ? FALSE : $response->_result;
}
public function upload($args = NULL)
{
$this->_multipart = TRUE;
$response = $this->_httpRequest('POST', $this->_uploadUrl.'statuses/update_with_media.json', $args);
return ( $response === NULL ) ? FALSE : $response->_result;
}
public function search($args = NULL)
{
$response = $this->_httpRequest('GET', $this->_searchUrl.'search.json', $args);
return ( $response === NULL ) ? FALSE : $response->_result;
}
public function loggedIn()
{
$access_key = $this->_getAccessKey();
$access_secret = $this->_getAccessSecret();
$loggedIn = FALSE;
if ( $this->_getAccessKey() !== NULL && $this->_getAccessSecret() !== NULL )
{
$loggedIn = TRUE;
}
$this->_obj->unit->run($loggedIn, TRUE, 'Logged In');
return $loggedIn;
}
private function _checkLogin()
{
if ( isset($_GET['oauth_token']) )
{
$this->_setAccessKey($_GET['oauth_token']);
$token = $this->_getAccessToken();
$token = $token->_result;
$token = ( is_bool($token) ) ? $token : (object) $token;
if ( !empty($token->oauth_token) && !empty($token->oauth_token_secret) )
{
$this->_setAccessKey($token->oauth_token);
$this->_setAccessSecret($token->oauth_token_secret);
}
redirect(current_url());
return NULL;
}
}
public function login()
{
if ( ($this->_getAccessKey() === NULL || $this->_getAccessSecret() === NULL) )
{
header('Location: '.$this-><API key>());
return;
}
return $this->_checkLogin();
}
public function logout()
{
$this->_obj->session->unset_userdata('<TwitterConsumerkey>');
}
public function getTokens()
{
return $this->_tokens;
}
private function _getConsumerKey()
{
return $this->_tokens['consumer_key'];
}
private function _getConsumerSecret()
{
return $this->_tokens['consumer_secret'];
}
public function getAccessKey(){ return $this->_getAccessKey(); }
private function _getAccessKey()
{
$tokens = $this->_obj->session->userdata('<TwitterConsumerkey>');
return ( $tokens === FALSE || !isset($tokens['access_key']) || empty($tokens['access_key']) ) ? NULL : $tokens['access_key'];
}
private function _setAccessKey($access_key)
{
$tokens = $this->_obj->session->userdata('<TwitterConsumerkey>');
if ( $tokens === FALSE || !is_array($tokens) )
{
$tokens = array('access_key' => $access_key);
}
else
{
$tokens['access_key'] = $access_key;
}
$this->_obj->session->set_userdata('<TwitterConsumerkey>', $tokens);
}
public function getAccessSecret(){ return $this->_getAccessSecret(); }
private function _getAccessSecret()
{
$tokens = $this->_obj->session->userdata('<TwitterConsumerkey>');
return ( $tokens === FALSE || !isset($tokens['access_secret']) || empty($tokens['access_secret']) ) ? NULL : $tokens['access_secret'];
}
private function _setAccessSecret($access_secret)
{
$tokens = $this->_obj->session->userdata('<TwitterConsumerkey>');
if ( $tokens === FALSE || !is_array($tokens) )
{
$tokens = array('access_secret' => $access_secret);
}
else
{
$tokens['access_secret'] = $access_secret;
}
$this->_obj->session->set_userdata('<TwitterConsumerkey>', $tokens);
}
private function _setAccessTokens($tokens)
{
$this->_setAccessKey($tokens['oauth_token']);
$this->_setAccessSecret($tokens['oauth_token_secret']);
}
public function setAccessTokens($tokens)
{
return $this->_setAccessTokens($tokens);
}
private function <API key>()
{
$token = $this->_getRequestToken();
return $this->_authorizationUrl.'?oauth_token=' . $token->oauth_token;
}
private function _getRequestToken()
{
return $this->_httpRequest('GET', $this->_requestTokenUrl);
}
private function _getAccessToken()
{
return $this->_httpRequest('GET', $this->_accessTokenUrl);
}
protected function _httpRequest($method = null, $url = null, $params = null)
{
if( empty($method) || empty($url) ) return FALSE;
if ( empty($params['oauth_signature']) ) $params = $this->_prepareParameters($method, $url, $params);
$this->_connection = new tweetConnection();
try {
switch ( $method )
{
case 'GET':
return $this->_connection->get($url, $params);
break;
case 'POST':
return $this->_connection->post($url, $params);
//print_r($url);
//exit;
//return $this->_connection->post($url, $params, $this->_multipart);
break;
case 'PUT':
return NULL;
break;
case 'DELETE':
return NULL;
break;
}
} catch (tweetException $e) {
$this->_errors[] = $e;
}
}
private function _getCallback()
{
return $this->_callback;
}
public function setCallback($url)
{
$this->_callback = $url;
}
private function _prepareParameters($method = NULL, $url = NULL, $params = NULL)
{
if ( empty($method) || empty($url) ) return FALSE;
$callback = $this->_getCallback();
if ( !empty($callback) )
{
$oauth['oauth_callback'] = $callback;
}
$this->setCallback(NULL);
$oauth['oauth_consumer_key'] = $this->_getConsumerKey();
$oauth['oauth_token'] = $this->_getAccessKey();
$oauth['oauth_nonce'] = $this->_generateNonce();
$oauth['oauth_timestamp'] = time();
$oauth['o<API key>] = $this->_signatureMethod;
$oauth['oauth_version'] = $this->_version;
array_walk($oauth, array($this, '_encode_rfc3986'));
if($this->_multipart)
{
$request_params = $params;
$params = array();
}
if ( is_array($params) )
{
array_walk($params, array($this, '_encode_rfc3986'));
}
$encodedParams = array_merge($oauth, (array)$params);
ksort($encodedParams);
$oauth['oauth_signature'] = $this->_encode_rfc3986($this->_generateSignature($method, $url, $encodedParams));
//return array('request' => $params, 'oauth' => $oauth);
if($this->_multipart){
return array('request' => $request_params, 'oauth' => $oauth);
} else {
return array('request' => $params, 'oauth' => $oauth);
}
}
private function _generateNonce()
{
return md5(uniqid(rand(), TRUE));
}
private function _encode_rfc3986($string)
{
return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode(($string))));
}
private function _generateSignature($method = null, $url = null, $params = null)
{
if( empty($method) || empty($url) ) return FALSE;
// concatenating
$concatenatedParams = '';
foreach ($params as $k => $v)
{
$k = $this->_encode_rfc3986($k);
$v = $this->_encode_rfc3986($v);
$concatenatedParams .= "{$k}={$v}&";
}
$concatenatedParams = $this->_encode_rfc3986(substr($concatenatedParams, 0, -1));
// normalize url
//$normalizedUrl = $this->_encode_rfc3986($this->_normalizeUrl($url));
// Using the normalized url when uploading generates a 401 issue, yet for other api calls there's not a problem...
if($this->_multipart){
$normalizedUrl = $this->_encode_rfc3986($url);
} else {
$normalizedUrl = $this->_encode_rfc3986($this->_normalizeUrl($url));
}
$method = $this->_encode_rfc3986($method); // don't need this but why not?
$signatureBaseString = "{$method}&{$normalizedUrl}&{$concatenatedParams}";
return $this->_signString($signatureBaseString);
}
private function _normalizeUrl($url = NULL)
{
$urlParts = parse_url($url);
if ( !isset($urlParts['port']) ) $urlParts['port'] = 80;
$scheme = strtolower($urlParts['scheme']);
$host = strtolower($urlParts['host']);
$port = intval($urlParts['port']);
$retval = "{$scheme}://{$host}";
if ( $port > 0 && ( $scheme === 'http' && $port !== 80 ) || ( $scheme === 'https' && $port !== 443 ) )
{
$retval .= ":{$port}";
}
$retval .= $urlParts['path'];
if ( !empty($urlParts['query']) )
{
$retval .= "?{$urlParts['query']}";
}
return $retval;
}
private function _signString($string)
{
$retval = FALSE;
switch ( $this->_signatureMethod )
{
case 'HMAC-SHA1':
$key = $this->_encode_rfc3986($this->_getConsumerSecret()) . '&' . $this->_encode_rfc3986($this->_getAccessSecret());
$retval = base64_encode(hash_hmac('sha1', $string, $key, true));
break;
}
return $retval;
}
} |
<?php
require_once('IController.php');
require_once('Configs.php');
require_once('ChocalaVars.php');
/**
* Description of WebController
* @author ypra
*/
abstract class WebController implements IController
{
protected $allowedMethods = array();
/**
*
* @var boolean
*/
protected $rendered = false;
/**
* The view class engine that generate the html code to return to the client
* @var WebView
*/
protected $view = null;
/**
* The name of the layout that will be generated
* @var string
*/
protected $layout = null;
/**
* The template file that will be used for generate the page
* @var string
*/
protected $template = null;
/**
* The ID that drive the page
* @var mixed
*/
protected $id = null;
final public function __construct()
{
$this->id = GlobalVars::instance()->id();
$this->layout = Configs::value('app.default.layout');
$this->view = new WebView($this->layout);
}
/**
* Initialization of generic operations, configurations or steps for all
* methods of the controller class
* @return void
*/
public function _init()
{
}
final public function isRendered()
{
return $this->rendered;
}
/**
* Set a variable to view
* @param string $name
* @param mixed $value
*/
final public function setVar($name, $value)
{
$this->view->setVar($name, $value);
}
/**
* Send directly the content as response from the request page
*
* @param string $content
* @return void
*/
final public function render($content)
{
$this->view->render($content);
$this->rendered = true;
}
/**
* Generate and display the html code from request page with action,
* controller and module properties using the layout and template on the
* view engine
* @param string $view
* @param string $module
* @return void
*/
final public function renderView($view, $module=null)
{
$this->view->renderView(lcfirst($view), $module);
$this->rendered = true;
}
/**
* Generate and send a json response encoding the controller's vars from
* request page with action, controller and module
*
* @return void
*/
final public function renderAsJSON()
{
$this->view->renderJSON();
$this->rendered = true;
}
/**
*
* @param array $arrayMap
* @param boolean $permanently
* @return void
*/
final public function redirectTo($arrayMap, $permanently = false)
{
$URI = URI::createURLTo($arrayMap);
Headers::instance()->redirectTo($URI, $permanently);
}
/**
* Routing to default page for request to unexisting pages
*
* @return void
*/
final public function noRoute()
{
$this->setVar('__exceptions', <API key>::exceptions());
}
/**
* Verify if the action is requested as a allowed method
*
* @param string $action
* @param string $method
* @return boolean
*/
final public function isAllowedMethod($action)
{
$method = HttpManager::requestMethod();
if(isset($this->allowedMethods[$action])){
return strtoupper(trim($this->allowedMethods[$action])) == $method;
}
return true;
}
} |
#ifndef SQLITE_LIBCU_H
#define SQLITE_LIBCU_H
#include <ext/global.h>
// CUDA
#define METHOD __host_device__
#define FIELD __device__
#define CONSTFIELD __constant__
#define __error__ ERROR
#define __implement__ panic("__implement__")
#pragma region Basetypes
#define SQLITE_PTRSIZE PTRSIZE_
#define SQLITE_WITHIN WITHIN_
#define UNUSED_PARAMETER UNUSED_SYMBOL
#define ArraySize ARRAYSIZE_
#define MIN MIN_
#define testcase TESTCASE_
#define VVA_ONLY DEBUGONLY_
#define ALWAYS ALWAYS_
#define NEVER NEVER_
#define SQLITE_DEBUG _DEBUG
#define <API key> LIBCU_HAVE_OS_TRACE
#define SQLITE_OS_OTHER __OS_OTHER
#define SQLITE_OS_WIN __OS_WIN
#define SQLITE_OS_UNIX __OS_UNIX
#define SQLITE_BYTEORDER LIBCU_BYTEORDER
#define SQLITE_BIGENDIAN LIBCU_BIGENDIAN
#define SQLITE_LITTLEENDIAN LIBCU_LITTLEENDIAN
#define SQLITE_UTF16NATIVE LIBCU_UTF16NATIVE
#define sqlite3_int64 int64_t
#define i64 int64_t
#define u64 uint64_t
#define u32 uint32_t
#define u16 uint16_t
#define i16 int16_t
#define u8 uint8_t
#define i8 int8_t
#define SQLITE_THREADSAFE LIBCU_THREADSAFE
#define <API key> <API key>
#pragma endregion
#pragma region From: sqlite.h
#define sqlite3 tagbase_t
// The SQLITE_*_BKPT macros are substitutes for the error codes with
#define SQLITE_CORRUPT_BKPT RC_CORRUPT_BKPT
#define SQLITE_MISUSE_BKPT RC_MISUSE_BKPT
#define <API key> RC_CANTOPEN_BKPT
#define SQLITE_NOMEM_BKPT RC_NOMEM_BKPT
#define <API key> RC_IOERR_NOMEM_BKPT
#define SQLITE_CORRUPT_PGNO RC_CORRUPT_PGNO
// CAPI3REF: Result Codes
#define SQLITE_OK RC_OK // Successful result
/* <API key> */
#define SQLITE_ERROR RC_ERROR // SQL error or missing database
#define SQLITE_INTERNAL RC_INTERNAL // Internal logic error in SQLite
#define SQLITE_PERM RC_PERM
#define SQLITE_ABORT RC_ABORT // Callback routine requested an abort
#define SQLITE_BUSY RC_BUSY // The database file is locked
#define SQLITE_LOCKED RC_LOCKED // A table in the database is locked
#define SQLITE_NOMEM RC_NOMEM // A malloc() failed
#define SQLITE_READONLY RC_READONLY // Attempt to write a readonly database
#define SQLITE_INTERRUPT RC_INTERRUPT // Operation terminated by sqlite3_interrupt()
#define SQLITE_IOERR RC_IOERR // Some kind of disk I/O error occurred
#define SQLITE_CORRUPT RC_CORRUPT // The database disk image is malformed
#define SQLITE_NOTFOUND RC_NOTFOUND // Unknown opcode in <API key>()
#define SQLITE_FULL RC_FULL // Insertion failed because database is full
#define SQLITE_CANTOPEN RC_CANTOPEN // Unable to open the database file
#define SQLITE_PROTOCOL RC_PROTOCOL // Database lock protocol error
#define SQLITE_EMPTY RC_EMPTY // Database is empty
#define SQLITE_SCHEMA RC_SCHEMA // The database schema changed
#define SQLITE_TOOBIG RC_TOOBIG // String or BLOB exceeds size limit
#define SQLITE_CONSTRAINT RC_CONSTRAINT // Abort due to constraint violation
#define SQLITE_MISMATCH RC_MISMATCH // Data type mismatch
#define SQLITE_MISUSE RC_MISUSE // Library used incorrectly
#define SQLITE_NOLFS RC_NOLFS // Uses OS features not supported on host
#define SQLITE_AUTH RC_AUTH // Authorization denied
#define SQLITE_FORMAT RC_FORMAT // Auxiliary database format error
#define SQLITE_RANGE RC_RANGE // 2nd parameter to sqlite3_bind out of range
#define SQLITE_NOTADB RC_NOTADB // File opened that is not a database file
#define SQLITE_NOTICE RC_NOTICE // Notifications from sqlite3_log()
#define SQLITE_WARNING RC_WARNING // Warnings from sqlite3_log()
#define SQLITE_ROW RC_ROW // sqlite3_step() has another row ready
#define SQLITE_DONE RC_DONE // sqlite3_step() has finished executing
// CAPI3REF: Extended Result Codes
#define SQLITE_IOERR_READ RC_IOERR_READ
#define <API key> RC_IOERR_SHORT_READ
#define SQLITE_IOERR_WRITE RC_IOERR_WRITE
#define SQLITE_IOERR_FSYNC RC_IOERR_FSYNC
#define <API key> RC_IOERR_DIR_FSYNC
#define <API key> RC_IOERR_TRUNCATE
#define SQLITE_IOERR_FSTAT RC_IOERR_FSTAT
#define SQLITE_IOERR_UNLOCK RC_IOERR_UNLOCK
#define SQLITE_IOERR_RDLOCK RC_IOERR_RDLOCK
#define SQLITE_IOERR_DELETE RC_IOERR_DELETE
#define <API key> RC_IOERR_BLOCKED
#define SQLITE_IOERR_NOMEM RC_IOERR_NOMEM
#define SQLITE_IOERR_ACCESS RC_IOERR_ACCESS
#define <API key> <API key>
#define SQLITE_IOERR_LOCK RC_IOERR_LOCK
#define SQLITE_IOERR_CLOSE RC_IOERR_CLOSE
#define <API key> RC_IOERR_DIR_CLOSE
#define <API key> RC_IOERR_SHMOPEN
#define <API key> RC_IOERR_SHMSIZE
#define <API key> RC_IOERR_SHMLOCK
#define SQLITE_IOERR_SHMMAP RC_IOERR_SHMMAP
#define SQLITE_IOERR_SEEK RC_IOERR_SEEK
#define <API key> <API key>
#define <API key>
#define <API key> <API key>
#define <API key>
#define SQLITE_IOERR_VNODE RC_IOERR_VNODE
#define SQLITE_IOERR_AUTH RC_IOERR_AUTH
#define <API key> <API key>
#define <API key> RC_BUSY_RECOVERY
#define <API key> RC_BUSY_SNAPSHOT
#define <API key>
#define <API key> RC_CANTOPEN_ISDIR
#define <API key> <API key>
#define <API key> <API key>
#define SQLITE_CORRUPT_VTAB RC_CORRUPT_VTAB
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> RC_READONLY_DBMOVED
#define <API key> RC_ABORT_ROLLBACK
#define <API key> RC_CONSTRAINT_CHECK
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> RC_CONSTRAINT_VTAB
#define <API key> RC_CONSTRAINT_ROWID
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define SQLITE_AUTH_USER RC_AUTH_USER
#define <API key> <API key>
// CAPI3REF: Text Encodings
#define SQLITE_UTF8 TEXTENCODE_UTF8
#define SQLITE_UTF16LE TEXTENCODE_UTF16LE
#define SQLITE_UTF16BE TEXTENCODE_UTF16BE
#define SQLITE_UTF16 TEXTENCODE_UTF16
#define SQLITE_ANY TEXTENCODE_ANY
#define <API key> <API key>
#pragma endregion
#pragma region From: sqlite.h - vsystem
// CAPI3REF: Flags For File Open Operations
#define <API key> VSYS_OPEN_READONLY
#define <API key> VSYS_OPEN_READWRITE
#define SQLITE_OPEN_CREATE VSYS_OPEN_CREATE
#define <API key> <API key>
#define <API key> VSYS_OPEN_EXCLUSIVE
#define <API key> VSYS_OPEN_AUTOPROXY
#define SQLITE_OPEN_URI VSYS_OPEN_URI
#define SQLITE_OPEN_MEMORY VSYS_OPEN_MEMORY
#define SQLITE_OPEN_MAIN_DB VSYS_OPEN_MAIN_DB
#define SQLITE_OPEN_TEMP_DB VSYS_OPEN_TEMP_DB
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define SQLITE_OPEN_NOMUTEX VSYS_OPEN_NOMUTEX
#define <API key> VSYS_OPEN_FULLMUTEX
#define <API key> <API key>
#define <API key> <API key>
#define SQLITE_OPEN_WAL VSYS_OPEN_WAL
/* Reserved */
// CAPI3REF: Device Characteristics
#define SQLITE_IOCAP_ATOMIC VSYS_IOCAP_ATOMIC
#define <API key> <API key>
#define <API key> VSYS_IOCAP_ATOMIC1K
#define <API key> VSYS_IOCAP_ATOMIC2K
#define <API key> VSYS_IOCAP_ATOMIC4K
#define <API key> VSYS_IOCAP_ATOMIC8K
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
// CAPI3REF: File Locking Levels
#define SQLITE_LOCK_NONE VSYS_LOCK_NONE
#define SQLITE_LOCK_SHARED VSYS_LOCK_SHARED
#define <API key> VSYS_LOCK_RESERVED
#define SQLITE_LOCK_PENDING VSYS_LOCK_PENDING
#define <API key> VSYS_LOCK_EXCLUSIVE
// CAPI3REF: Synchronization Type Flags
#define SQLITE_SYNC_NORMAL VSYS_SYNC_NORMAL
#define SQLITE_SYNC_FULL VSYS_SYNC_FULL
#define <API key> VSYS_SYNC_DATAONLY
// CAPI3REF: OS Interface Open File Handle
#define sqlite3_file vsysfile
//# define pMethods methods
// CAPI3REF: OS Interface File Virtual Methods Object
#define sqlite3_io_methods vsysfile_methods
# define pMethods methods
// CAPI3REF: Standard File Control Opcodes
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> VSYS_FCNTL_VFSNAME
#define <API key> <API key>
#define SQLITE_FCNTL_PRAGMA VSYS_FCNTL_PRAGMA
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define SQLITE_FCNTL_TRACE VSYS_FCNTL_TRACE
#define <API key> <API key>
#define SQLITE_FCNTL_SYNC VSYS_FCNTL_SYNC
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define SQLITE_FCNTL_ZIPVFS VSYS_FCNTL_ZIPVFS
#define SQLITE_FCNTL_RBU VSYS_FCNTL_RBU
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define SQLITE_FCNTL_PDB VSYS_FCNTL_PDB
// CAPI3REF: Mutex Handle
#define sqlite3_mutex mutex
/ CAPI3REF: Loadable Extension Thunk
//typedef struct <API key> <API key>;
// CAPI3REF: OS Interface Object
#define sqlite3_syscall_ptr vsystemcall_ptr
#define sqlite3_vfs vsystem
# define iVersion version
# define szOsFile sizeOsFile
# define mxPathname maxPathname
# define pNext next
# define zName name
# define pAppData appData
// CAPI3REF: Flags for the xAccess VFS method
#define <API key> VSYS_ACCESS_EXISTS
#define <API key> <API key>
#define SQLITE_ACCESS_READ VSYS_ACCESS_READ
// CAPI3REF: Flags for the xShmLock VFS method
#define SQLITE_SHM_UNLOCK VSYS_SHM_UNLOCK
#define SQLITE_SHM_LOCK VSYS_SHM_LOCK
#define SQLITE_SHM_SHARED VSYS_SHM_SHARED
#define <API key> VSYS_SHM_EXCLUSIVE
// CAPI3REF: Maximum xShmLock index
#define SQLITE_SHM_NLOCK VSYS_SHM_NLOCK
/ CAPI3REF: Initialize The SQLite Library
//__host_device__ RC runtimeInitialize();
//__host_device__ RC runtimeShutdown();
//__host_device__ RC vsystemInitialize();
//__host_device__ RC vsystemShutdown();
#pragma endregion
#pragma region From: bitvec.c
#define Bitvec bitvec_t
#define sqlite3BitvecCreate(iSize) bitvecNew(iSize)
#define <API key>(p, i) bitvecGet(p, i)
#define sqlite3BitvecTest(p, i) !bitvecGet(p, i)
#define sqlite3BitvecSet(p, i) bitvecSet(p. i)
#define sqlite3BitvecClear(p, i, pBuf) bitvecClear(p, i, pBuf)
#define <API key>(p) bitvecDestroy(p)
#define sqlite3BitvecSize(p) bitvecSize(p)
#define <API key>(sz, aOp) bitvecBuiltinTest(sz, aOp)
#pragma endregion
#pragma region From: fault.c
#define BenignMallocHooks BenignMallocHooks
#define <API key>(xBenignBegin, xBenignEnd) allocBenignHook(xBenignBegin, xBenignEnd)
#define <API key>() allocBenignBegin()
#define <API key>() allocBenignEnd()
#pragma endregion
#pragma region From: global.c
#define Sqlite3Config RuntimeConfig
#pragma endregion
#pragma region From: hash.c
#define Hash hash_t
#define sqlite3HashInit(pNew) hashInit(pNew)
#define sqlite3HashClear(pH) hashClear(ph)
#define sqlite3HashFind(pH, pKey) hashFind(ph, pKey)
#define sqlite3HashInsert(pH, pKey, data) hashInsert(ph, pKey, data)
#pragma endregion
#pragma region From: hwtime.h
#define sqlite3Hwtime() panic("NEED")
#pragma endregion
#pragma region From: main.c
#define sqlite3GlobalConfig _runtimeConfig
# define bCoreMutex coreMutex
#define sqlite3_version libcu_version
#define sqlite3_libversion() libcu_libversion()
#define sqlite3_sourceid() libcu_sourceid()
#define <API key>() <API key>()
#define sqlite3_threadsafe() libcu_threadsafe()
#define sqlite3IoTrace panic("NEED")
#define <API key> libcu_tempDirectory
#define <API key> libcu_dataDirectory
#define sqlite3_initialize() runtimeInitialize()
#define sqlite3_shutdown() runtimeShutdown()
#define sqlite3_config(op, ...) runtimeConfig(op, __VA_ARGS__)
#define sqlite3_db_mutex(db) panic("NEED")
#define <API key>(db) panic("NEED")
#define <API key>(db) panic("NEED")
#define sqlite3_db_config(db, op, ...) panic("NEED")
#define <API key>(db) panic("NEED")
#define <API key>(db, iRowid) panic("NEED")
#define sqlite3_changes(db) panic("NEED")
#define <API key>(db) panic("NEED")
#define <API key>(db) panic("NEED")
#define sqlite3_close(db) panic("NEED")
#define sqlite3_close_v2(db) panic("NEED")
#define <API key>(db) panic("NEED")
#define sqlite3RollbackAll(db, tripCode) panic("NEED")
#define sqlite3ErrName(rc) libcuErrName(rc)
#define sqlite3ErrStr(rc) libcuErrStr(rc)
#define <API key>(p) panic("NEED")
#define <API key>(db, xBusy, pArg) panic("NEED")
#define <API key>(db, nOps, xProgress, pArg) panic("NEED")
#define <API key>(db, ms) panic("NEED")
#define sqlite3_interrupt(db) panic("NEED")
#define sqlite3CreateFunc(db, zFunctionName, nArg, enc, pUserData, xSFunc, xStep, xFinal, pDestructor) panic("NEED")
#define <API key>(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal) panic("NEED")
#define <API key>(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, xDestroy) panic("NEED")
#define <API key>(db, zName, nArg) panic("NEED")
#define sqlite3_trace(db, xTrace, pArg) panic("NEED")
#define sqlite3_profile(db, xProfile, pArg) panic("NEED")
#define sqlite3_commit_hook(db, xCallback, pArg) panic("NEED")
#define sqlite3_update_hook(db, xCallback, pArg) panic("NEED")
#define <API key>(db, xCallback, pArg) panic("NEED")
#define <API key>(db,xCallback, pArg) panic("NEED")
#define <API key>(pClientData, db, zDb, nFrame) panic("NEED")
#define <API key>(db, nFrame) panic("NEED")
#define sqlite3_wal_hook(db, xCallback, pArg) panic("NEED")
#define <API key>(db, zDb, eMode, pnLog, pnCkpt) panic("NEED")
#define <API key>(db, zDb) panic("NEED")
#define sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt) panic("NEED")
#define sqlite3TempInMemory(db) panic("NEED")
#define sqlite3_errmsg(db) panic("NEED")
#define sqlite3_errmsg16(db) panic("NEED")
#define sqlite3_errcode(db) panic("NEED")
#define <API key>(db) panic("NEED")
#define <API key>(db) panic("NEED")
#define sqlite3_errstr(rc) panic("NEED")
#define sqlite3_limit(db, limitId, newLimit) panic("NEED")
#define sqlite3ParseUri(zDefaultVfs, zUri, pFlags, ppVfs, pzFile, pzErrMsg) panic("NEED")
#define sqlite3_open(zFilename, ppDb) panic("NEED")
#define sqlite3_open16(zFilename, ppDb) panic("NEED")
#define <API key>(db, zName, enc, pCtx, xCompare) panic("NEED")
#define <API key>(db, zName, enc, pCtx, xCompare, xDel) panic("NEED")
#define <API key>(db, zName, enc, pCtx, xCompare) panic("NEED")
#define <API key>(db, pCollNeededArg, xCollNeeded) panic("NEED")
#define <API key>(db, pCollNeededArg, xCollNeeded16) panic("NEED")
#define <API key>() panic("NEED")
#define <API key>(db) panic("NEED")
#define sqlite3CorruptError(lineno) libcuCorruptError(lineno)
#define sqlite3MisuseError(lineno) libcuMisuseError(lineno)
#define <API key>(lineno) libcuCantopenError(lineno)
#define <API key>(lineno, pgno) libcuCorruptError(lineno, pgno)
#define sqlite3NomemError(lineno) libcuNomemError(lineno)
#define <API key>(lineno) <API key>(lineno)
#define <API key>() panic("NEED")
#define <API key>(db, zDbName, zTableName, zColumnName, pzDataType, pzCollSeq, pNotNull, pPrimaryKey, pAutoinc) panic("NEED")
#define sqlite3_sleep(ms) panic("NEED")
#define <API key>(db, onoff) panic("NEED")
#define <API key>(db, zDbName, op, pArg) panic("NEED")
#define <API key>(op, ...) panic("NEED")
#define <API key>(zFilename, zParam) convert_uriparam(zFilename, zParam)
#define sqlite3_uri_boolean(zFilename, zParam, bDflt) convert_uritob(zFilename, zParam, bDflt)
#define sqlite3_uri_int64(zFilename, zParam, bDflt) convert_uritoi64(zFilename, zParam, bDflt)
#define <API key>(db, zDbName) panic("NEED")
#define sqlite3_db_filename(db, zDbName) panic("NEED")
#define sqlite3_db_readonly(db, zDbName) panic("NEED")
#define <API key>(db, zDb, ppSnapshot) panic("NEED")
#define <API key>(db, zDb, pSnapshot) panic("NEED")
#define <API key>(db, zDb) panic("NEED")
#define <API key>(pSnapshot) panic("NEED")
#define <API key>(zOptName) <API key>(zOptName)
#define <API key>(N) <API key>(N)
#pragma endregion
#pragma region From: malloc.c
#define <API key>(X, Y) memdbg_settype(X, Y)
#define <API key>(X, Y) memdbg_hastype(X, Y)
#define <API key>(X, Y) memdbg_nottype(X, Y)
#define <API key>(n) alloc_releasememory(n)
#define sqlite3MallocMutex() allocMutex()
#define <API key>(xCallback, pArg, iThreshold) panic("DEPRECATED")
#define <API key>(n) <API key>()
#define <API key>(n) alloc_softheaplimit()
#define sqlite3MallocInit() allocInitialize()
#define <API key>() allocHeapNearlyFull()
#define sqlite3MallocEnd() allocShutdown()
#define sqlite3_memory_used() alloc_memoryused()
#define <API key>(resetFlag) <API key>(resetFlag)
#define sqlite3Malloc(n) alloc(n)
#define sqlite3_malloc(n) alloc32(n)
#define sqlite3_malloc64(n) alloc64(n)
#define sqlite3MallocSize(p) allocSize(p)
#define sqlite3DbMallocSize(db, p) tagallocSize(db, p)
#define sqlite3_msize(p) alloc_msize(p)
#define sqlite3_free(p) mfree(p)
#define sqlite3DbFreeNN(db, p) tagfreeNN(db, p)
#define sqlite3DbFree(db, p) tagfree(db, p)
#define sqlite3Realloc(pOld, nBytes) allocRealloc(pOld, nBytes)
#define sqlite3_realloc(pOld, n) alloc_realloc32(pOld, n)
#define sqlite3_realloc64(pOld, n) alloc_realloc64(pOld, n)
#define sqlite3MallocZero(n) allocZero(n)
#define sqlite3DbMallocZero(db, n) tagallocZero(db, n)
#define sqlite3DbMallocRaw(db, n) tagallocRaw(db, n)
#define <API key>(db, n) tagallocRawNN(db, n)
#define sqlite3DbRealloc(db, p, n) tagrealloc(db, p, n)
#define <API key>(db, p, n) tagreallocOrFree(db, p, n)
#define sqlite3DbStrDup(db, z) tagstrdup(db, z)
#define sqlite3DbStrNDup(db, z, n) tagstrndup(db, z, n)
#define sqlite3SetString(pz, db, zNew) tagstrset(pz, db, zNew)
#define sqlite3OomFault(db) tagOomFault(db)
#define sqlite3OomClear(db) tagOomClear(db)
#define sqlite3ApiExit(db, rc) tagApiExit(db, rc)
#pragma endregion
#pragma region From: mem0.c, mem1.c
#define <API key>() <API key>()
#pragma endregion
#pragma region From: memjournal.c
//#define sqlite3_file memfile_t
#define sqlite3JournalOpen(pVfs, zName, pJfd, flags, nSpill)
#define <API key>(pJfd) memfileOpen
#define <API key>(pJfd)
#define <API key>(p)
#define sqlite3JournalSize(pVfs)
#pragma endregion
#pragma region From: mutex.c
#define <API key> systemMemoryBarrier
// CAPI3REF: Mutex Types
#define SQLITE_MUTEX_FAST MUTEX_FAST
#define <API key> MUTEX_RECURSIVE
#define <API key> MUTEX_STATIC_MASTER
#define <API key> MUTEX_STATIC_MEM
#define <API key> MUTEX_STATIC_MEM2
#define <API key> MUTEX_STATIC_OPEN
#define <API key> MUTEX_STATIC_PRNG
#define <API key> MUTEX_STATIC_LRU
#define <API key> MUTEX_STATIC_LRU2
#define <API key> MUTEX_STATIC_PMEM
#define <API key> MUTEX_STATIC_APP1
#define <API key> MUTEX_STATIC_APP2
#define <API key> MUTEX_STATIC_APP3
#define <API key> MUTEX_STATIC_VFS1
#define <API key> MUTEX_STATIC_VFS2
#define <API key> MUTEX_STATIC_VFS3
#define sqlite3_mutex mutex
#define sqlite3MutexInit() mutexInitialize()
#define sqlite3MutexEnd() mutexShutdown()
#define sqlite3_mutex_alloc(id) mutex_alloc(id)
#define sqlite3MutexAlloc(id) mutexAlloc(id)
#define sqlite3_mutex_free(p) mutex_free(p)
#define sqlite3_mutex_enter(p) mutex_enter(p)
#define sqlite3_mutex_try(p) mutex_tryenter(p)
#define sqlite3_mutex_leave(p) mutex_leave(p)
#define sqlite3_mutex_held(p) mutex_held(p)
#define <API key>(p) mutex_notheld(p)
#pragma endregion
#pragma region From: mutex_noop.c, mutex_unix.c, mutex_w32.c
#define sqlite3DefaultMutex() <API key>()
#pragma endregion
#pragma region From: notify.c
#define <API key>(db, xNotify, pArg) notify_unlock(db, xNotify, pArg)
#define <API key>(db, pBlocker) <API key>(db, pBlocker)
#define <API key>(db) <API key>(db)
#define <API key>(db) <API key>(db)
#pragma endregion
#pragma region From: os.c
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> libcu_io_error_hit
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define sqlite3_diskfull libcu_diskfull
#define <API key> <API key>
#define <API key> <API key>
#define sqlite3OsClose(pId) vsys_close(pId)
#define sqlite3OsRead(id, pBuf, amt, offset) vsys_read(id, pBuf, amt, offset)
#define sqlite3OsWrite(id, pBuf, amt, offset) vsys_write(id, pBuf, amt, offset)
#define sqlite3OsTruncate(id, size) vsys_truncate(id, size)
#define sqlite3OsSync(id, flags) vsys_sync(id, flags)
#define sqlite3OsFileSize(id, pSize) vsys_fileSize(id, pSize)
#define sqlite3OsLock(id, lockType) vsys_lock(id, lockType)
#define sqlite3OsUnlock(id, lockType) vsys_unlock(id, lockType)
#define <API key>(id, pResOut) <API key>(id, pResOut)
#define <API key>(id, op, pArg) vsys_fileControl(id, op, pArg)
#define <API key>(id, op, pArg) <API key>(id, op, pArg)
#define sqlite3OsSectorSize(id) vsys_sectorSize(id)
#define <API key>(id) <API key>(id)
#define sqlite3OsShmLock(id, offset, n, flags) vsys_shmLock(id, offset, n, flags)
#define sqlite3OsShmBarrier(id) vsys_shmBarrier(id)
#define sqlite3OsShmUnmap(id, deleteFlag) vsys_shmUnmap(id, deleteFlag)
#define sqlite3OsShmMap(id, iPage, pgsz, bExtend, pp) vsys_shmMap(id, iPage, pgsz, bExtend, pp)
#define sqlite3OsFetch(id, iOff, iAmt, pp) vsys_fetch(id, iOff, iAmt, pp)
#define sqlite3OsUnfetch(id, iOff, p) vsys_unfetch(id, iOff, p)
#define sqlite3OsOpen(pVfs, zPath, pFile, flags, pFlagsOut) vsys_open(pVfs, zPath, pFile, flags, pFlagsOut)
#define sqlite3OsDelete(pVfs, zPath, dirSync) vsys_delete(pVfs, zPath, dirSync)
#define sqlite3OsAccess(pVfs, zPath, flags, pResOut) vsys_access(pVfs, zPath, flags, pResOut)
#define <API key>(pVfs, zPath, nPathOut, zPathOut) vsys_fullPathname(pVfs, zPath, nPathOut, zPathOut)
#define sqlite3OsDlOpen(pVfs, zPath) vsys_dlOpen(pVfs, zPath)
#define sqlite3OsDlError(pVfs, nByte, zBufOut) vsys_dlError(pVfs, nByte, zBufOut)
#define sqlite3OsDlSym(pVfs, pHdle, zSym) vsys_dlSym(pVfs, pHdle, zSym)
#define sqlite3OsDlClose(pVfs, pHandle) vsys_dlClose(pVfs, pHandle)
#define sqlite3OsRandomness(pVfs, nByte, zBufOut) vsys_randomness(pVfs, nByte, zBufOut)
#define sqlite3OsSleep(pVfs, nMicro) vsys_sleep(pVfs, nMicro)
#define <API key>(pVfs) vsys_getLastError(pVfs)
#define <API key>(pVfs, pTimeOut) <API key>(pVfs, pTimeOut)
#define sqlite3OsOpenMalloc(pVfs, zFile, ppFile, flags, pOutFlags) vsys_openMalloc(pVfs, zFile, ppFile, flags, pOutFlags)
#define sqlite3OsCloseFree(pFile) vsys_closeAndFree(pFile)
#define sqlite3OsInit() vsystemFakeInit()
#define sqlite3_vfs_find(zVfs) vsystemFind(zVfs)
#define <API key>(pVfs, makeDflt) vsystemRegister(pVfs, makeDflt)
#define <API key>(pVfs) vsystemUnregister(pVfs)
#pragma endregion
#pragma region From: pcache.c
//#define PgHdr PgHdr
//# define pDirty dirty
//# define pData data
//# define pMethods methods
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key>(pPg) pcachePageSanity(pPg)
#define <API key>() pcacheInitialize()
#define <API key>() pcacheShutdown()
#define sqlite3PcacheSize() pcacheSize()
#define sqlite3PcacheOpen(szPage, szExtra, bPurgeable, xStress, pStress, p) pcacheOpen(szPage, szExtra, bPurgeable, xStress, pStress, p)
#define <API key>(pCache, szPage) pcacheSetPageSize(pCache, szPage)
#define sqlite3PcacheFetch(pCache, pgno, createFlag) pcacheFetch(pCache, pgno, createFlag)
#define <API key>(pCache, pgno, ppPage) pcacheFetchStress(pCache, pgno, ppPage)
#define <API key>(pCache, pgno, pPage) pcacheFetchFinish(pCache, pgno, pPage)
#define <API key>(p) pcacheRelease(p)
#define sqlite3PcacheRef(p) pcacheRef(p)
#define sqlite3PcacheDrop(p) pcacheDrop(p)
#define <API key>(p) pcacheMakeDirty(p)
#define <API key>(p) pcacheMakeClean(p)
#define <API key>(pCache) pcacheCleanAll(pCache)
#define <API key>(pCache) pcacheClearWritable(pCache)
#define <API key>(pCache) <API key>(pCache)
#define sqlite3PcacheMove(p, newPgno) pcacheMove(p, newPgno)
#define <API key>(pCache, pgno) pcacheTruncate(pCache, pgno)
#define sqlite3PcacheClose(pCache) pcacheClose(pCache)
#define sqlite3PcacheClear(pCache) pcacheClear(pCache)
#define <API key>(pCache) pcacheDirtyList(pCache)
#define <API key>(pCache) pcacheRefCount(pCache)
#define <API key>(p) pcachePageRefcount(p)
#define <API key>(pCache) pcachePagecount(pCache)
#define <API key>(pCache) pcacheGetCachesize(pCache)
#define <API key>(pCache, mxPage) pcacheSetCachesize(pCache, mxPage)
#define <API key>(p, mxPage) pcacheSetSpillsize(p, mxPage)
#define sqlite3PcacheShrink(pCache) pcacheShrink(pCache)
#define <API key>() pcacheHeaderSize()
#define <API key>(pCache) pcachePercentDirty(pCache)
#define <API key>(pCache, xIter) pcacheIterateDirty(pCache, xIter)
#pragma endregion
#pragma region From: pcache1.c
#define <API key>(pBuf, sz, n) pcacheBufferSetup(pBuf, sz, n)
#define sqlite3PageMalloc(sz) sqlite3PageMalloc(sz)
#define sqlite3PageFree(p) sqlite3PageFree(p)
#define <API key>() <API key>()
#define <API key>() pcache1HeaderSize()
#define sqlite3Pcache1Mutex() pcache1Mutex()
#define <API key>(nReq) pcacheReleaseMemory(nReq)
#define sqlite3PcacheStats(pnCurrent, pnMax, pnMin, pnRecyclable) pcacheStats(pnCurrent, pnMax, pnMin, pnRecyclable)
#pragma endregion
#pragma region From: pragma.c
#define sqlite3GetBoolean(z, dflt) convert_atob(z, dflt)
#pragma endregion
#pragma region From: printf.c
#define StrAccum strbuf_t
#define sqlite3VXPrintf(pAccum, fmt, ap) strbldAppendFormatv(pAccum, fmt, ap)
#define sqlite3AppendChar(p, N, c) strbldAppendChar(p, N, c)
#define <API key>(p, z, N) strbldAppend(p, z, N)
#define <API key>(p, z) strbldAppendAll(p, z)
#define <API key>(p) strbldToString(p)
#define <API key>(p) strbldReset(p)
#define sqlite3StrAccumInit(p, db, zBase, n, mx) strbldInit(p, db, zBase, n, mx)
#define sqlite3VMPrintf(db, zFormat, ap) vmtagprintf(db, zFormat, ap)
#define sqlite3MPrintf(db, zFormat, ...) mtagprintf(db, zFormat, __VA_ARGS__)
#define sqlite3_vmprintf(zFormat, ap) vmprintf(zFormat, ap)
#define sqlite3_mprintf(zFormat, ...) mprintf(zFormat, __VA_ARGS__)
#define sqlite3_vsnprintf(n, zBuf, zFormat, ap) vmsnprintf(zBuf, n, zFormat, ap)
#define sqlite3_snprintf(n, zBuf, zFormat, ...) msnprintf(zBuf, n, zFormat, __VA_ARGS__)
#define sqlite3_log(iErrCode, zFormat, ...) _log(iErrCode, zFormat, __VA_ARGS__)
#define sqlite3DebugPrintf(zFormat, ...) _debug(zFormat, __VA_ARGS__)
#define sqlite3XPrintf(p, zFormat, ...) strbldAppendFormat(p, zFormat, __VA_ARGS__)
#pragma endregion
#pragma region From: random.c
#define sqlite3_randomness(N, pBuf) randomness_(N, pBuf)
#define <API key>() randomness_save()
#define <API key>() randomness_restore()
#pragma endregion
#pragma region From: status.c
#define sqlite3StatusValue(op) status_now(op)
#define sqlite3StatusUp(op, N) status_inc(op, N)
#define sqlite3StatusDown(op, N) status_dec(op, N)
#define <API key>(op, X) status_max(op, X)
#define sqlite3_status64(op, pCurrent, pHighwater, resetFlag) status64(op, pCurrent, pHighwater, resetFlag)
#define sqlite3_status(op, pCurrent, pHighwater, resetFlag) status(op, pCurrent, pHighwater, resetFlag)
#define <API key>(db, pHighwater) taglookasideUsed(db, pHighwater)
#define sqlite3_db_status(db, op, pCurrent, pHighwater, resetFlag) tagstatus(db, op, pCurrent, pHighwater, resetFlag)
#pragma endregion
#pragma region From: threads.c
#define SQLiteThread thread_t
#define sqlite3ThreadCreate(ppThread, xTask, pIn) thread_create(ppThread, xTask, pIn)
#define sqlite3ThreadJoin(p, ppOut) thread_join(p, ppOut)
#pragma endregion
#pragma region From: utf.c
#define sqlite3Utf8Read(pz) utf8read(pz)
#define <API key>(pMem, desiredEnc) panic("NEED")
#define <API key>(pMem) panic("NEED")
#define sqlite3Utf8CharLen(zIn, nByte) utf8charlen(zIn, nByte)
#define sqlite3Utf8To8(zIn) utf8to8(zIn)
#define sqlite3Utf16to8(db, z, nByte, enc) panic("NEED")
#define sqlite3Utf16ByteLen(zIn, nChar) utf16bytelen(zIn, nChar)
#define sqlite3UtfSelfTest() utfselftest()
#pragma endregion
#pragma region From: util.c
#define sqlite3Coverage(x) __coverage(x)
#define sqlite3FaultSim(iTest) _faultSim(iTest)
#define sqlite3IsNaN(x) math_isNaN(x)
#define sqlite3Strlen30(z) ((int)strlen(z))
#define sqlite3ColumnType(pCol, zDflt) panic("NEED")
#define sqlite3Error(db, err_code) tagError(db, err_code)
#define sqlite3SystemError(db, rc) tagSystemError(db, rc)
#define sqlite3ErrorWithMsg(db, err_code, zFormat, ...) tagErrorWithMsg(db, err_code, zFormat, __VA_ARGS__)
#define sqlite3ErrorMsg(pParse, zFormat, ...)
#define sqlite3Dequote(z) dequote(z)
#define sqlite3TokenInit(p, z) panic("NEED")
#define sqlite3_stricmp(zLeft, zRight) _stricmp(zLeft, zRight)
#define sqlite3StrICmp(zLeft, zRight) _stricmp(zLeft, zRight)
#define sqlite3_strnicmp(zLeft, zRight, N) strnicmp(zLeft, zRight, N)
#define sqlite3AtoF(z, pResult, length, enc) convert_atofe(z, pResult, length, enc)
#define sqlite3Atoi64(zNum, pNum, length, enc) convert_atoi64e(zNum, pNum, length, enc)
#define <API key>(z, pOut) convert_axtoi64e(z, pOut)
#define sqlite3GetInt32(zNum, pValue) convert_atoie(zNum, pValue)
#define sqlite3Atoi(z) convert_atoi(z)
#define sqlite3PutVarint(p, v) convert_putvarint(p, v)
#define sqlite3GetVarint(p, v) convert_getvarint(p, v)
#define sqlite3GetVarint32(p, v) convert_getvarint32(p, v)
#define sqlite3VarintLen(v) <API key>(v)
#define sqlite3Get4byte(p) convert_get4(p)
#define sqlite3Put4byte(p, v) convert_put4(p, v)
#define sqlite3HexToInt(h) convert_xtoi(h)
#define sqlite3HexToBlob(db, z, n) <API key>(db, z, n)
#define <API key>(db) tagSafetyCheckOk(db)
#define <API key>(db) <API key>(db)
#define sqlite3AddInt64(pA, iB) math_add64(pA, iB)
#define sqlite3SubInt64(pA, iB) math_sub64(pA, iB)
#define sqlite3MulInt64(pA, iB) math_mul64(pA, iB)
#define sqlite3AbsInt32(x) math_abs32(x)
#define sqlite3FileSuffix3(zBaseFilename, z) util_fileSuffix3(zBaseFilename, z)
#define sqlite3LogEstAdd(a, b) math_addLogest(a, b)
#define sqlite3LogEst(x) math_logest(x)
#define <API key>(x) <API key>(x)
#define sqlite3LogEstToInt(x) panic("NEED")
#define sqlite3VListAdd(db, pIn, zName, nName, iVal) util_vlistadd(db, pIn, zName, nName, iVal)
#define <API key>(pIn, iVal) util_vlistIdToName(pIn, iVal)
#define <API key>(pIn, zName, nName) util_vlistNameToId(pIn, zName, nName)
#pragma endregion
// parent
#pragma region From: os_unix.c, os_win.c
#pragma endregion
#pragma region From: pager.c
#define sqlite3SectorSize(pFile) sqlite3SectorSize(pFile)
#pragma endregion
#pragma region From: wal.c
#pragma endregion
#endif /* SQLITE_LIBCU_H */ |
import * as React from 'react';
import classNames from 'classnames';
import { ownerDocument, activeElement, contains, getContainer, on } from 'dom-lib';
import canUseDom from 'dom-lib/lib/query/canUseDOM';
import Portal from '../Portal';
import ModalManager from './ModalManager';
import Fade from '../Animation/Fade';
import { ModalProps } from './Modal.d';
import getDOMNode from '../utils/getDOMNode';
import mergeRefs from '../utils/mergeRefs';
class RefHolder extends React.Component<any> {
render() {
return this.props.children || null;
}
}
interface BaseModalProps extends ModalProps {
container?: HTMLElement | (() => HTMLElement);
onRendered?: Function;
transition: React.ElementType;
onEscapeKeyUp?: React.<API key>;
onBackdropClick?: React.MouseEventHandler;
containerClassName?: string;
<API key>?: number;
<API key>?: number;
role?: string;
animationProps?: any;
}
interface BaseModalState {
exited?: boolean;
}
const modalManager = new ModalManager();
class BaseModal extends React.Component<BaseModalProps, BaseModalState> {
static manager = modalManager;
static defaultProps = {
backdrop: true,
keyboard: true,
autoFocus: true,
enforceFocus: true
};
mountNode = null;
modalNodeRef = null;
backdropRef = null;
dialogRef: React.RefObject<any> = null;
lastFocus = null;
<API key> = null;
onFocusinListener = null;
constructor(props: BaseModalProps) {
super(props);
this.state = { exited: !props.show };
this.backdropRef = React.createRef();
this.modalNodeRef = React.createRef();
this.dialogRef = React.createRef();
}
componentDidMount() {
if (this.props.show) {
this.onShow();
}
}
static <API key>(nextProps: BaseModalProps) {
if (nextProps.show) {
return { exited: false };
} else if (!nextProps.transition) {
// Otherwise let handleHidden take care of marking exited.
return { exited: true };
}
return null;
}
<API key>(prevProps: BaseModalProps) {
if (this.props.show && !prevProps.show) {
this.checkForFocus();
}
return null;
}
componentDidUpdate(prevProps: BaseModalProps) {
const { transition } = this.props;
if (prevProps.show && !this.props.show && !transition) {
// Otherwise handleHidden will call this.
this.onHide();
} else if (!prevProps.show && this.props.show) {
this.onShow();
}
}
<API key>() {
const { show, transition } = this.props;
if (show || (transition && !this.state.exited)) {
this.onHide();
}
}
onShow() {
const doc = ownerDocument(this);
const container = getContainer(this.props.container, doc.body);
const { containerClassName } = this.props;
modalManager.add(this, container, containerClassName);
this.<API key> = on(doc, 'keyup', this.handleDocumentKeyUp);
this.onFocusinListener = on(doc, 'focus', this.enforceFocus);
this.props.onShow?.();
}
onHide() {
modalManager.remove(this);
this.<API key>?.off();
this.onFocusinListener?.off();
this.restoreLastFocus();
}
getDialogElement(): any {
return getDOMNode(this.dialogRef.current);
}
setMountNodeRef = (ref: any) => {
this.mountNode = ref?.getMountNode?.();
};
isTopModal() {
return modalManager.isTopModal(this);
}
handleHidden = (args: any) => {
this.setState({ exited: true });
this.onHide();
this.props.onExited?.(args);
};
handleBackdropClick = (event: React.MouseEvent) => {
if (event.target !== event.currentTarget) {
return;
}
const { onBackdropClick, backdrop, onHide } = this.props;
onBackdropClick?.(event);
backdrop && onHide?.(event);
};
handleDocumentKeyUp = (event: React.KeyboardEvent) => {
const { keyboard, onHide, onEscapeKeyUp } = this.props;
if (keyboard && event.keyCode === 27 && this.isTopModal()) {
onEscapeKeyUp?.(event);
onHide?.(event);
}
};
checkForFocus() {
if (canUseDom) {
this.lastFocus = activeElement();
}
}
restoreLastFocus() {
// Support: <=IE11 doesn't support `focus()` on svg elements
if (this.lastFocus) {
this.lastFocus.focus?.();
this.lastFocus = null;
}
}
enforceFocus = () => {
const { enforceFocus } = this.props;
if (!enforceFocus || !this.isTopModal()) {
return;
}
const active = activeElement(ownerDocument(this));
const modal = this.getDialogElement();
if (modal && modal !== active && !contains(modal, active)) {
modal.focus();
}
};
renderBackdrop() {
const {
transition,
backdrop,
<API key>,
backdropStyle,
backdropClassName
} = this.props;
const backdropPorps = {
style: backdropStyle,
onClick: backdrop === true ? this.handleBackdropClick : undefined
};
if (transition) {
return (
<Fade transitionAppear in={this.props.show} timeout={<API key>}>
{(props, ref) => {
const { className, ...rest } = props;
return (
<div
{...rest}
{...backdropPorps}
className={classNames(backdropClassName, className)}
ref={mergeRefs(this.backdropRef, ref)}
/>
);
}}
</Fade>
);
}
return <div ref={this.backdropRef} className={backdropClassName} {...backdropPorps} />;
}
render() {
const {
children,
transition: Transition,
backdrop,
<API key>,
style,
className,
container,
animationProps,
onExit,
onExiting,
onEnter,
onEntering,
onEntered,
rest
} = this.props;
const show = !!rest.show;
const mountModal = show || (Transition && !this.state.exited);
if (!mountModal) {
return null;
}
let dialog = children;
if (Transition) {
dialog = (
<Transition
{...animationProps}
transitionAppear
unmountOnExit
in={show}
timeout={<API key>}
onExit={onExit}
onExiting={onExiting}
onExited={this.handleHidden}
onEnter={onEnter}
onEntering={onEntering}
onEntered={onEntered}
>
{dialog}
</Transition>
);
}
return (
<Portal ref={this.setMountNodeRef} container={container}>
<div
ref={this.modalNodeRef}
role={rest.role || 'dialog'}
style={style}
className={className}
>
{backdrop && this.renderBackdrop()}
<RefHolder ref={this.dialogRef}>{dialog}</RefHolder>
</div>
</Portal>
);
}
}
export default BaseModal; |
import requests
import json
cart_url = 'http://127.0.0.1:8000/api/cart/'
def create_cart():
# create cart
cart_r = requests.get(cart_url)
# get cart token
cart_token = cart_r.json()["token"]
return cart_token
def do_api_test(email=None, user_auth=None):
cart_token = create_cart()
# add items to cart
new_cart_url = cart_url + "?token=" + cart_token + "&item=10&qty=3"
new_cart_r = requests.get(new_cart_url)
#print new_cart_r.text
if email:
data = {
"email": email
}
u_c_r = requests.post(user_checkout_url, data=data)
user_checkout_token = u_c_r.json().get("user_checkout_token")
#print user_checkout_token
addresses = "http://127.0.0.1:8000/api/user/address/?checkout_token=" + user_checkout_token
addresses_r = requests.get(addresses)
addresses_r_data = addresses_r.json()
if addresses_r_data["count"] >= 2:
b_id = addresses_r_data["results"][0]["id"]
s_id = addresses_r_data["results"][1]["id"]
else:
addresses_create = "http://127.0.0.1:8000/api/user/address/create/"
user_id = 11
data = {
"user": user_id,
"type": "billing",
"street": "12423 Test",
"city": "Newport Beach",
"zipcode": 92304,
}
addresses_create_r = requests.post(addresses_create, data=data)
b_id = addresses_create_r.json().get("id")
data = {
"user": user_id,
"type": "shipping",
"street": "12423 Test",
"city": "Newport Beach",
"zipcode": 92304,
}
<API key> = requests.post(addresses_create, data=data)
s_id = <API key>.json().get("id")
"""
do checkout
"""
checkout_url = "http://127.0.0.1:8000/api/checkout/"
data = {
"billing_address": b_id,
"shipping_address": s_id,
"cart_token": cart_token,
"checkout_<API key>
}
#print data
order = requests.post(checkout_url, data=data)
#print order.headers
print order.text
do_api_test(email='abc1234@gmail.com')
# login_url = base_url + "auth/token/"
# products_url = base_url + "products/"
# refresh_url = login_url + "refresh/"
# cart_url = base_url + "cart/"
# #requests.get
# #requests.post(login_url, data=None, headers=None, params=None)
# data = {
# "username": "jmitchel3",
# "password": "123"
# login_r = requests.post(login_url, data=data)
# login_r.text
# json_data = login_r.json()
# import json
# print(json.dumps(json_data, indent=2))
# token = json_data["token"]
# print token
# headers = {
# "Content-Type": "application/json",
# "Authorization": "JWT %s" %(token),
# p_r = requests.get(products_url, headers=headers)
# print p_r.text
# print(json.dumps(p_r.json(), indent=2))
# #Refresh URL TOKEN
# data = {
# "token": token
# refresh_r = requests.post(refresh_url, data=data)
# print refresh_r.json()
# token = refresh_r.json()["token"]
# cart_r = requests.get(cart_url)
# cart_token = cart_r.json()["token"]
# new_cart_url = cart_url + "?token=" + cart_token + "&item=10&qty=3&delete=True"
# new_cart_r = requests.get(new_cart_url)
# print new_cart_r.json() |
def printFileContents(myFile):
print(open(myFile).read().splitlines())
def writeFileContents(myFile, somethingToWrite):
f = open(myFile,'a')
f.write(somethingToWrite +'\n') # python will convert \n to os.linesep
f.close() # you can omit in most cases as the destructor will call if
printFileContents("alive.txt")
writeFileContents("writer.txt", "All for one!")
#Consider for Example
#def writeToDatabase():
# import pyodbc
# cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
# cursor = cnxn.cursor()
# cursor.execute("select user_id, user_name from users")
# rows = cursor.fetchall()
# for row in rows:
# print row.user_id, row.user_name |
# Pwee PHP Extension
Pwee is a PHP extension that gives web developers the ability to expand the PHP runtime
environment. Developers can use XML to define and add custom constants and variables that
are accessible to each script. The lifetime and scope of constants and variables can be
controlled individually and the scope of variables can be expanded so they are persistent
across multiple requests to the same script executor.
Requirements
* [PHP 4.1 or later](http:
Certain features are not available under Windows.
Installation
Download and extract the Pwee tarball to the PHP extension directory. PHP extensions are
located in the /ext subdirectory of the PHP installation. These instructions assume you
installed PHP in `/usr/local/src`.
Static Linking
For the best performance impact it makes sense to link Pwee directly into PHP.
% tar xvfz pwee.tar.gz -C /usr/local/src/php/ext
% cd /usr/local/src/php
% ./buildconf
% ./configure --with-pwee [other options]
Shared Library (DSO)
% tar xvfz pwee.tar.gz -C /usr/local/src/pwee
% cd /usr/local/src/pwee
% phpize
% ./configure --with-pwee=shared [other options]
% make
% make install
Shared Library
% tar xvfz pwee.tar.gz -C /usr/local/src/php/ext
% cd /usr/local/src/php
% ./buildconf
% ./configure --with-pwee=shared [other options]
## Configuration
After you install the package and build PHP all that's left is to create an XML environment
definition and add `pwee.sysconfpath` or `pwee.userconfpath` settings to your php.ini.
Virtual Hosts
If you want to define the environment based on the VirtualHost you can modify your
httpd.conf and add a php_value option for the directory that is the DocumentRoot
for the VirtualHost.
<VirtualHost _default_:80>
ServerName www.domain.com
DocumentRoot /var/www/www.domain.com
<Directory /var/www/www.domain.com>
php_value pwee.userconfpath "/var/www/www.domain.com/pwee.conf.xml"
</Directory>
</VirtualHost>
If you want to define the environment based on a particular directory you can add a php_value
option to a .htaccess file. In order for this to work the AllowOverride property for the
<Directory> that contains the .htaccess must include the value Options or All.
php_value pwee.userconfpath "/var/www/www.domain.com/pwee.conf.xml"
It is more efficient to define the Pwee configuration in the VirtualHost definition
in httpd.conf than using .htaccess. Either one is suitable and Pwee will cache the
environment definition internally for efficiency.
php.ini Settings
There are a number of different settings that control how Pwee works.
* `pwee.sysconfpath` - Path to a system wide XML environment definition file.
This value can only be set in php.ini. There is no default value.
* `pwee.userconfpath` - Path to a user defined XML environment definition file.
This value should be set on a per directory basis in either httpd.conf or .htaccess.
There is no default value. Once a user environment is loaded it is cached for
efficiency. If you modify the XML definition and want Pwee to reload it you need
to append a serial number to the end of the path. The serial number is specified
following a colon. For example conf.xml:1 would specify serial number 1. Any
change in this part of the path will cause Pwee to reload the definition.
Only one userconfpath is active at any given time.
* `pwee.userconf_allow` - Determines if Pwee allows user environments to be defined
using pwee.userconfpath. The default is Yes. This value can only be set in php.ini.
* `pwee.<API key>` - Determines if Pwee registers constants for network
information such as server IP addresses. The default is Yes.
* `pwee.net_constant_prefix` - Prefix to use for network constants. Only applicable
when pwee.<API key> is Yes. The default prefix is 'SERVER'.
* `pwee.<API key>` - Determines if Pwee registers constants that uniquely
identify the executor and request. The default is Yes.
* `pwee.exposeinfo` - Determines if constants and variables are displayed by phpinfo().
The default is Yes.
Default Environment Constants
Besides the constants and variables defined by XML environment definitions,
Pwee defines some constants itself.
* `EXECUTOR_UID` - Each script executor is assigned a unique identifier.
The identifier is 36 characters long and has the format <API key>.
The lifetime of an executor depends on how you invoke PHP. For example, if you
are using Apache with mod_php each Apache process is an executor.
* `<API key>` - Each script execution (request) is assigned a unique identifier.
The identifier is 41 characters long and has the format <API key>.
* `SERVER_IFADDR_LO` - Defines the IP address of the loopback network device.
Almost always 127.0.0.1.
* `SERVER_IFADDR_ETH[0...]` - Defines the IP address of other network devices.
One constant will be created for each device. There is almost always a
SERVER_IFADDR_ETH0 constant.
* `SERVER_IFADDR` - Defines the IP address of the first network device that is
not the loopback device. Almost always the same as SERVER_IFADDR_ETH0.
* `SERVER_HOSTNAME` - Defines the server hostname. The actual value depends on
your server network configuration. Under Linux you can see the hostname for
your server using the -f option to the <i>hostname</i> command.
* `<API key>` - Defines the server short hostname. The actual value
depends on your server network configuration. Under Linux you can see the
short hostname for your server using the -s option to the <i>hostname</i> command.
* `SERVER_HOSTDOMAIN` - Defines the server domain name. The actual value depends
on your server network configuration. Under Linux you can see the short hostname
for your server using the -d option to the <i>hostname</i> command.
Exported Functions
* `pwee_info()` - Prints out the same information as phpinfo() except it only
displays Pwee module information.
XML Environment Definition
Document Type Definition
<!DOCTYPE Environments
[
<!ELEMENT Environments ((Package|Application)+)>
<!ELEMENT Application ((Server|Constants|Variables)+)>
<!ATTLIST Application name CDATA #REQUIRED>
<!ATTLIST Application namespace CDATA #REQUIRED>
<!ATTLIST Application comment CDATA #IMPLIED>
<!ELEMENT Package ((Server|Constants|Variables)+)>
<!ATTLIST Package name CDATA #REQUIRED>
<!ATTLIST Package namespace CDATA #REQUIRED>
<!ATTLIST Package comment CDATA #IMPLIED>
<!ELEMENT Server ((Constants|Variables)+)>
<!ATTLIST Server ip CDATA #IMPLIED>
<!ATTLIST Server interface CDATA #IMPLIED>
<!ATTLIST Server hostname CDATA #IMPLIED>
<!ATTLIST Server domain CDATA #IMPLIED>
<!ATTLIST Server comment CDATA #IMPLIED>
<!ELEMENT Constants (Constant+)>
<!ATTLIST Constants prefix CDATA #IMPLIED>
<!ATTLIST Constants comment CDATA #IMPLIED>
<!ELEMENT Constant EMPTY>
<!ATTLIST Constant name CDATA #REQUIRED>
<!ATTLIST Constant value CDATA #REQUIRED>
<!ATTLIST Constant type (string|long|boolean|double) "string">
<!ATTLIST Constant comment CDATA #IMPLIED>
<!ELEMENT Variables (Variable+)>
<!ATTLIST Variables prefix CDATA #IMPLIED>
<!ATTLIST Variables scope (request|executor) "request">
<!ATTLIST Variables comment CDATA #IMPLIED>
<!ELEMENT Variable EMPTY>
<!ATTLIST Variable name CDATA #REQUIRED>
<!ATTLIST Variable value CDATA #REQUIRED>
<!ATTLIST Variable type (string|long|boolean|double) "string">
<!ATTLIST Variable scope (request|executor) #IMPLIED>
<!ATTLIST Variable comment CDATA #IMPLIED>
]>
XML Elements
# Environments
The Environment element is the document root. It must contain one or more
Application or Package elements.
# Application and Package
Constants and variables are grouped by Application or Package elements.
Currently there is no difference between these two elements as they have the same
attributes. Application and Package elements must contain one or more Server,
Constants or Variables elements.
* `name` - Each Application and Package must be named. This is a string value
and is used for informational purposes only.
* `namespace` - Each Application and Package must define a namespace. The namespace
is a string that will prefix the name of each constant and variable in the
Application or Package. The namespace value will be separated from the constant
or variable name with an underscore character.
* `comment` - The element can have an associated string comment for documentation purposes.
# Server
The Server element is used to control the constants and variables that are defined
for particular servers. You can restrict constants and variables based on the server
IP address, hostname or domain. Server elements must contain one or more Constants
and Variables sections. These elements will only apply when the conditions of the Server
element are met.
* `ip` - You can restrict the environment defined for a particular server by specifying the
exact IP address of the server. If you want an environment to be applied to multiple servers
you can set the IP address to a particular subnet. For example, if you want to set the
environment for only the server 192.168.1.10 you would set "ip = 192.168.1.10".
If you have more than one server and want to set the environment for all servers in
a particular Class C subnet (192.168.1.*) you would set "ip = 192.168.1." (note
the trailing period).
* `interface` - When defining the environment based on IP address the default is to use the
IP address of the eth0 network interface. If you want to use the IP of a different
network interface you can use this attribute. This attribute is only relative if the
ip attribute is set.
* `hostname` - You can define the environment based on the server hostname instead
of the IP address by setting a value for this attribute instead of the ip attribute.
The environment will only be applied if there is an exact match between this value
and the short hostname of the server. Under Linux you can see the short hostname
for your server using the -s option with the <i>hostname</i> command. If the ip
attribute is set the hostname attribute is ignored.
* `domain` - You can define the environment based on the server domain instead of
the IP address by setting a value for this attribute instead of the ip attribute.
The environment will only be applied if there is an exact match between this value
and the hostname domain of the server. Under Linux you can see the hostname domain
for your server using the -d option with the <i>hostname</i> command. If the ip
or hostname attribute is set the domain attribute is ignored.
* `comment` - The element can have an associated string comment for documentation purposes.
# Constants
Constant elements are grouped together by a Constants element. Constants elements
must contain one or more Constant elements.
* `prefix` - Prefix is a string value that will prefix the name of each constant
in the element. The prefix will be separated from the constant name with an underscore character.
This prefix is applied in addition to the namespace prefix for the Application or Package.
* `comment` - The element can have an associated string comment for documentation purposes.
# Variables
Variable elements are grouped together by a Variables element. Variables elements
must contain one or more Variable elements
* `prefix` - Prefix is a string value that will prefix the name of each variable
in the element. The prefix will be separated from the variable name with an
underscore character. This prefix is applied in addition to the namespace prefix
for the Application or Package.
* `scope` - You can apply a scope to a group of Variable elements by setting the
scope of the Variables element. See the description of the Variable scope attribute
for a list of string values that can be used. The default scope is request.
* `comment` - The element can have an associated string comment for documentation purposes.
# Constant
Constant elements allow you to define constant values cannot be changed during
script execution.
* `name` - Each constant must be named. The actual name of the constant accessible
to scripts depends on the namespace of the Application or Package and whether the
Constants element defined a prefix.
* `value` - The value for the constant. The value must be specified as a string but
is converted to a PHP type based on the type attribute.
* `type` - The constant type can be string, long, boolean or double. If the type
is not specified it is assumed to be a string.
* `comment` - The element can have an associated string comment for documentation purposes.
# Variable
Variable elements allow you to define variable values that can be changed during
script execution. Depending on the scope of the variable the lifetime of the
variable can be changed.
* `name` - Each variable must be named. The actual name of the variable accessible
to scripts depends on the namespace of the Application or Package and whether the
Variables element defined a prefix.
* `value` - The value for the variable. The value must be specified as a string but
is converted to a PHP type based on the type attribute.
* `type` - The variable type can be string, long, boolean or double. If the type
is not specified it is assumed to be a string.
* `scope` - Scope controls the lifetime of variable. The scope can be request or executor.
If the variable has request scope the value of the variable will be reset for
each request. This is the default scope. The more interesting scope is executor.
This scope allows the variable to retain its value across multiple requests.
This behavior is greatly dependent on how PHP is invoked. For example,
if you use Apache with mod_php each individual Apache process is considered an
executor. Requests handled by each executor will be able to access and modify the
value available to the next request. Executor scope does not (yet) allow you to define
"application" variables that are shared between all executors.
If you dynamically load the extension as a shared library the executor scope becomes
request scope because the lifetime of the executor and request are the same.
If a Variable scope is set it overrides the scope of the Variables element.
* `comment` - The element can have an associated string comment for documentation purposes.
Example
An example will help illustrate what kind of problem Pwee solves. If your web application uses
a database, each script needs to know the hostname of the database server (as well as the username
and password). This is easily achieved by hardcoding the hostname in your script.
$db = new Database;
$db->hostname = "foo";
$db->user = "user";
$db->password = "password";
This is very simplistic however. If you have both a development and production network you need to
add logic to the script so your application uses the appropriate database based on where it's running.
One way to achieve this is to base it on the IP address of the server.
$db = new Database;
if (ereg("^192.168.1.", _SERVER["SERVER_ADDR"]))
$db->hostname = "foo";
else
$db->hostname = "bar";
This logic fails though if you run your script from the shell because SERVER_ADDR is not defined.
If you run scripts from the shell you have to work up some other way to determine weather you should be using the
production or development database server. The fact remains however that every single time a script
is run it has to examine its environment in order to determine what it should do.
If you want to make the process more efficient an alternative is to create server specific include
files that define the environment without having to examine anything. In this case you would create
two scripts, say production.config.inc and development.config.inc. Each script would
define the constant you can use when connecting to the database.
config.inc links to <i>production.config.inc</i> on <i>production</i> servers:
define(DATABASE_HOSTNAME, "foo");
config.inc links to <i>development.config.inc</i> on <i>development</i> servers:
define(DATABASE_HOSTNAME, "bar");
At the top of each script you just include the configuration script.
require_once("config.inc");
$db = new Database;
$db->hostname = DATABASE_HOSTNAME;
This solution works well but is very error prone because you have to manage two files
that need to have the same name but contain different content. Bad things can happen if
you accidentally overwrite the file on the wrong server. If you have more than two networks it becomes
even more error prone.
Using the Pwee extension you would just create an environment definition in XML.
<?xml version="1.0"?>
<Environments>
<Application name="My web application" namespace="">
<Constants>
<Constant name="DATABASE_USER" value="user" />
<Constant name="DATABASE_PASSWORD" value="password" />
</Constants>
<Server ip="192.168.1.">
<Constants>
<Constant name="DATABASE_HOSTNAME" value="bar" />
</Constants>
</Server>
<Server ip="10.10.0.">
<Constants>
<Constant name="DATABASE_HOSTNAME" value="foo" />
</Constants>
</Server>
</Application>
</Environments>
This environment defines USER and PASSWORD as being server independent whereas HOSTNAME
depends on the IP address of the server. Depending on how you invoke PHP, the environment
definition will only be read once and the appropriate constants will be added to the runtime
environment for all your scripts. The scripts don't need to have any extra logic or waste
any time determining what values for which constants to use.
This example is a good illustration for another problem common to PHP web applications.
Almost every script contains include and require statements. Take the simple script above.
require_once("config.inc");
The question is where exactly is config.inc? If PHP doesn't find this script in the local
directory it's going to search your include path. What if you have multiple projects and each
has its own config.inc? You could add more path information.
require_once("projectA/config.inc");
But you still might be forcing PHP to search the include path. In order to streamline performance
and keep PHP from searching for the file on every script execution you need to specify the full
path to the file. (Include paths also become an issue if you have a lot of VirtualHosts. You don't want to
include VirtualHost specific directories in the main include_path. If you set the include_path
in .htaccess files you run into trouble when you execute PHP from the shell.)
require_once("/full/path/to/projectA/config.inc");
This works but becomes a nuisance if the full path to your project changes. A common solution
to avoid full paths is to include one main configuration file that defines a constant or variable
that can be used in subsequent include statements.
require_once("projectA/config.inc");
- or -
require_once("/full/path/to/projectA/config.inc");
// config.inc set $INCLUDE_DIR
require_once("$INCLUDE_DIR/classA.php");
require_once("$INCLUDE_DIR/classB.php");
This is a good solution but you are still forced to either search the include path or
have full paths in your scripts. Pwee provides a better solution. You can define a Pwee
environment that defines INCLUDE_DIR as either a variable or as a constant.
<?xml version="1.0"?>
<Environments>
<Application name="www.domain.com" namespace="">
<Variables>
<Variable name="INCLUDE_DIR" value="/full/path/to/projectA" />
</Variables>
</Application>
</Environments>
<?xml version="1.0"?>
<Environments>
<Application name="www.domain.com" namespace="">
<Constants>
<Constant name="INCLUDE_DIR" value="/full/path/to/projectA/" />
</Constants>
</Application>
</Environments>
Then use that variable or constant as before.
require_once("$INCLUDE_DIR/classA.php");
- or -
require_once(INCLUDE_DIR . "classA.php");
Why
Q) Why not just include a file at the top of each script that defines all the
constants and variables you need?
The short answer - efficiency. The example above provides a good illustration. You are
forced to either make PHP search the include path to find the include file
or you must have at least one full path hard coded in all your scripts.
Depending on your situation and performance requirements and what the include file
actually needs to do you may be better off using an include file. If your include
file just defines a bunch of constants and global variables you're better off with
Pwee. If the script you include contains application logic you must use an include
file. Pwee also lets you benefit from executor variables which an include file cannot
provide. Even when using include files Pwee can be useful because it will define
constants (such as the server's IP address) that you can use to make server specific
decisions. If you use a caching product like Zend Accelerator, APC, PHPA, etc.
the performance hit for including a file is probably negligible but Pwee may be
able to reduce it to zero.
Q) Why not just use the php.ini setting auto_prepend_file?
First read the answer for the question above. Using auto_prepend_file is better
than the include file approach because instead of hard coding a path in all your
scripts you just hard code a script path in your php.ini. The downside still is
that you are wasting time defining constants and variables with each script execution
that could be done once per executor. As with the include file approach in general
using auto_prepend_file has its place too.
Sample Packages
Smarty Template Engine
If you use the [Smarty Template Engine](http:
here is a Pwee package that defines constants that Smarty will use. Smarty uses the
SMARTY_DIR constant to find the location of the Smarty classes. The other constants are useful
only if you change the hardcoded paths in the Smarty class definition.
<Package name="Smarty" namespace="SMARTY">
<Constants>
<Constant name="DIR" value="/var/www/domain.com/classes/Smarty/" />
<Constant name="TEMPLATE_DIR" value="/var/www/domain.com/templates/" />
<Constant name="COMPILE_DIR" value="/var/www/domain.com/cache/Smarty/templates_c/" />
<Constant name="CACHE_DIR" value="/var/www/domain.com/cache/Smarty/cache/" />
<Constant name="CONFIG_DIR" value="/var/www/domain.com/classes/Smarty/configs/" />
</Constants>
</Package>
ADOdb Database Library for PHP
If you use the [ADOdb Database Library for PHP](http://adodb.sourceforge.net/) here
is a Pwee package that defines both constants and variables that ADOdb can use. ADOdb uses the
ADODB_DIR constant to find the location of the ADOdb classes. ADOdb will use the ADODB_CACHE_DIR
variable to find the location of the cache directory. If you are using ADOdb for session
management you can define variables the session handler will use. You can include these variables
in a Server block so you can have different connection parameters for production and development
networks.
<Package name="ADODB" namespace="ADODB">
<Constants>
<Constant name="DIR" value="/var/www/domain.com/classes/adodb" />
</Constants>
<Variables>
<Variable name="CACHE_DIR" value="/var/www/domain.com/cache/adodb" />
</Variables>
<Server ip="192.168.0." comment="development servers">
<Variables prefix="SESSION">
<Variable name="DRIVER" value="mysql" />
<Variable name="USER" value="user" />
<Variable name="PWD" value="password" />
<Variable name="DB" value="database" />
<Variable name="CONNECT" value="server" />
<Variable name="TBL" value="sessions" />
</Variables>
</Server>
</Package> |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
file=str(sys.argv[1])
file2=str(sys.argv[2])
outfile=open(file2,'w')
with open (file) as f:
for line in f:
if line.startswith('<API key>'):
line = line.replace('<API key>','<API key>')
line = line.replace('table.gz','table.minphr')
if line.startswith('LexicalReordering'):
line = line.replace('bidirectional-fe.gz','bidirectional-fe')
outfile.write(line)
outfile.close() |
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
namespace BugGuardian.WebForms.TestWebApp {
public partial class SiteMaster {
<summary>
MainContent control.
</summary>
<remarks>
Auto-generated field.
To modify move field declaration from designer file to code-behind file.
</remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent;
}
} |
<ion-nav-bar>
</ion-nav-bar>
<ion-view view-title="Allergies">
<ion-nav-buttons side="secondary">
<button class="button button-clear" ng-click="add()">
<i class="icon <API key>"></i> Add
</button>
</ion-nav-buttons>
<ion-content>
<div class="list">
<ion-checkbox ng-repeat="allergy in allergiesList" ng-model="allergy.checked" ng-checked="allergy.checked">
{{allergy.text}}
</ion-checkbox>
</div>
</ion-content>
</ion-view> |
<?php
namespace Blog\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Blog\MainBundle\Entity\Category;
/**
* Post
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Blog\MainBundle\Entity\PostRepository")
*/
class Post
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Category
* @ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
* @ORM\JoinColumn(name="category_id", <API key>="id")
*/
protected $category;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* @var string
*
* @ORM\Column(name="content", type="text", length=25000)
*/
private $content;
/**
* @var \DateTime
*
* @ORM\Column(name="startingDate", type="datetime", nullable=true)
*/
private $startingDate;
/**
* @var \DateTime
*
* @ORM\Column(name="endingDate", type="datetime", nullable=true)
*/
private $endingDate;
/**
* @var \DateTime
*
* @ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* @var \DateTime
*
* @ORM\Column(name="modified", type="datetime")
*/
private $modified;
/**
* @var integer
*
* @ORM\Column(name="status", type="integer")
*/
private $status;
public function __construct()
{
$this->setCreated(new \DateTime());
$this->setModified(new \DateTime());
$this->setStatus(1);
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* @param Category $category
* @return Post
*/
public function setCategory(Category $category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Set title
*
* @param string $title
* @return Post
*/
public function setTitle($title)
{
$this->title = $title;
$this->slug = $this->slugify($title);
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set slug
*
* @param string $slug
* @return Post
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* @return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set content
*
* @param string $content
* @return Post
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set starting date
*
* @param \DateTime $startingDate
* @return Post
*/
public function setStartingDate($startingDate = null)
{
$this->startingDate = $startingDate;
return $this;
}
/**
* Get starting date
*
* @return \DateTime
*/
public function getStartingDate()
{
return $this->startingDate;
}
/**
* Set ending date
*
* @param \DateTime $endingDate
* @return Post
*/
public function setEndingDate($endingDate = null)
{
$this->endingDate = $endingDate;
return $this;
}
/**
* Get ending date
*
* @return \DateTime
*/
public function getEndingDate()
{
return $this->endingDate;
}
/**
* Set created
*
* @param \DateTime $created
* @return Post
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set modified
*
* @param \DateTime $modified
* @return Post
*/
public function setModified($modified)
{
$this->modified = $modified;
return $this;
}
/**
* Get modified
*
* @return \DateTime
*/
public function getModified()
{
return $this->modified;
}
/**
* Set status
*
* @param integer $status
* @return Post
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Generate slugified version of given string
*
* @param $text
* @return mixed|string
*/
public function slugify($text)
{
// Change scandic characters to stripped ones
$text = str_replace('å', 'a', $text);
$text = str_replace('Å', 'a', $text);
$text = str_replace('ä', 'a', $text);
$text = str_replace('Ä', 'a', $text);
$text = str_replace('ö', 'o', $text);
$text = str_replace('Ö', 'o', $text);
// replace non letter or digits by -
$text = preg_replace('#[^\\pL\d]+#u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
if (function_exists('iconv'))
{
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('#[^-\w]+#', '', $text);
if (empty($text))
{
return 'n-a';
}
return $text;
}
} |
package cz.augi.gsonscala
import java.lang.reflect.ParameterizedType
import java.util.Optional
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.{JsonReader, JsonWriter}
import com.google.gson.{Gson, TypeAdapter, TypeAdapterFactory}
object <API key> extends TypeAdapterFactory {
override def create[T](gson: Gson, t: TypeToken[T]): TypeAdapter[T] =
if (classOf[Optional[_]].isAssignableFrom(t.getRawType)) new OptionalTypeAdapter(gson, t) else null
}
class OptionalTypeAdapter[T](gson: Gson, t: TypeToken[T]) extends TypeAdapter[T] {
val innerType = t.getType.asInstanceOf[ParameterizedType].<API key>()(0)
override def write(out: JsonWriter, value: T): Unit =
value match {
case o: Optional[_] =>
if (o.isPresent) {
gson.toJson(o.get, innerType, out)
} else {
// we must forcibly write null in order the read method to be called
val orig = out.getSerializeNulls
out.setSerializeNulls(true)
out.nullValue()
out.setSerializeNulls(orig)
}
}
override def read(in: JsonReader): T = Optional.ofNullable(gson.fromJson(in, innerType)).asInstanceOf[T]
} |
@charset "UTF-8";
#settings-ctrl {
position: relative;
}
#donate {
position: absolute;
top: 0;
right: 0;
}
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],
.ng-cloak, .x-ng-cloak,
.ng-hide {
display: none !important;
}
ng\:form {
display: block;
}
body {
height: 200px;
width: 500px;
font-family: 'Open Sans', sans-serif;
}
.btn {
color: #333;
}
.btn.btn-primary,
.btn.btn-danger {
color: #FFF;
}
.spacer {
margin-top: 49px;
height: 1px;
}
.center {
text-align: center;
}
#countdown {
margin-bottom: 20px;
}
#countdown h1 {
font-size: 4em;
font-family: 'Open Sans', sans-serif;
text-shadow: none;
}
#countdown .time-unit {
font-size: 24px;
}
@font-face {
font-family: 'Actor';
src: url('chrome-extension://__MSG_@@extension_id__/fonts/DroidSansMono.ttf');
}
.actionbar {
position: absolute;
bottom: 0.25em;
right: 0.25em;
}
.actionbar .glyphicon-cog {
font-size: 24px;
color: #000;
text-decoration: none;
}
.actionbar .glyphicon-cog:hover {
color: #333;
}
.actionbar li {
list-style: none;
}
.actionbar ul {
margin: 0;
}
.actionbar {
color: #333;
}
.typeahead ul {
max-height: 150px;
border: 1px solid #333;
padding: 3px;
overflow: auto;
}
.break .container {
height: 500px;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align: center;
}
.break h1 {
margin-top: 40px;
}
/* Settings */
.settings .container {
width: 700px;
height: 500px;
margin: auto;
position: absolute;
left: 0;
right: 0;
}
.settings .container h3 {
margin-top: 40px;
}
.form-control {
width: initial;
}
.form-group label {
display: block;
font-size: 16px;
font-weight: 400;
}
input.form-control {
display: inline-block;
}
.form-control.checkbox {
display: inline-block;
width: 17px;
height: 17px;
}
.form-control.min-input {
width: 75px;
}
.form-group.has-error,
.form-group.has-error .help-block {
color: #FD5E5A;
}
input[type='color'] {
padding: 3px 2px;
width: 40px;
}
.day-input {
display: inline-block;
padding-left: 10px;
padding-right: 10px;
}
.day-input label {
display: inline-block;
width: 25px;
}
.alert.save-alert {
width: 400px;
position: fixed;
z-index: 2;
margin: auto;
left: 0;
right: 0;
text-align: center;
} |
package edu.ustc.mix.core.mq.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
public class RabbitMQReceiver {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
// <API key>(factory);
<API key>(factory);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
while (true) {
Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
public static void <API key>(ConnectionFactory factory) {
factory.setHost("localhost");
}
public static void <API key>(ConnectionFactory factory) {
factory.setHost("10.0.40.151");
factory.setPort(5672);
factory.setUsername("gatewayservice");
factory.setPassword("pass");
factory.setVirtualHost("/contact");
}
} |
/*!
Parse a request details: filters, fields selection, sorting
*/
export default function (resource_obj, querystring, context) {
// resource identifier in the querystring params
const res_key = resource_obj.relationship ? resource_obj.relationship.name : resource_obj.type;
// querystring param to consider time to time
let key = '';
// ids are needed
resource_obj.ids = resource_obj.ids || [];
// is the client asking for a particular subset of fields?
resource_obj.fields = resource_obj.fields || [];
key = 'fields[' + res_key + ']';
if (querystring[key] !== undefined) {
resource_obj.fields = querystring[key].split(',');
delete querystring[key];
} else if (0 === resource_obj.fields.length) {
// if not, add all fields
resource_obj.fields = Object.keys(context.resources[resource_obj.type].attributes);
}
// is the client asking for a particular sorting?
resource_obj.sorters = resource_obj.sorters || [];
key = 'sort[' + res_key + ']';
if (querystring[key] !== undefined) {
resource_obj.sorters = querystring[key].split(',').map((field) => {
return {
field: field.slice(1),
// fields are prefixed with + for ascending order and - for descending
asc: field[0] === '+'
};
});
delete querystring[key];
}
// is the client asking for a filtered response?
resource_obj.filters = resource_obj.filters || [];
Object.keys(context.resources[resource_obj.type].attributes).forEach((field) => {
key = res_key + '[' + field + ']';
if (querystring[key] !== undefined) {
resource_obj.filters.push({field, values: querystring[key].split(',')});
delete querystring[key];
}
});
return resource_obj;
} |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int getLength(struct ListNode* head) {
int length = 0;
while (head != NULL) {
head = head->next;
length++;
}
return length;
}
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* reverse = NULL;
struct ListNode* node = NULL;
while (head != NULL) {
node = head;
head = head->next;
node->next = reverse;
reverse = node;
}
return reverse;
}
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* rHead = NULL;
struct ListNode* rTail = NULL;
struct ListNode* sHead = NULL;
struct ListNode* sTail = NULL;
while (head != NULL) {
sHead = head;
sTail = head;
int cnt = k;
while (--cnt > 0 && sTail->next != NULL) {
sTail = sTail->next;
}
if (cnt > 0) {
break;
}
head = sTail->next;
sTail->next = NULL;
sHead = reverseList(sHead);
if (rHead == NULL) {
rHead = sHead;
rTail = sHead;
} else {
rTail->next = sHead;
}
while (rTail->next != NULL) {
rTail = rTail->next;
}
}
if (rHead == NULL) return head;
rTail->next = head;
return rHead;
} |
class Integer
def divisible_by?(k)
(self % k).zero?
end
def next_divisible_int(k)
((self / k) + 1) * k
end
def prev_divisible_int(k)
return (self - k) if divisible_by?(k)
(self / k) * k
end
end
def solution(a, b, k)
count = 0
count += a.divisible_by?(k) ? 1 : 0
count += b.divisible_by?(k) ? 1 : 0
count + ((b.prev_divisible_int(k) - a.next_divisible_int(k)) / k) + 1
end |
// Use of this source code is governed by a BSD-style
package sync2
import (
"testing"
"time"
)
func TestSemaNoTimeout(t *testing.T) {
s := NewSemaphore(1)
s.Acquire()
released := false
go func() {
time.Sleep(10 * time.Millisecond)
released = true
s.Release()
}()
s.Acquire()
if !released {
t.Errorf("want true, got false")
}
}
func TestSemaTimeout(t *testing.T) {
s := NewSemaphore(1)
s.Acquire()
go func() {
time.Sleep(10 * time.Millisecond)
s.Release()
}()
if ok := s.AcquireTimeout(5 * time.Millisecond); ok {
t.Errorf("want false, got true")
}
time.Sleep(10 * time.Millisecond)
if ok := s.AcquireTimeout(5 * time.Millisecond); !ok {
t.Errorf("want true, got false")
}
} |
using Library.Entity;
namespace Library.Services.Interface
{
public interface <API key> : IServiceBase<FamilyEventTemplate>
{
<summary>
Create a FamilyEvent from a FamilyEventTemplate
</summary>
<param name="id">Id of FamilyEventTemplate</param>
<returns></returns>
FamilyEvent CreateEvent(string id);
}
} |
<html>
<head>
<title>Mozilla/5.0 (Linux; U; Android 4.0.3; xx; LG-L40G Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
Mozilla/5.0 (Linux; U; Android 4.0.3; xx; LG-L40G Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
<p>
Detected by 8 of 8 providers<br />
As bot detected by 0 of 7
</p>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Actions</th></tr><tr><td>BrowscapPhp<br /><small>6011</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.0</td><td></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ |
"tags": ["Wiki", "ESHTMC", "ESHTMC"],
"author": "Xin Feng",
"title": "Jinlong Weng's Friend, Invitation"
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<h1>Invitation</h1>
<canvas id="myCanvas" width="1024" height="1024"></canvas>
<script>
var canvas_width=1024;
var canvas_height=768;
var margin_width=canvas_width/25;
var margin_height=canvas_height/25;
var theater_rows=14;
var seat_width=24;
var seat_height=36;
function calc_seat_loc(row,id) {
if (row == 14) {
if (id == 1) {return 14;}
else if ((id >= 2) && (id % 2 == 0)) {return 14+id/2;}
else if ((id >= 3) && (id % 2 == 1)) {return 12-(id-1)/2;}
}
else if ((row <= 4) || ((row >= 11 ) && (row <= 13))) {
seat01=13;
seat02=14;
}
else if ((row >=5) && (row <=10)) {
seat01=15;
seat02=16;
}
if (id % 2 == 1) {return seat01-(id-1)/2;}
else if (id % 2 == 0) {return seat02+(id-2)/2;}
}
function make_seat(row,id,sold){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var color='white';
if (sold == 0){
color='white';
}
else if (sold == 1){
color='gray';
} else {
color='yellow';
}
var posx = margin_width + calc_seat_loc(row,id) * seat_width;
var posy = margin_height + (theater_rows-row) * seat_height;
context.beginPath();
context.rect(posx, posy, seat_width, seat_height);
context.fillStyle = color;
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();
context.font = '10pt Calibri';
context.fillStyle = 'black';
context.textAlign = 'center';
context.fillText(id, posx+12, posy+20);
}
function mark_rows(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var posx = margin_width/2;
for (row=1; row<=theater_rows; row++){
var posy = margin_height + (theater_rows-row) * seat_height + 20;
context.font = '10pt Calibri';
context.fillStyle = 'black';
context.textAlign = 'center';
context.fillText('Row '+row, posx, posy);
}
}
function empty_seats(){
for(row=1; row<=4; row++){
for(id=1; id<=22; id++){
make_seat(row,id,0);
}
}
for(row=11; row<=13; row++){
for(id=1; id<=22; id++){
make_seat(row,id,0);
}
}
for(row=5; row<=10; row++){
for(id=1; id<=19; id++){
make_seat(row,id,0);
}
}
for(id=1; id<=23; id++)
make_seat(14,id,0);
}
function reserve_seats(){
make_seat(12,16,2);
}
function one(buyer,row,id){
make_seat(row,id,1);
}
function six(buyer,row,id1,id2,id3,id4,id5,id6){
if (id1>0)
one(buyer,row,id1);
if (id2>0)
one(buyer,row,id2);
if (id3>0)
one(buyer,row,id3);
if (id4>0)
one(buyer,row,id4);
if (id5>0)
one(buyer,row,id5);
if (id6>0)
one(buyer,row,id6);
}
function five(buyer,row,id1,id2,id3,id4,id5){
six(buyer,row,id1,id2,id3,id4,id5,0);
}
function four(buyer,row,id1,id2,id3,id4){
five(buyer,row,id1,id2,id3,id4,0);
}
function three(buyer,row,id1,id2,id3){
four(buyer,row,id1,id2,id3,0);
}
function two(buyer,row,id1,id2){
three(buyer,row,id1,id2,0);
}
function range(buyer,row,min,max){
for(id=min; id<=max; id++)
make_seat(row,id,1);
}
//INIT
mark_rows();
empty_seats();
//BEGIN_TICKETS
one('Elva Zhou',11,6);
three('Elva Zhou',3,18,20,22);
two('Elva Zhou',10,6,8);
one('Elva Zhou',12,2);
two('Elva Zhou',12,14,16);
//END_TICKETS
reserve_seats();
function make_legend(owner, buyer){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
color='yellow';
context.beginPath();
loc = margin_width + calc_seat_loc(1,21) * seat_width
context.rect(loc, 600, seat_width, seat_height);
context.fillStyle = color;
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();
context.font = '10pt Calibri';
context.fillStyle = 'black';
context.textAlign = 'center';
context.fillText(owner, loc + 90, 613);
context.fillText('(Owner)', loc + 90, 633);
color='gray';
context.beginPath();
loc = margin_width + calc_seat_loc(1,22) * seat_width
context.rect(loc, 600, seat_width, seat_height);
context.fillStyle = color;
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();
context.font = '10pt Calibri';
context.fillStyle = 'black';
context.textAlign = 'center';
context.fillText(buyer, loc - 60, 613);
context.fillText('(Buyer)', loc - 60, 633);
}
make_legend("Jinlong Weng's Friend", "Elva Zhou")
</script>
</body>
</html> |
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20131103135539) do
create_table "my_timeline_events", :force => true do |t|
t.string "description"
t.datetime "happened_on"
t.string "icon_name"
t.string "external_link"
t.string "original_id"
t.boolean "public", :default => true
t.integer "importance", :default => 5
t.integer "user_id"
t.integer "linkable_id"
t.string "linkable_type"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "my_timeline_foos", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "my_timeline_posts", :force => true do |t|
t.text "full_text"
t.datetime "happened_on"
t.integer "event_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "<API key>", :force => true do |t|
t.string "var", :null => false
t.text "value"
t.integer "target_id", :null => false
t.string "target_type", :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "<API key>", ["target_type", "target_id", "var"], :name => "<API key>", :unique => true
end |
"use strict";
var Root = require('../root');
module.exports = Root.create().
def('linear', function (from, to) {
return function (progress) {
return from + ((to - from) * progress);
};
}).
def('sineIn', function (from, to) {
var linear = this.linear(from, to);
return function (progress) {
return linear(Math.sin(progress * Math.PI / 2));
};
}).
def('sineOut', function (from, to) {
var linear = this.linear(from, to);
return function (progress) {
return linear(1 - Math.sin((1 - progress) * Math.PI / 2));
};
}).
def('stepIn', function (from, to) {
return function (progress) {
return progress === 0 ? from : to;
};
}).
def('stepOut', function (from, to) {
return function (progress) {
return progress !== 1 ? from : to;
};
}); |
module MongoJob
module Helpers
# Given a word with dashes, returns a camel cased version of it.
# classify('job-name') # => 'JobName'
def classify(dashed_word)
dashed_word.split('-').each { |part| part[0] = part[0].chr.upcase }.join
end
# Given a camel cased word, returns the constant it represents
# constantize('JobName') # => JobName
def constantize(camel_cased_word)
camel_cased_word = camel_cased_word.to_s
if camel_cased_word.include?('-')
camel_cased_word = classify(camel_cased_word)
end
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
constant = constant.const_get(name) || constant.const_missing(name)
end
constant
end
end
end |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Web.WebPages.OAuth;
using SumatorMVC.Models;
namespace SumatorMVC
{
public static class AuthConfig
{
public static void RegisterAuth()
{
// To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
//OAuthWebSecurity.<API key>(
// clientId: "",
// clientSecret: "");
//OAuthWebSecurity.<API key>(
// consumerKey: "",
// consumerSecret: "");
//OAuthWebSecurity.<API key>(
// appId: "",
// appSecret: "");
//OAuthWebSecurity.<API key>();
}
}
} |
layout: post
title: wake up you need to make money!!!
date: 2016-04-03
categories:
- All me
description:
image: 'https://jaythanelam.github.io/mommy-knows-best/assets/images/wakeup-make-money.jpg'
image-sm: 'https://jaythanelam.github.io/mommy-knows-best/assets/images/wakeup-make-money.jpg'
I'm looking at going back to school. While it's been on the docket for awhile - ok, like a decade - I guess I need to get my big girl panties on and just get-er-done! Full Disclosure, even just typing the words "going back to school" makes my stomach roll. Don't get me wrong,
> I truly loved the experience of college. The freedom on every level. Freedom to explore. Freedom to experiment. Freedom to experience. I LOVED THAT PART.
But the academics... the memorization and the formidable exams. Failing when you really tried. Failing when you hoped for luck. Failure is just a bitch no matter how you skin it. ;) So, looking at going back to school now, minus "the experience" with a whole lotta -it's not about the adventure, but pure academics mama!! Looking to gain knowledge and insight and to be honest, getting out there and makin some money! (how apt that a crazy rap song so perfectly fits this point in my life, "WAKE UP YOU NEED TO MAKE MONEY!!!") - is all a little terrifying!
So, I've got my liquid courage and I'm setting out on a new adventure starting now... Wish me luck ;)
xoxo,
Jen |
package com.chiorichan.plugin.acme.certificate;
import com.chiorichan.AppConfig;
import com.chiorichan.configuration.<API key>;
import com.chiorichan.http.HttpCode;
import com.chiorichan.http.ssl.CertificateWrapper;
import com.chiorichan.lang.EnumColor;
import com.chiorichan.logger.Log;
import com.chiorichan.plugin.acme.AcmePlugin;
import com.chiorichan.plugin.acme.AcmeScheduledTask;
import com.chiorichan.plugin.acme.api.<API key>;
import com.chiorichan.plugin.acme.api.AcmeProtocol;
import com.chiorichan.plugin.acme.api.AcmeUtils;
import com.chiorichan.plugin.acme.api.<API key>;
import com.chiorichan.plugin.acme.api.HttpResponse;
import com.chiorichan.plugin.acme.lang.AcmeException;
import com.chiorichan.plugin.acme.lang.AcmeState;
import com.chiorichan.site.Site;
import com.chiorichan.site.SiteManager;
import com.chiorichan.utils.UtilEncryption;
import com.chiorichan.utils.UtilIO;
import io.jsonwebtoken.impl.TextCodec;
import org.bouncycastle.operator.<API key>;
import org.bouncycastle.x509.util.<API key>;
import java.io.File;
import java.io.<API key>;
import java.io.IOException;
import java.security.<API key>;
import java.security.KeyStoreException;
import java.security.<API key>;
import java.security.<API key>;
import java.security.cert.<API key>;
import java.security.cert.<API key>;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
public class Certificate
{
private File sslCertFile;
private File sslKeyFile;
private final String key;
private boolean pendingUpdate = false;
private String uri;
private <API key> configSection;
private CertificateWrapper certificateCache = null;
private final Set<String> domains = new HashSet<>();
public Certificate( <API key> configSection ) throws <API key>, IOException
{
String privateKey = configSection.getString( "privateKey", "domain" );
sslCertFile = configSection.has( "certFile" ) ? UtilIO.isAbsolute( configSection.getString( "certFile" ) ) ? new File( configSection.getString( "certFile" ) ) : new File( AppConfig.get().getDirectory().getAbsolutePath(), configSection.getString( "certFile" ) ) : null;
sslKeyFile = <API key>.getPrivateKey( privateKey );
this.key = configSection.getName();
this.configSection = configSection;
this.uri = configSection.getString( "uri" );
if ( key.equals( "default" ) )
domains.addAll( AcmeScheduledTask.getVerifiedDomains() );
else
// TODO Allow mapping to contain domains and/or siteIds
for ( String map : configSection.getAsList( "mapping", new ArrayList<String>() ) )
{
Site site = SiteManager.instance().getSiteById( map );
if ( site != null )
site.getDomains().forEach( n ->
{
domains.add( n.getFullDomain() );
} );
}
}
public String certUri()
{
return uri;
}
public File getCertFile()
{
return sslCertFile;
}
public CertificateWrapper getCertificate()
{
if ( certificateCache == null )
try
{
certificateCache = new CertificateWrapper( sslCertFile, sslKeyFile, null );
domains.addAll( certificateCache.<API key>() );
}
catch ( <API key> | <API key> e )
{
e.printStackTrace();
return null;
}
return certificateCache;
}
public File getKeyFile()
{
return sslKeyFile;
}
public String key()
{
return key;
}
public String md5()
{
if ( configSection.getString( "md5" ) == null && sslCertFile != null )
configSection.set( "md5", UtilEncryption.md5( sslCertFile ) );
return configSection.getString( "md5" );
}
private void renewCertificate() throws <API key>, <API key>, <API key>, KeyStoreException, AcmeException, <API key>, <API key>, IOException
{
if ( pendingUpdate )
throw new AcmeException( "Certificate " + key() + " is pending an update!" );
Log.get().info( EnumColor.AQUA + "Attempting to renew certificate: " + key() );
<API key> downloader = new <API key>( null, certUri() );
File parentDir = new File( AcmePlugin.instance().getDataFolder(), key );
do
downloader.save( parentDir );
while ( downloader.isPending() && !downloader.isDownloaded() );
File sslCertFileTemp = new File( parentDir, "fullchain.pem" );
// Log.get().debug( "Old MD5 %s and New MD5 %s", md5(), SecureFunc.md5( sslCertFileTemp ) );
// According to the Acme Protocol, it is plausible for the CA to not response with a renewed certificate. For now, we will compare the old and new certificate MD5, if they match, we request a revoke and renew to force renewal.
if ( md5().equals( UtilEncryption.md5( sslCertFileTemp ) ) )
{
Log.get().warning( "The CA did not respond with a renewed certificate, we will now force a renewal by first revoking the old certificate." );
revokeCertificate();
signNewCertificate();
}
sslCertFile = sslCertFileTemp;
certificateCache = null;
save();
}
public boolean revokeCertificate()
{
if ( pendingUpdate )
return false;
try
{
if ( getCertificate() == null )
return false;
pendingUpdate = true;
AcmeProtocol proto = AcmePlugin.instance().getClient();
String body = proto.newJwt( new TreeMap<String, Object>()
{
{
put( "resource", "revoke-cert" );
put( "certificate", TextCodec.BASE64URL.encode( getCertificate().getEncoded() ) );
}
} );
HttpResponse response = AcmeUtils.post( "POST", proto.getUrlNewRevoke(), "application/json", body, "application/json" );
proto.nonce( response.getHeaderString( "Replay-Nonce" ) );
pendingUpdate = false;
if ( response.getStatus() == HttpCode.HTTP_OK )
{
certificateCache = null;
return true;
}
else
return false;
}
catch ( AcmeException | <API key> | <API key> | <API key> | KeyStoreException | IOException | <API key> e )
{
return false;
}
}
private void save()
{
<API key> section = AcmePlugin.instance().getSubConfig().<API key>( "certificates." + key, true );
section.set( "certFile", UtilIO.relPath( sslCertFile ) );
section.set( "privateKey", <API key>.getPrivateKeyIden( sslKeyFile ) );
section.set( "uri", certUri() );
section.set( "md5", UtilEncryption.md5( sslCertFile ) );
AcmePlugin.instance().saveConfig();
}
private void signNewCertificate() throws <API key>, <API key>, <API key>, KeyStoreException, <API key>, AcmeException, IOException, <API key>
{
if ( pendingUpdate )
throw new AcmeException( "Certificate " + key() + " is pending an update!" );
final Certificate cert = this;
pendingUpdate = true;
<API key> signingRequest = AcmePlugin.instance().getClient().newSigningRequest( domains, sslKeyFile );
signingRequest.doCallback( true, () ->
{
if ( signingRequest.getState() == AcmeState.SUCCESS )
try
{
File parentDir = UtilIO.buildFile( AcmePlugin.instance().getDataFolder(), key );
signingRequest.getDownloader().save( parentDir );
sslCertFile = new File( parentDir, "fullchain.pem" );
uri = signingRequest.getDownloader().getCertificateUri();
save();
if ( key.equals( "default" ) )
<API key>.<API key>( cert );
else if ( !<API key>.certificateLoaded( key ) )
<API key>.loadCertificate( cert );
}
catch ( AcmeException e )
{
AcmePlugin.instance().getLogger().severe( "Unexpected Exception Thrown", e );
}
else
AcmePlugin.instance().getLogger().severe( "Failed certificate signing for reason " + signingRequest.lastMessage() );
pendingUpdate = false;
} );
}
public boolean validateCertificate()
{
try
{
if ( pendingUpdate )
return false;
if ( sslKeyFile == null )
sslKeyFile = <API key>.getPrivateKey( "domain" );
if ( key.equals( "default" ) )
domains.addAll( AcmeScheduledTask.getVerifiedDomains() );
if ( !UtilIO.checkMd5( sslCertFile, md5() ) )
{
if ( sslCertFile == null )
sslCertFile = UtilIO.buildFile( AcmePlugin.instance().getDataFolder(), key, "fullchain.pem" );
if ( certUri() == null )
{
signNewCertificate();
return false;
}
else
renewCertificate();
}
// If the certificate will expire in less than 15 days, we will attempt to renew it.
if ( getCertificate() == null || getCertificate().daysRemaining() < 15 )
renewCertificate();
if ( key.equals( "default" ) && getCertificate() != null )
{
List<String> dnsNames = getCertificate().<API key>();
if ( !dnsNames.containsAll( domains ) )
{
// Log.get().debug( "Default certificate is missing domains --> " + Joiner.on( ", " ).join( domains ) + " // " + Joiner.on( ", " ).join( dnsNames ) );
revokeCertificate();
signNewCertificate();
return false;
}
}
return true;
}
catch ( AcmeException | <API key> | <API key> | <API key> | KeyStoreException | <API key> | IOException | <API key> e )
{
e.printStackTrace();
return false;
}
}
} |
<?php
namespace Mayeco\NotificationsBundle\Entity;
use Doctrine\ORM\EntityRepository;
class ResponseRepository extends EntityRepository
{
} |
using Ycql.SqlFunctions;
namespace Ycql.SqlServerFunctions
{
<summary>
Represents Day function in Sql Server which returns an integer representing the day (day of the month) of the specified date
</summary>
public class <API key> : SqlFunctionBase
{
<summary>
Initializes a new instance of the <API key> class using specified column
</summary>
<param name="column">A column that is time, date, smalldatetime, datetime, datetime2, or datetimeoffset</param>
public <API key>(DbColumn column)
: this((object) column)
{
}
<summary>
Initializes a new instance of the <API key> class using specified date expression
</summary>
<param name="dateExpression">An expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value</param>
public <API key>(object dateExpression)
: base("DAY", dateExpression)
{
}
}
} |
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Maquileros</h3>
<div class="box-tools pull-right">
<a ng-show="vm.can('crear_maquilero')" class="btn btn-block btn-success btn-xs" href="#!/maquilero-add"><i class="fa fa-plus"></i> Agregar Maquilero</a>
</div>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
<div class="row">
<div class="col-xs-6">
<div id="<API key>" class="dataTables_filter">
<label>
Buscar:<input ng-model="vm.search" type="search" class="form-control input-sm" placeholder="" aria-controls="DataTables_Table_0">
</label>
</div>
</div>
</div>
<div style="overflow-x:auto;">
<table class="table table-striped table-responsive">
<tr>
<th>Nombre</th>
<th>Apellidos</th>
<th>Calle</th>
<th>No Interior</th>
<th>No Exterior</th>
<th>Colonia</th>
<th>Ciudad</th>
<th>Municipio</th>
<th>Fijo</th>
<th>Movil</th>
<th ng-show="vm.can('editar_maquilero')|| vm.can('eliminar_maquilero')"> </th>
</tr>
<tr ng-repeat="t in vm.textileros | filter:vm.search ">
<td><a ng-href="#!/maquileros/{{t.id_textileros}}" ng-bind="t.nombre" ng-show="vm.can('ver_maquilero')"></a>
<span ng-bind="t.nombre" ng-show="!vm.can('ver_maquilero')"></span>
</td>
<td ng-bind="t.apellidos"></td>
<td ng-bind="t.calle"></td>
<td ng-bind="t.no_interior"></td>
<td ng-bind="t.no_exterior"></td>
<td ng-bind="t.colonia"></td>
<td ng-bind="t.ciudad"></td>
<td ng-bind="t.municipio"></td>
<td ng-bind="t.telefono_fijo"></td>
<td ng-bind="t.telefono_movil"></td>
<td ng-show="vm.can('editar_maquilero')|| vm.can('eliminar_maquilero')">
<div class="btn-group" >
<button class="btn btn-xs btn-warning" ng-click="vm.update(t)" ng-show="vm.can('editar_maquilero')">
<i class="fa fa-edit"></i>
</button>
<button class="btn btn-xs btn-danger" ng-click="vm.delete(t.id_textileros)" ng-show="vm.can('eliminar_maquilero')">
<i class="fa fa-trash-o"></i>
</button>
</div>
</td>
</tr>
</table>
</div>
<div class="alert alert-danger" ng-show="vm.error">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
<span ng-bind="vm.error"></span>
</div>
</div>
</div>
</div>
</div> |
// BMPLoader.cpp
// PacManX
#pragma once
#include "../include/BMPLoader.hpp"
#define STD_OFFSET 54
using std::ios;
BMPloader::BMPloader(const string filename) {
mImage = NULL;
mWidth = mHeight = 0;
mIsOK = false;
infile = new ifstream(filename.c_str(), ios::in | ios::binary);
if (!infile->fail()) {
char ch1, ch2;
infile->get(ch1); infile->get(ch2);
if (ch1 == 'B' && ch2 == 'M') {
unsigned int total = getLong();
infile->seekg( 4, ios::cur);
unsigned int offset = getLong();
infile->seekg( 0, ios::end);
unsigned long int length = infile->tellg();
if (length == total && offset == STD_OFFSET) {
infile->seekg( 18, ios::beg);
unsigned int w = getLong();
unsigned int h = getLong();
infile->seekg( 2, ios::cur);
unsigned int bitCount = getShort();
unsigned int compression = getLong();
unsigned int sizeImage = getLong();
if (bitCount == 24 && compression == 0 &&
(sizeImage == 0 || sizeImage == (3*w*h)) &&
(3*w*h+offset) <= length) {
total = 3 * w * h;
infile->seekg(offset, ios::beg);
mImage = new char[total];
infile->read(mImage, total);
if (infile->gcount() == total) {
mWidth = w;
mHeight = h;
mIsOK = true;
char * ptr = mImage;
for (int i = 0; i < (w * h); i++) {
ch1 = *(ptr+2);
*(ptr+2) = *ptr;
*ptr = ch1;
ptr+=3;
}
}
}
}
}
infile->close();
}
delete infile;
}
BMPloader::~BMPloader() {
if (mImage != NULL) {
delete mImage;
}
}
const unsigned int BMPloader::getShort() {
char ch1, ch2;
infile->get( ch2); infile->get( ch1);
return (ch1 & 0x00ff) * 256 + (ch2 & 0x00ff);
}
const unsigned int BMPloader::getLong() {
unsigned int low = getShort();
return getShort() * 0x10000 + low;
} |
export const FETCH_INSTRUMENTS = "FETCH_INSTRUMENTS"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const CREATE_INSTRUMENT = "CREATE_INSTRUMENT"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const UPDATE_INSTRUMENT = "UPDATE_INSTRUMENT"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const DELETE_INSTRUMENT = "DELETE_INSTRUMENT"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const CREATE_MAPPING = "CREATE_MAPPING"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const RESET_NEW_MAPPING = "RESET_NEW_MAPPING"
export const <API key> = "<API key>"
export const DELETE_MAPPING = "DELETE_MAPPING"
export const <API key> = "<API key>"
export const <API key> = "<API key>"
export const <API key> = "<API key>" |
# coding: utf-8
import bisect
import contextlib
import csv
from datetime import datetime
import functools
import json
import logging
import random
import threading
import time
import unittest
import uuid
import redis
QUIT = False
SAMPLE_COUNT = 100
config_connection = None
# <start id="recent_log"/>
SEVERITY = {
logging.DEBUG: 'debug',
logging.INFO: 'info',
logging.WARNING: 'warning',
logging.ERROR: 'error',
logging.CRITICAL: 'critical',
}
SEVERITY.update((name, name) for name in SEVERITY.values())
def log_recent(conn, name, message, severity=logging.INFO, pipe=None):
severity = str(SEVERITY.get(severity, severity)).lower()
destination = 'recent:%s:%s'%(name, severity)
message = time.asctime() + ' ' + message
pipe = pipe or conn.pipeline()
pipe.lpush(destination, message)
# 100
pipe.ltrim(destination, 0, 99)
pipe.execute()
# <end id="recent_log"/>
# <start id="common_log"/>
def log_common(conn, name, message, severity=logging.INFO, timeout=5):
severity = str(SEVERITY.get(severity, severity)).lower()
destination = 'common:%s:%s'%(name, severity)
start_key = destination + ':start'
pipe = conn.pipeline()
end = time.time() + timeout
while time.time() < end:
try:
pipe.watch(start_key)
now = datetime.utcnow().timetuple()
hour_start = datetime(*now[:4]).isoformat()
existing = pipe.get(start_key)
pipe.multi()
if existing and existing < hour_start:
pipe.rename(destination, destination + ':last')
pipe.rename(start_key, destination + ':pstart')
pipe.set(start_key, hour_start)
pipe.zincrby(destination, message)
# log_recent()execute()
log_recent(pipe, name, message, severity, pipe)
return
except redis.exceptions.WatchError:
continue
# <end id="common_log"/>
# <start id="update_counter"/>
PRECISION = [1, 5, 60, 300, 3600, 18000, 86400]
def update_counter(conn, name, count=1, now=None):
now = now or time.time()
pipe = conn.pipeline()
for prec in PRECISION:
pnow = int(now / prec) * prec
hash = '%s:%s'%(prec, name)
pipe.zadd('known:', hash, 0)
pipe.hincrby('count:' + hash, pnow, count)
pipe.execute()
# <end id="update_counter"/>
# <start id="get_counter"/>
def get_counter(conn, name, precision):
hash = '%s:%s'%(precision, name)
# Redis
data = conn.hgetall('count:' + hash)
to_return = []
for key, value in data.iteritems():
to_return.append((int(key), int(value)))
to_return.sort()
return to_return
# <end id="get_counter"/>
# <start id="clean_counters"/>
def clean_counters(conn):
pipe = conn.pipeline(True)
passes = 0
while not QUIT:
start = time.time()
index = 0
while index < conn.zcard('known:'):
hash = conn.zrange('known:', index, index)
index += 1
if not hash:
break
hash = hash[0]
prec = int(hash.partition(':')[0])
bprec = int(prec // 60) or 1
if passes % bprec:
continue
hkey = 'count:' + hash
cutoff = time.time() - SAMPLE_COUNT * prec
samples = map(int, conn.hkeys(hkey))
samples.sort()
remove = bisect.bisect_right(samples, cutoff)
if remove:
conn.hdel(hkey, *samples[:remove])
if remove == len(samples):
try:
pipe.watch(hkey)
if not pipe.hlen(hkey):
pipe.multi()
pipe.zrem('known:', hash)
pipe.execute()
index -= 1
else:
pipe.unwatch()
except redis.exceptions.WatchError:
pass
passes += 1
duration = min(int(time.time() - start) + 1, 60)
time.sleep(max(60 - duration, 1))
# <end id="clean_counters"/>
# <start id="update_stats"/>
def update_stats(conn, context, type, value, timeout=5):
destination = 'stats:%s:%s'%(context, type)
# common_log()
start_key = destination + ':start'
pipe = conn.pipeline(True)
end = time.time() + timeout
while time.time() < end:
try:
pipe.watch(start_key)
now = datetime.utcnow().timetuple()
hour_start = datetime(*now[:4]).isoformat()
existing = pipe.get(start_key)
pipe.multi()
if existing and existing < hour_start:
pipe.rename(destination, destination + ':last')
pipe.rename(start_key, destination + ':pstart')
pipe.set(start_key, hour_start)
tkey1 = str(uuid.uuid4())
tkey2 = str(uuid.uuid4())
pipe.zadd(tkey1, 'min', value)
pipe.zadd(tkey2, 'max', value)
# MINMAX
pipe.zunionstore(destination,
[destination, tkey1], aggregate='min')
pipe.zunionstore(destination,
[destination, tkey2], aggregate='max')
pipe.delete(tkey1, tkey2)
pipe.zincrby(destination, 'count')
pipe.zincrby(destination, 'sum', value)
pipe.zincrby(destination, 'sumsq', value*value)
return pipe.execute()[-3:]
except redis.exceptions.WatchError:
continue
# <end id="update_stats"/>
# <start id="get_stats"/>
def get_stats(conn, context, type):
key = 'stats:%s:%s'%(context, type)
data = dict(conn.zrange(key, 0, -1, withscores=True))
data['average'] = data['sum'] / data['count']
numerator = data['sumsq'] - data['sum'] ** 2 / data['count']
data['stddev'] = (numerator / (data['count'] - 1 or 1)) ** .5
return data
# <end id="get_stats"/>
# <start id="<API key>"/>
# Python
@contextlib.contextmanager
def access_time(conn, context):
start = time.time()
yield
delta = time.time() - start
stats = update_stats(conn, context, 'AccessTime', delta)
average = stats[1] / stats[0]
pipe = conn.pipeline(True)
pipe.zadd('slowest:AccessTime', context, average)
# AccessTime100
pipe.zremrangebyrank('slowest:AccessTime', 0, -101)
pipe.execute()
# <end id="<API key>"/>
# <start id="access_time_use"/>
# viewRedis
def process_view(conn, callback):
with access_time(conn, request.path):
# yield
return callback()
# <end id="access_time_use"/>
# <start id="_1314_14473_9188"/>
def ip_to_score(ip_address):
score = 0
for v in ip_address.split('.'):
score = score * 256 + int(v, 10)
return score
# <end id="_1314_14473_9188"/>
# 5-10
# <start id="_1314_14473_9191"/>
# GeoLiteCity-Blocks.csv
def import_ips_to_redis(conn, filename):
csv_file = csv.reader(open(filename, 'rb'))
for count, row in enumerate(csv_file):
start_ip = row[0] if row else ''
if 'i' in start_ip.lower():
continue
if '.' in start_ip:
start_ip = ip_to_score(start_ip)
elif start_ip.isdigit():
start_ip = int(start_ip, 10)
else:
continue
city_id = row[2] + '_' + str(count)
# IDIP
conn.zadd('ip2cityid:', city_id, start_ip)
# <end id="_1314_14473_9191"/>
# 5-11
# <start id="_1314_14473_9194"/>
# GeoLiteCity-Location.csv
def <API key>(conn, filename):
for row in csv.reader(open(filename, 'rb')):
if len(row) < 4 or not row[0].isdigit():
continue
row = [i.decode('latin-1') for i in row]
city_id = row[0]
country = row[1]
region = row[2]
city = row[3]
# Redis
conn.hset('cityid2city:', city_id,
json.dumps([city, region, country]))
# <end id="_1314_14473_9194"/>
# 5-12
# <start id="_1314_14473_9197"/>
def find_city_by_ip(conn, ip_address):
# IPZREVRANGEBYSCORE
if isinstance(ip_address, str):
ip_address = ip_to_score(ip_address)
city_id = conn.zrevrangebyscore(
'ip2cityid:', ip_address, 0, start=0, num=1)
if not city_id:
return None
# IDID
city_id = city_id[0].partition('_')[0]
return json.loads(conn.hget('cityid2city:', city_id))
# <end id="_1314_14473_9197"/>
# 5-13
# <start id="<API key>"/>
LAST_CHECKED = None
<API key> = False
def <API key>(conn):
global LAST_CHECKED, <API key>
if LAST_CHECKED < time.time() - 1:
LAST_CHECKED = time.time()
<API key> = bool(
conn.get('<API key>'))
return <API key>
# <end id="<API key>"/>
# 5-14
# <start id="set_config"/>
def set_config(conn, type, component, config):
conn.set(
'config:%s:%s'%(type, component),
json.dumps(config))
# <end id="set_config"/>
#END
# 5-15
# <start id="get_config"/>
CONFIGS = {}
CHECKED = {}
def get_config(conn, type, component, wait=1):
key = 'config:%s:%s'%(type, component)
if CHECKED.get(key) < time.time() - wait:
CHECKED[key] = time.time()
# Redis
config = json.loads(conn.get(key) or '{}')
# Unicode
config = dict((str(k), config[k]) for k in config)
old_config = CONFIGS.get(key)
if config != old_config:
CONFIGS[key] = config
return CONFIGS.get(key)
# <end id="get_config"/>
# 5-16
# <start id="redis_connection"/>
REDIS_CONNECTIONS = {}
def redis_connection(component, wait=1):
key = 'config:redis:' + component
def wrapper(function):
@functools.wraps(function)
def call(*args, **kwargs):
old_config = CONFIGS.get(key, object())
_config = get_config(
config_connection, 'redis', component, wait)
config = {}
# Redis
for k, v in _config.iteritems():
config[k.encode('utf-8')] = v
if config != old_config:
REDIS_CONNECTIONS[key] = redis.Redis(**config)
# Redis
return function(
REDIS_CONNECTIONS.get(key), *args, **kwargs)
return call
# Redis
return wrapper
# <end id="redis_connection"/>
# 5-17
'''
# <start id="<API key>"/>
@redis_connection('logs') # redis_connection()
def log_recent(conn, app, message): #
'the old log_recent() code'
log_recent('main', 'User 235 logged in') # log_recent()
# <end id="<API key>"/>
'''
class request:
pass
# a faster version with pipelines for actual testing
def import_ips_to_redis(conn, filename):
csv_file = csv.reader(open(filename, 'rb'))
pipe = conn.pipeline(False)
for count, row in enumerate(csv_file):
start_ip = row[0] if row else ''
if 'i' in start_ip.lower():
continue
if '.' in start_ip:
start_ip = ip_to_score(start_ip)
elif start_ip.isdigit():
start_ip = int(start_ip, 10)
else:
continue
city_id = row[2] + '_' + str(count)
pipe.zadd('ip2cityid:', city_id, start_ip)
if not (count+1) % 1000:
pipe.execute()
pipe.execute()
def <API key>(conn, filename):
pipe = conn.pipeline(False)
for count, row in enumerate(csv.reader(open(filename, 'rb'))):
if len(row) < 4 or not row[0].isdigit():
continue
row = [i.decode('latin-1') for i in row]
city_id = row[0]
country = row[1]
region = row[2]
city = row[3]
pipe.hset('cityid2city:', city_id,
json.dumps([city, region, country]))
if not (count+1) % 1000:
pipe.execute()
pipe.execute()
class TestCh05(unittest.TestCase):
def setUp(self):
global config_connection
import redis
self.conn = config_connection = redis.Redis(db=15)
self.conn.flushdb()
def tearDown(self):
self.conn.flushdb()
del self.conn
global config_connection, QUIT, SAMPLE_COUNT
config_connection = None
QUIT = False
SAMPLE_COUNT = 100
print
print
def test_log_recent(self):
import pprint
conn = self.conn
print "Let's write a few logs to the recent log"
for msg in xrange(5):
log_recent(conn, 'test', 'this is message %s'%msg)
recent = conn.lrange('recent:test:info', 0, -1)
print "The current recent message log has this many messages:", len(recent)
print "Those messages include:"
pprint.pprint(recent[:10])
self.assertTrue(len(recent) >= 5)
def test_log_common(self):
import pprint
conn = self.conn
print "Let's write some items to the common log"
for count in xrange(1, 6):
for i in xrange(count):
log_common(conn, 'test', "message-%s"%count)
common = conn.zrevrange('common:test:info', 0, -1, withscores=True)
print "The current number of common messages is:", len(common)
print "Those common messages are:"
pprint.pprint(common)
self.assertTrue(len(common) >= 5)
def test_counters(self):
import pprint
global QUIT, SAMPLE_COUNT
conn = self.conn
print "Let's update some counters for now and a little in the future"
now = time.time()
for delta in xrange(10):
update_counter(conn, 'test', count=random.randrange(1,5), now=now+delta)
counter = get_counter(conn, 'test', 1)
print "We have some per-second counters:", len(counter)
self.assertTrue(len(counter) >= 10)
counter = get_counter(conn, 'test', 5)
print "We have some per-5-second counters:", len(counter)
print "These counters include:"
pprint.pprint(counter[:10])
self.assertTrue(len(counter) >= 2)
print
tt = time.time
def new_tt():
return tt() + 2*86400
time.time = new_tt
print "Let's clean out some counters by setting our sample count to 0"
SAMPLE_COUNT = 0
t = threading.Thread(target=clean_counters, args=(conn,))
t.setDaemon(1) # to make sure it dies if we ctrl+C quit
t.start()
time.sleep(1)
QUIT = True
time.time = tt
counter = get_counter(conn, 'test', 86400)
print "Did we clean out all of the counters?", not counter
self.assertFalse(counter)
def test_stats(self):
import pprint
conn = self.conn
print "Let's add some data for our statistics!"
for i in xrange(5):
r = update_stats(conn, 'temp', 'example', random.randrange(5, 15))
print "We have some aggregate statistics:", r
rr = get_stats(conn, 'temp', 'example')
print "Which we can also fetch manually:"
pprint.pprint(rr)
self.assertTrue(rr['count'] >= 5)
def test_access_time(self):
import pprint
conn = self.conn
print "Let's calculate some access times..."
for i in xrange(10):
with access_time(conn, "req-%s"%i):
time.sleep(.5 + random.random())
print "The slowest access times are:"
atimes = conn.zrevrange('slowest:AccessTime', 0, -1, withscores=True)
pprint.pprint(atimes[:10])
self.assertTrue(len(atimes) >= 10)
print
def cb():
time.sleep(1 + random.random())
print "Let's use the callback version..."
for i in xrange(5):
request.path = 'cbreq-%s'%i
process_view(conn, cb)
print "The slowest access times are:"
atimes = conn.zrevrange('slowest:AccessTime', 0, -1, withscores=True)
pprint.pprint(atimes[:10])
self.assertTrue(len(atimes) >= 10)
def test_ip_lookup(self):
conn = self.conn
try:
open('GeoLiteCity-Blocks.csv', 'rb')
open('<API key>.csv', 'rb')
except:
print "********"
print "You do not have the GeoLiteCity database available, aborting test"
print "Please have the following two files in the current path:"
print "GeoLiteCity-Blocks.csv"
print "<API key>.csv"
print "********"
return
print "Importing IP addresses to Redis... (this may take a while)"
import_ips_to_redis(conn, 'GeoLiteCity-Blocks.csv')
ranges = conn.zcard('ip2cityid:')
print "Loaded ranges into Redis:", ranges
self.assertTrue(ranges > 1000)
print
print "Importing Location lookups to Redis... (this may take a while)"
<API key>(conn, '<API key>.csv')
cities = conn.hlen('cityid2city:')
print "Loaded city lookups into Redis:", cities
self.assertTrue(cities > 1000)
print
print "Let's lookup some locations!"
rr = random.randrange
for i in xrange(5):
print find_city_by_ip(conn, '%s.%s.%s.%s'%(rr(1,255), rr(256), rr(256), rr(256)))
def <API key>(self):
print "Are we under maintenance (we shouldn't be)?", <API key>(self.conn)
self.conn.set('<API key>', 'yes')
print "We cached this, so it should be the same:", <API key>(self.conn)
time.sleep(1)
print "But after a sleep, it should change:", <API key>(self.conn)
print "Cleaning up..."
self.conn.delete('<API key>')
time.sleep(1)
print "Should be False again:", <API key>(self.conn)
def test_config(self):
print "Let's set a config and then get a connection from that config..."
set_config(self.conn, 'redis', 'test', {'db':15})
@redis_connection('test')
def test(conn2):
return bool(conn2.info())
print "We can run commands from the configured connection:", test()
if __name__ == '__main__':
unittest.main() |
package com.swandiggy.poe4j.data.rows.gen;
import java.util.List;
import com.swandiggy.poe4j.data.annotations.DatFile;
import com.swandiggy.poe4j.data.annotations.Order;
import com.swandiggy.poe4j.data.rows.BaseRow;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@DatFile("<API key>")
public class <API key>
extends BaseRow
{
@Order(0)
private String id1;
@Order(1)
private String id2;
@Order(2)
private List<Integer> data1;
@Order(3)
private List<Integer> data2;
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class CI_DB_mysqli_driver | Practica2_Servidor</title>
<link rel="stylesheet" href="resources/style.css?<SHA1-like>">
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li>
<a href="namespace-Composer.html">
Composer<span></span>
</a>
<ul>
<li>
<a href="namespace-Composer.Autoload.html">
Autoload </a>
</li>
</ul></li>
<li class="active">
<a href="namespace-None.html">
None </a>
</li>
<li>
<a href="namespace-org.html">
org<span></span>
</a>
<ul>
<li>
<a href="namespace-org.bovigo.html">
bovigo<span></span>
</a>
<ul>
<li>
<a href="namespace-org.bovigo.vfs.html">
vfs<span></span>
</a>
<ul>
<li>
<a href="namespace-org.bovigo.vfs.example.html">
example </a>
</li>
<li>
<a href="namespace-org.bovigo.vfs.visitor.html">
visitor </a>
</li>
</ul></li></ul></li></ul></li>
<li>
<a href="namespace-PHP.html">
PHP </a>
</li>
</ul>
</div>
<hr>
<div id="elements">
<h3>Classes</h3>
<ul>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-Agregador.html" class="invalid">Agregador</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">AutoFilterTest</a></li>
<li><a href="<API key>.html">AutoloaderTest</a></li>
<li><a href="<API key>.html">CalculationTest</a></li>
<li><a href="class-Camiseta.html">Camiseta</a></li>
<li><a href="class-Carrito.html">Carrito</a></li>
<li><a href="class-Carro.html">Carro</a></li>
<li><a href="class-Categorias.html">Categorias</a></li>
<li><a href="<API key>.html">CellCollectionTest</a></li>
<li><a href="class-CellTest.html">CellTest</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-CI_Benchmark.html" class="invalid">CI_Benchmark</a></li>
<li><a href="class-CI_Cache.html" class="invalid">CI_Cache</a></li>
<li><a href="class-CI_Cache_apc.html" class="invalid">CI_Cache_apc</a></li>
<li><a href="<API key>.html" class="invalid">CI_Cache_dummy</a></li>
<li><a href="class-CI_Cache_file.html" class="invalid">CI_Cache_file</a></li>
<li><a href="<API key>.html" class="invalid">CI_Cache_memcached</a></li>
<li><a href="<API key>.html">CI_Cache_redis</a></li>
<li><a href="<API key>.html">CI_Cache_wincache</a></li>
<li><a href="class-CI_Calendar.html" class="invalid">CI_Calendar</a></li>
<li><a href="class-CI_Cart.html" class="invalid">CI_Cart</a></li>
<li><a href="class-CI_Config.html" class="invalid">CI_Config</a></li>
<li><a href="class-CI_Controller.html" class="invalid">CI_Controller</a></li>
<li><a href="<API key>.html">CI_DB_active_record</a></li>
<li><a href="class-CI_DB_Cache.html" class="invalid">CI_DB_Cache</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_cubrid_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_cubrid_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_cubrid_result</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="class-CI_DB_driver.html" class="invalid">CI_DB_driver</a></li>
<li><a href="class-CI_DB_forge.html" class="invalid">CI_DB_forge</a></li>
<li><a href="<API key>.html">CI_DB_ibase_driver</a></li>
<li><a href="<API key>.html">CI_DB_ibase_forge</a></li>
<li><a href="<API key>.html">CI_DB_ibase_result</a></li>
<li><a href="<API key>.html">CI_DB_ibase_utility</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mssql_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mssql_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mssql_result</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mssql_utility</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mysql_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mysql_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mysql_result</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mysql_utility</a></li>
<li class="active"><a href="<API key>.html" class="invalid">CI_DB_mysqli_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mysqli_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_mysqli_result</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_oci8_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_oci8_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_oci8_result</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_oci8_utility</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_odbc_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_odbc_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_odbc_result</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_odbc_utility</a></li>
<li><a href="<API key>.html">CI_DB_pdo_4d_driver</a></li>
<li><a href="<API key>.html">CI_DB_pdo_4d_forge</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_pdo_driver</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_pdo_forge</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">CI_DB_pdo_ibm_forge</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">CI_DB_pdo_oci_forge</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_pdo_result</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_pdo_utility</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_postgre_forge</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html">CI_DB_query_builder</a></li>
<li><a href="class-CI_DB_result.html" class="invalid">CI_DB_result</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">CI_DB_sqlite3_forge</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_sqlite_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_sqlite_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_sqlite_result</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_sqlsrv_driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_sqlsrv_forge</a></li>
<li><a href="<API key>.html" class="invalid">CI_DB_sqlsrv_result</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="class-CI_DB_utility.html" class="invalid">CI_DB_utility</a></li>
<li><a href="class-CI_Driver.html" class="invalid">CI_Driver</a></li>
<li><a href="<API key>.html" class="invalid">CI_Driver_Library</a></li>
<li><a href="class-CI_Email.html" class="invalid">CI_Email</a></li>
<li><a href="class-CI_Encrypt.html" class="invalid">CI_Encrypt</a></li>
<li><a href="class-CI_Encryption.html">CI_Encryption</a></li>
<li><a href="class-CI_Exceptions.html" class="invalid">CI_Exceptions</a></li>
<li><a href="<API key>.html" class="invalid">CI_Form_validation</a></li>
<li><a href="class-CI_FTP.html" class="invalid">CI_FTP</a></li>
<li><a href="class-CI_Hooks.html" class="invalid">CI_Hooks</a></li>
<li><a href="class-CI_Image_lib.html" class="invalid">CI_Image_lib</a></li>
<li><a href="class-CI_Input.html" class="invalid">CI_Input</a></li>
<li><a href="class-CI_Javascript.html" class="invalid">CI_Javascript</a></li>
<li><a href="class-CI_Jquery.html" class="invalid">CI_Jquery</a></li>
<li><a href="class-CI_Lang.html" class="invalid">CI_Lang</a></li>
<li><a href="class-CI_Loader.html" class="invalid">CI_Loader</a></li>
<li><a href="class-CI_Log.html" class="invalid">CI_Log</a></li>
<li><a href="class-CI_Migration.html" class="invalid">CI_Migration</a></li>
<li><a href="class-CI_Model.html" class="invalid">CI_Model</a></li>
<li><a href="class-CI_Output.html" class="invalid">CI_Output</a></li>
<li><a href="class-CI_Pagination.html" class="invalid">CI_Pagination</a></li>
<li><a href="class-CI_Parser.html" class="invalid">CI_Parser</a></li>
<li><a href="class-CI_Profiler.html" class="invalid">CI_Profiler</a></li>
<li><a href="class-CI_Router.html" class="invalid">CI_Router</a></li>
<li><a href="class-CI_Security.html" class="invalid">CI_Security</a></li>
<li><a href="class-CI_Session.html" class="invalid">CI_Session</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">CI_Session_driver</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-CI_SHA1.html">CI_SHA1</a></li>
<li><a href="class-CI_Table.html" class="invalid">CI_Table</a></li>
<li><a href="class-CI_Trackback.html" class="invalid">CI_Trackback</a></li>
<li><a href="class-CI_Typography.html" class="invalid">CI_Typography</a></li>
<li><a href="class-CI_Unit_test.html" class="invalid">CI_Unit_test</a></li>
<li><a href="class-CI_Upload.html" class="invalid">CI_Upload</a></li>
<li><a href="class-CI_URI.html" class="invalid">CI_URI</a></li>
<li><a href="class-CI_User_agent.html" class="invalid">CI_User_agent</a></li>
<li><a href="class-CI_Utf8.html" class="invalid">CI_Utf8</a></li>
<li><a href="class-CI_Xmlrpc.html" class="invalid">CI_Xmlrpc</a></li>
<li><a href="class-CI_Xmlrpcs.html" class="invalid">CI_Xmlrpcs</a></li>
<li><a href="class-CI_Zip.html" class="invalid">CI_Zip</a></li>
<li><a href="class-CodePageTest.html">CodePageTest</a></li>
<li><a href="class-ColorTest.html">ColorTest</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">ColumnIteratorTest</a></li>
<li><a href="class-Complex.html">Complex</a></li>
<li><a href="class-complexAssert.html">complexAssert</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-DataTypeTest.html">DataTypeTest</a></li>
<li><a href="class-DateTest.html">DateTest</a></li>
<li><a href="class-DateTimeTest.html">DateTimeTest</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">EliminarUsuario</a></li>
<li><a href="<API key>.html">EngineeringTest</a></li>
<li><a href="class-Error404.html">Error404</a></li>
<li><a href="class-Excel.html">Excel</a></li>
<li><a href="class-FileTest.html">FileTest</a></li>
<li><a href="class-FinancialTest.html">FinancialTest</a></li>
<li><a href="class-FontTest.html">FontTest</a></li>
<li><a href="class-FPDF.html">FPDF</a></li>
<li><a href="class-FunctionsTest.html">FunctionsTest</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-HyperlinkTest.html">HyperlinkTest</a></li>
<li><a href="<API key>.html">JSON_WebClient</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="class-LayoutTest.html">LayoutTest</a></li>
<li><a href="class-LegendTest.html">LegendTest</a></li>
<li><a href="class-LogicalTest.html">LogicalTest</a></li>
<li><a href="class-Login.html">Login</a></li>
<li><a href="class-LookupRefTest.html">LookupRefTest</a></li>
<li><a href="class-Main.html">Main</a></li>
<li><a href="class-MathTrigTest.html">MathTrigTest</a></li>
<li><a href="class-Mdl_Agregador.html">Mdl_Agregador</a></li>
<li><a href="class-Mdl_camiseta.html">Mdl_camiseta</a></li>
<li><a href="class-Mdl_carrito.html">Mdl_carrito</a></li>
<li><a href="<API key>.html">Mdl_categorias</a></li>
<li><a href="<API key>.html">Mdl_MisPedidos</a></li>
<li><a href="class-Mdl_pedidos.html">Mdl_pedidos</a></li>
<li><a href="<API key>.html">Mdl_provincias</a></li>
<li><a href="<API key>.html">Mdl_restablecerCont</a></li>
<li><a href="<API key>.html">Mdl_seleccionadas</a></li>
<li><a href="class-Mdl_usuarios.html">Mdl_usuarios</a></li>
<li><a href="class-Mdl_xml.html">Mdl_xml</a></li>
<li><a href="class-MisPedidos.html">MisPedidos</a></li>
<li><a href="<API key>.html">ModificarCorrecto</a></li>
<li><a href="<API key>.html">ModificarUsuario</a></li>
<li><a href="class-Monedas.html">Monedas</a></li>
<li><a href="class-MyReadFilter.html">MyReadFilter</a></li>
<li><a href="<API key>.html">NumberFormatTest</a></li>
<li><a href="<API key>.html">PasswordHasherTest</a></li>
<li><a href="class-PclZip.html">PclZip</a></li>
<li><a href="class-PDF.html" class="invalid">PDF</a></li>
<li><a href="class-Pedidos.html">Pedidos</a></li>
<li><a href="class-PHPExcel.html">PHPExcel</a></li>
<li><a href="<API key>.html">PHPExcel_Autoloader</a></li>
<li><a href="<API key>.html">PHPExcel_Best_Fit</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-PHPExcel_Cell.html">PHPExcel_Cell</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Chart</a></li>
<li><a href="<API key>.html">PHPExcel_Chart_Axis</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Comment</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_HashTable</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_IOFactory</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_NamedRange</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Properties</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Reader_CSV</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_RichText</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Settings</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Shared_OLE</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Style</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Style_Fill</a></li>
<li><a href="<API key>.html">PHPExcel_Style_Font</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Worksheet</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Writer_CSV</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Writer_PDF</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">ReferenceHelperTest</a></li>
<li><a href="class-Registro.html">Registro</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">RowCellIteratorTest</a></li>
<li><a href="<API key>.html">RowIteratorTest</a></li>
<li><a href="class-RuleTest.html">RuleTest</a></li>
<li><a href="<API key>.html">SesionNoIniciada</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-StringTest.html">StringTest</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="class-TextDataTest.html">TextDataTest</a></li>
<li><a href="class-Tienda01.html">Tienda01</a></li>
<li><a href="class-Tienda02.html">Tienda02</a></li>
<li><a href="class-Tiendas_Model.html">Tiendas_Model</a></li>
<li><a href="class-TimeZoneTest.html">TimeZoneTest</a></li>
<li><a href="class-trendClass.html">trendClass</a></li>
<li><a href="class-TTFParser.html">TTFParser</a></li>
<li><a href="<API key>.html">WorksheetColumnTest</a></li>
<li><a href="<API key>.html">WorksheetRowTest</a></li>
<li><a href="<API key>.html">XEEValidatorTest</a></li>
<li><a href="class-XML.html">XML</a></li>
<li><a href="<API key>.html" class="invalid">XML_RPC_Client</a></li>
<li><a href="<API key>.html" class="invalid">XML_RPC_Message</a></li>
<li><a href="<API key>.html" class="invalid">XML_RPC_Response</a></li>
<li><a href="<API key>.html" class="invalid">XML_RPC_Values</a></li>
</ul>
<h3>Interfaces</h3>
<ul>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
</ul>
<h3>Exceptions</h3>
<ul>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PHPExcel_Exception</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
</ul>
<h3>Functions</h3>
<ul>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html">_error_handler</a></li>
<li><a href="<API key>.html" class="invalid">_exception_handler</a></li>
<li><a href="<API key>.html" class="invalid">_get_smiley_array</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="function-_list.html" class="invalid">_list</a></li>
<li><a href="<API key>.html">_parse_attributes</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html">_shutdown_handler</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="function-acosh.html">acosh</a></li>
<li><a href="function-alternator.html" class="invalid">alternator</a></li>
<li><a href="function-anchor.html" class="invalid">anchor</a></li>
<li><a href="<API key>.html" class="invalid">anchor_popup</a></li>
<li><a href="<API key>.html">array_column</a></li>
<li><a href="<API key>.html">array_replace</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">ascii_to_entities</a></li>
<li><a href="function-asinh.html">asinh</a></li>
<li><a href="function-atanh.html">atanh</a></li>
<li><a href="function-auto_link.html" class="invalid">auto_link</a></li>
<li><a href="<API key>.html" class="invalid">auto_typography</a></li>
<li><a href="function-base_url.html" class="invalid">base_url</a></li>
<li><a href="function-br.html" class="invalid">br</a></li>
<li><a href="<API key>.html" class="invalid">byte_format</a></li>
<li><a href="<API key>.html">cambiaFormatoFecha</a></li>
<li><a href="function-camelize.html" class="invalid">camelize</a></li>
<li><a href="<API key>.html" class="invalid">character_limiter</a></li>
<li><a href="<API key>.html">claves_check</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">config_item</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html">CreaArrayParaSelect</a></li>
<li><a href="function-CreaSelect.html">CreaSelect</a></li>
<li><a href="<API key>.html">CreaSelectMod</a></li>
<li><a href="<API key>.html" class="invalid">create_captcha</a></li>
<li><a href="<API key>.html" class="invalid">current_url</a></li>
<li><a href="function-date_range.html">date_range</a></li>
<li><a href="<API key>.html" class="invalid">days_in_month</a></li>
<li><a href="function-DB.html" class="invalid">DB</a></li>
<li><a href="<API key>.html" class="invalid">delete_cookie</a></li>
<li><a href="<API key>.html" class="invalid">delete_files</a></li>
<li><a href="<API key>.html" class="invalid">directory_map</a></li>
<li><a href="<API key>.html">dni_LetraNIF</a></li>
<li><a href="function-do_hash.html" class="invalid">do_hash</a></li>
<li><a href="function-doctype.html" class="invalid">doctype</a></li>
<li><a href="function-element.html" class="invalid">element</a></li>
<li><a href="function-elements.html" class="invalid">elements</a></li>
<li><a href="function-ellipsize.html" class="invalid">ellipsize</a></li>
<li><a href="<API key>.html" class="invalid">encode_php_tags</a></li>
<li><a href="<API key>.html" class="invalid">entities_to_ascii</a></li>
<li><a href="<API key>.html" class="invalid">entity_decode</a></li>
<li><a href="function-Error.html">Error</a></li>
<li><a href="<API key>.html" class="invalid">force_download</a></li>
<li><a href="<API key>.html" class="invalid">form_button</a></li>
<li><a href="<API key>.html" class="invalid">form_checkbox</a></li>
<li><a href="function-form_close.html" class="invalid">form_close</a></li>
<li><a href="<API key>.html" class="invalid">form_dropdown</a></li>
<li><a href="function-form_error.html" class="invalid">form_error</a></li>
<li><a href="<API key>.html" class="invalid">form_fieldset</a></li>
<li><a href="<API key>.html" class="invalid">form_fieldset_close</a></li>
<li><a href="<API key>.html" class="invalid">form_hidden</a></li>
<li><a href="function-form_input.html" class="invalid">form_input</a></li>
<li><a href="function-form_label.html" class="invalid">form_label</a></li>
<li><a href="<API key>.html" class="invalid">form_multiselect</a></li>
<li><a href="function-form_open.html" class="invalid">form_open</a></li>
<li><a href="<API key>.html" class="invalid">form_open_multipart</a></li>
<li><a href="<API key>.html" class="invalid">form_password</a></li>
<li><a href="function-form_prep.html" class="invalid">form_prep</a></li>
<li><a href="function-form_radio.html" class="invalid">form_radio</a></li>
<li><a href="function-form_reset.html" class="invalid">form_reset</a></li>
<li><a href="<API key>.html" class="invalid">form_submit</a></li>
<li><a href="<API key>.html" class="invalid">form_textarea</a></li>
<li><a href="<API key>.html" class="invalid">form_upload</a></li>
<li><a href="<API key>.html">function_usable</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="function-get_config.html" class="invalid">get_config</a></li>
<li><a href="function-get_cookie.html" class="invalid">get_cookie</a></li>
<li><a href="<API key>.html" class="invalid">get_dir_file_info</a></li>
<li><a href="<API key>.html" class="invalid">get_file_info</a></li>
<li><a href="<API key>.html" class="invalid">get_filenames</a></li>
<li><a href="<API key>.html" class="invalid">get_instance</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="function-get_mimes.html">get_mimes</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">GetInfoFromTrueType</a></li>
<li><a href="<API key>.html">GetInfoFromType1</a></li>
<li><a href="<API key>.html">getPrecioFinal</a></li>
<li><a href="<API key>.html" class="invalid">gmt_to_local</a></li>
<li><a href="<API key>.html">hash_equals</a></li>
<li><a href="<API key>.html">hash_pbkdf2</a></li>
<li><a href="function-heading.html" class="invalid">heading</a></li>
<li><a href="function-hex2bin.html">hex2bin</a></li>
<li><a href="<API key>.html" class="invalid">highlight_code</a></li>
<li><a href="<API key>.html" class="invalid">highlight_phrase</a></li>
<li><a href="<API key>.html" class="invalid">html_escape</a></li>
<li><a href="<API key>.html" class="invalid">human_to_unix</a></li>
<li><a href="function-humanize.html" class="invalid">humanize</a></li>
<li><a href="function-hypo.html">hypo</a></li>
<li><a href="function-img.html" class="invalid">img</a></li>
<li><a href="<API key>.html" class="invalid">increment_string</a></li>
<li><a href="function-index_page.html" class="invalid">index_page</a></li>
<li><a href="function-is_cli.html">is_cli</a></li>
<li><a href="<API key>.html">is_countable</a></li>
<li><a href="function-is_false.html" class="invalid">is_false</a></li>
<li><a href="function-is_https.html">is_https</a></li>
<li><a href="function-is_loaded.html" class="invalid">is_loaded</a></li>
<li><a href="function-is_php.html" class="invalid">is_php</a></li>
<li><a href="<API key>.html" class="invalid">is_really_writable</a></li>
<li><a href="function-is_true.html" class="invalid">is_true</a></li>
<li><a href="function-JAMAError.html">JAMAError</a></li>
<li><a href="<API key>.html">js_insert_smiley</a></li>
<li><a href="function-lang.html" class="invalid">lang</a></li>
<li><a href="function-link_tag.html" class="invalid">link_tag</a></li>
<li><a href="function-load_class.html" class="invalid">load_class</a></li>
<li><a href="function-LoadMap.html">LoadMap</a></li>
<li><a href="<API key>.html" class="invalid">local_to_gmt</a></li>
<li><a href="<API key>.html" class="invalid">log_message</a></li>
<li><a href="function-mailto.html" class="invalid">mailto</a></li>
<li><a href="<API key>.html">MakeDefinitionFile</a></li>
<li><a href="function-MakeFont.html">MakeFont</a></li>
<li><a href="<API key>.html">MakeFontDescriptor</a></li>
<li><a href="<API key>.html">MakeFontEncoding</a></li>
<li><a href="<API key>.html">MakeUnicodeArray</a></li>
<li><a href="<API key>.html">MakeWidthArray</a></li>
<li><a href="<API key>.html">mb_str_replace</a></li>
<li><a href="function-mb_strlen.html">mb_strlen</a></li>
<li><a href="function-mb_strpos.html">mb_strpos</a></li>
<li><a href="function-mb_substr.html">mb_substr</a></li>
<li><a href="function-mdate.html" class="invalid">mdate</a></li>
<li><a href="function-Message.html">Message</a></li>
<li><a href="function-meta.html" class="invalid">meta</a></li>
<li><a href="<API key>.html">MostrarDescuento</a></li>
<li><a href="<API key>.html">MuestraMonedas</a></li>
<li><a href="<API key>.html" class="invalid">mysql_to_unix</a></li>
<li><a href="function-nbs.html" class="invalid">nbs</a></li>
<li><a href="function-nice_date.html">nice_date</a></li>
<li><a href="<API key>.html" class="invalid">nl2br_except_pre</a></li>
<li><a href="function-Notice.html">Notice</a></li>
<li><a href="function-now.html" class="invalid">now</a></li>
<li><a href="<API key>.html" class="invalid">octal_permissions</a></li>
<li><a href="<API key>.html">odbc_fetch_array</a></li>
<li><a href="<API key>.html">odbc_fetch_object</a></li>
<li><a href="function-ol.html" class="invalid">ol</a></li>
<li><a href="<API key>.html" class="invalid">parse_smileys</a></li>
<li><a href="<API key>.html">password_get_info</a></li>
<li><a href="<API key>.html">password_hash</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">password_verify</a></li>
<li><a href="<API key>.html">PclZipUtilCopyBlock</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html">PclZipUtilRename</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="function-plural.html" class="invalid">plural</a></li>
<li><a href="function-prep_url.html" class="invalid">prep_url</a></li>
<li><a href="<API key>.html"><API key></a></li>
<li><a href="<API key>.html" class="invalid">quotes_to_entities</a></li>
<li><a href="<API key>.html" class="invalid">random_element</a></li>
<li><a href="<API key>.html" class="invalid">random_string</a></li>
<li><a href="function-read_file.html" class="invalid">read_file</a></li>
<li><a href="function-redirect.html" class="invalid">redirect</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="<API key>.html" class="invalid">reduce_multiples</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="function-repeater.html" class="invalid">repeater</a></li>
<li><a href="<API key>.html" class="invalid">safe_mailto</a></li>
<li><a href="<API key>.html" class="invalid">sanitize_filename</a></li>
<li><a href="function-SaveToFile.html">SaveToFile</a></li>
<li><a href="function-send_email.html" class="invalid">send_email</a></li>
<li><a href="<API key>.html">SesionIniciadaCheck</a></li>
<li><a href="<API key>.html" class="invalid">set_checkbox</a></li>
<li><a href="function-set_cookie.html" class="invalid">set_cookie</a></li>
<li><a href="function-set_radio.html" class="invalid">set_radio</a></li>
<li><a href="<API key>.html" class="invalid">set_realpath</a></li>
<li><a href="function-set_select.html" class="invalid">set_select</a></li>
<li><a href="<API key>.html" class="invalid">set_status_header</a></li>
<li><a href="function-set_value.html" class="invalid">set_value</a></li>
<li><a href="function-show_404.html" class="invalid">show_404</a></li>
<li><a href="function-show_error.html" class="invalid">show_error</a></li>
<li><a href="function-singular.html" class="invalid">singular</a></li>
<li><a href="function-site_url.html" class="invalid">site_url</a></li>
<li><a href="function-smiley_js.html" class="invalid">smiley_js</a></li>
<li><a href="<API key>.html" class="invalid">standard_date</a></li>
<li><a href="<API key>.html" class="invalid">strip_image_tags</a></li>
<li><a href="<API key>.html" class="invalid">strip_quotes</a></li>
<li><a href="<API key>.html" class="invalid">strip_slashes</a></li>
<li><a href="<API key>.html" class="invalid"><API key></a></li>
<li><a href="function-timespan.html" class="invalid">timespan</a></li>
<li><a href="<API key>.html" class="invalid">timezone_menu</a></li>
<li><a href="function-timezones.html" class="invalid">timezones</a></li>
<li><a href="function-transpose.html">transpose</a></li>
<li><a href="<API key>.html" class="invalid">trim_slashes</a></li>
<li><a href="function-ul.html" class="invalid">ul</a></li>
<li><a href="function-underscore.html" class="invalid">underscore</a></li>
<li><a href="<API key>.html" class="invalid">unix_to_human</a></li>
<li><a href="function-uri_string.html" class="invalid">uri_string</a></li>
<li><a href="function-url_title.html" class="invalid">url_title</a></li>
<li><a href="<API key>.html" class="invalid">valid_email</a></li>
<li><a href="<API key>.html" class="invalid">validation_errors</a></li>
<li><a href="function-Warning.html">Warning</a></li>
<li><a href="<API key>.html" class="invalid">word_censor</a></li>
<li><a href="<API key>.html" class="invalid">word_limiter</a></li>
<li><a href="function-word_wrap.html" class="invalid">word_wrap</a></li>
<li><a href="function-write_file.html" class="invalid">write_file</a></li>
<li><a href="<API key>.html" class="invalid">xml_convert</a></li>
<li><a href="function-xss_clean.html" class="invalid">xss_clean</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="">
<input type="hidden" name="ie" value="UTF-8">
<input type="text" name="q" class="text" placeholder="Search">
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-None.html" title="Summary of None"><span>Namespace</span></a>
</li>
<li class="active">
<span>Class</span> </li>
</ul>
<ul>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
</ul>
<ul>
</ul>
</div>
<div id="content" class="class">
<h1>Class CI_DB_mysqli_driver</h1>
<div class="invalid">
<p>
Documentation of this class could not be generated.
</p>
<p>
Class was originally declared in Otros/Agregador_Tiendas/system/database/drivers/mysqli/mysqli_driver.php and is invalid because of:
</p>
<ul>
</ul>
</div>
</div>
<div id="footer">
Practica2_Servidor API documentation generated by <a href="http://apigen.org">ApiGen</a>
</div>
</div>
</div>
<script src="resources/combined.js"></script>
<script src="elementlist.js"></script>
</body>
</html> |
<?php
namespace Model\Ontology;
use Model\Entity\Question;
class QuestionDefinition implements IDefinition
{
use \Nette\SmartObject;
/** @var CourseFactory */
private $factory;
/** @var QuestionRepository */
private $repository;
/** @var string Question's source filename */
public $source;
/** @var array Array of QuestionItems */
private $questionItems = array();
/** @var array Used up question items when question items may not be repeated */
private $<API key> = array();
/** @var bool One question definition may be used multiple times */
private $repeatAllowed = FALSE;
/** @var array Array of Params objects */
private $params = array();
/** @var string hash of the data */
private $hash;
/** @var array Array of rubrics */
private $rubrics = array();
/** @var int Count of produced questions from this definition */
private $assembledCount = 0;
/**
* @param array
* @param <API key>
*/
public function __construct($data, $factory)
{
$this->factory = $factory;
$this->repository = $this->factory->questionRepository;
$this->hash = substr(sha1(serialize($data)), 0, 6);
$this->source = $data['filename'];
if (isset($data['allowRepeat']) && $data['allowRepeat'] === 'question') {
$this->repeatAllowed = TRUE;
}
$this->defineQuestionItems($data);
if (isset($data['rubrics'])) {
$builder = new RubricBuilder;
$this->rubrics = $builder->buildSet($data['rubrics']);
}
}
/**
* Defines questions and adds them to the assignment structure.
* @param QuestionDefinition
* @param array question data
* @param array parent question data used in param inheritance
* @return QuestionDefinition
*/
private function defineQuestionItems($data, $inherit = array())
{
// inherit from parent
if (count($inherit)) {
$data = array_merge($inherit, $data);
}
// define params
$params = $this->defineParams($data);
// check and prepare questions
if (!isset($data['questions'])) {
throw new <API key>('No questions found.');
} else if (is_string($data['questions'])) {
$data['questions'] = array($data['questions']);
}
// define questions
foreach ($data['questions'] as $item) {
if (is_string($item)) {
$this->questionItems[] = new QuestionItem($data, $item, $params);
} else if (is_array($item)) {
$this->defineQuestionItems($item, $data);
} else {
throw new <API key>();
}
}
}
/**
* @param array
* @return Params
*/
private function defineParams($data)
{
// deprecated vars --> params
if (isset($data['vars'])) {
$data['params'] = $data['vars'];
unset($data['vars']);
}
$paramsAvailable = (isset($data['params']) && is_array($data['params']));
if ($paramsAvailable) {
$params = new Params($data['params']);
// allow repeat
if (isset($data['allowRepeat']) && $data['allowRepeat'] === 'params') {
$params->allowRepeat();
}
// register in unit
if (in_array($params, $this->params)) {
$params = $this->params[array_search($params, $this->params)];
} else {
$this->params[] = $params;
}
} else {
$params = null;
}
return $params;
}
/**
* Get all questions' keys
* @return array
*/
public function getKeys()
{
return array_keys($this->questionDefinitions);
}
/**
* Get questions' count
* @return int
*/
public function count()
{
return count($this->questionDefinitions);
}
/**
* Assembles a new question.
* @return Model\Entity\Question
*/
public function assemble()
{
$question = new Question();
$question->source = $this->source;
$question->itemKey = $this-><API key>();
$question->paramsKey = $this->questionItems[$question->itemKey]->assembleParamsKey();
$question->hash = $this->hash;
$question->order = $this->assembledCount;
/* Question texts are saved so that they're
* available in case the definition
* changes and it's been already used somehow */
$question->text = $this->questionItems[$question->itemKey]->getText($question->paramsKey);
$question->prefill = $this->questionItems[$question->itemKey]->getPrefill($question->paramsKey);
$question->input = $this->questionItems[$question->itemKey]->getInput($question->paramsKey);
$this->repository->persist($question);
$this->assembledCount++;
return $question;
}
private function <API key>()
{
$keys = array_keys($this->questionItems);
$availableKeys = array_diff($keys, $this-><API key>);
if (count($availableKeys) === 0) {
throw new Exception('Cannot generate more variations of the same question.');
return;
}
$key = $availableKeys[array_rand($availableKeys)];
if (!$this->repeatAllowed) {
$this-><API key>[] = $key;
}
return $key;
}
/**
* Produces a question from saved entity.
* @param Model\Entity\Question
* @return Model\Ontology\QuestionProduct
*/
public function produce($question)
{
$product = new QuestionProduct($question);
$product->rubrics = $this->rubrics;
$item = $this->getQuestionItem($question->itemKey);
$product->bloom = $item->bloom;
$product->source = $this->source;
$product->order = $question->order;
$product->text = $item->getText($question->paramsKey);
$product->prefill = $item->getPrefill($question->paramsKey);
$product->input = $item->getInput($question->paramsKey);
$product->comments = $item->comments;
$product->hashMatch = $question->hash === $this->hash;
if (!$product->hashMatch) {
$product->textDump = ($question->text !== $product->text)
? $question->text
: null;
$product->prefillDump = ($question->prefill !== $product->prefill)
? $question->prefill
: null;
$product->inputDump = ($question->input !== $product->input)
? $question->input
: null;
}
return $product;
}
private function getQuestionItem($key)
{
if (isset($this->questionItems[$key])) {
return $this->questionItems[$key];
} else {
return FALSE;
}
}
} |
/*
Programa que transforma todos os caracteres em minusculo
AUTOR: GABRIEL HENRIQUE CAMPOS SCALICI
NUMERO: 9292970
DATA:10-05-2015
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main(){
char * seq = malloc(10000);
int i, j;
//PEgando os valores digitados pelo usuario
scanf("%s", seq);
for(i=0; i<strlen(seq); i++){
switch (seq[i]){
case 'A':
seq[i] = 'a';
break;
case 'B':
seq[i] = 'b';
break;
case 'C':
seq[i] = 'c';
break;
case 'D':
seq[i] = 'd';
break;
case 'E':
seq[i] = 'e';
break;
case 'F':
seq[i] = 'f';
break;
case 'G':
seq[i] = 'g';
break;
case 'H':
seq[i] = 'h';
break;
case 'I':
seq[i] = 'i';
break;
case 'J':
seq[i] = 'j';
break;
case 'K':
seq[i] = 'k';
break;
case 'L':
seq[i] = 'l';
break;
case 'M':
seq[i] = 'm';
break;
case 'N':
seq[i] = 'n';
break;
case 'O':
seq[i] = 'o';
break;
case 'P':
seq[i] = 'p';
break;
case 'Q':
seq[i] = 'q';
break;
case 'R':
seq[i] = 'r';
break;
case 'S':
seq[i] = 's';
break;
case 'T':
seq[i] = 't';
break;
case 'U':
seq[i] = 'u';
break;
case 'V':
seq[i] = 'v';
break;
case 'X':
seq[i] = 'x';
break;
case 'Y':
seq[i] = 'y';
break;
case 'W':
seq[i] = 'w';
break;
case 'Z':
seq[i] = 'z';
break;
}
}
for(i=0; i<strlen(seq); i++){
printf("%c", seq[i]);
}
return 0;
} |
using System.Collections.Generic;
using System.Linq;
namespace ErwinMayerLabs.Lib {
public static class UtilsExtensions {
public static IEnumerable<T> GetRange<T>(this IReadOnlyList<T> array, int startIndex, int endIndex) {
if (startIndex <= endIndex) {
for (var j = startIndex; j <= endIndex; ++j) {
yield return array[j];
}
}
else {
for (var j = startIndex; j >= endIndex; --j) {
yield return array[j];
}
}
}
public static bool ContainsAny<T>(this IEnumerable<T> source, params T[] matches) {
return matches.Any(source.Contains);
}
public static bool ContainsAny<T>(this IEnumerable<T> source, IEnumerable<T> matches) {
return matches.Any(source.Contains);
}
}
} |
package com.example.newbiechen.<API key>.ui.base;
import android.os.Bundle;
import android.support.annotation.IntegerRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public abstract class BaseFragment extends Fragment{
private View root = null;
@LayoutRes
protected abstract int createView();
/**
* View
*/
protected abstract void initView(Bundle savedInstanceState);
protected void initClick(){
}
protected void processLogic(Bundle savedInstanceState){
}
protected void initWidget(Bundle savedInstanceState){
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
int resId = createView();
root = inflater.inflate(resId,container,false);
return root;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView(savedInstanceState);
initWidget(savedInstanceState);
initClick();
processLogic(savedInstanceState);
}
public String getName(){
return getClass().getName();
}
protected <VT> VT getViewById(int id){
if (root == null){
return null;
}
return (VT) root.findViewById(id);
}
} |
## Compiling your own version with Gulp-Include
You many not need to use every component available. If you would like to compile your own version and you are using Gulp ish.js makes that pretty easy for you.
Firstly you will need to install Gulp-Include.
$ npm install gulp-include --save-dev
Then add an include task to your Gulp file
var gulp = require("gulp"),
include = require("gulp-include");
gulp.task("scripts", function() {
console.log("-- gulp is running task 'scripts'");
gulp.src("ish.custom.js")
.pipe(include())
.on('error', console.log)
.pipe(gulp.dest("dist/js"));
});
gulp.task("default", ["scripts"]
Next copy the /ish.custom.js file into your project and update the gulp.src parameter to reflect the new location. You can also change the destination folder include sourcemaps and more. Checkout the Gulp-Inluce npm page for more detail.
File references in your new ish.custom.js file will need to be updated to point to the location of the ish.js library files within your project.
Adding/Removing Packages
Gulp-Include uses //=require and //=include directives. All of the files are referenced in the ish.custom.js file you just copied although some are commented out. Note that since Gulp-Include uses single line comments to start their directives double single quotes will prevent that directive from being executed. You can learn more over at the Gulp-Include NPM page.
// This directive will be executed.
//require path/to/file.js
// This directive will not be executed.
/require path/to/file.js
Once you are happy with the files being bundled run gulp and your newly compiled file should be ready to go. |
<?php
namespace Oro\Bundle\FilterBundle\Filter;
use Doctrine\Common\Collections\Collection;
use Oro\Bundle\FilterBundle\Datasource\<API key>;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Oro\Bundle\FilterBundle\Form\Type\Filter\FilterType;
use Oro\Bundle\FilterBundle\Form\Type\Filter\ChoiceFilterType;
class ChoiceFilter extends AbstractFilter
{
/**
* {@inheritdoc}
*/
protected function getFormType()
{
return ChoiceFilterType::NAME;
}
/**
* {@inheritdoc}
*/
public function apply(<API key> $ds, $data)
{
$data = $this->parseData($data);
if (!$data) {
return false;
}
$operator = $this->getOperator($data['type']);
$parameter = $ds-><API key>($this->getName());
if ('IN' == $operator) {
$expression = $ds->expr()->in($this->get(FilterUtility::DATA_NAME_KEY), $parameter, true);
} else {
$expression = $ds->expr()->notIn($this->get(FilterUtility::DATA_NAME_KEY), $parameter, true);
}
$this->applyFilterToClause($ds, $expression);
$ds->setParameter($parameter, $data['value']);
return true;
}
/**
* {@inheritdoc}
*/
public function getMetadata()
{
$formView = $this->getForm()->createView();
$fieldView = $formView->children['value'];
$choices = array_map(
function (ChoiceView $choice) {
return [
'label' => $choice->label,
'value' => $choice->value
];
},
$fieldView->vars['choices']
);
$metadata = parent::getMetadata();
$metadata['choices'] = $choices;
$metadata['populateDefault'] = $formView->vars['populate_default'];
if ($fieldView->vars['multiple']) {
$metadata[FilterUtility::TYPE_KEY] = 'multichoice';
}
return $metadata;
}
/**
* @param mixed $data
*
* @return array|bool
*/
protected function parseData($data)
{
if (!is_array($data)
|| !array_key_exists('value', $data)
|| $data['value'] === ''
|| is_null($data['value'])
|| ((is_array($data['value']) || $data['value'] instanceof Collection) && !count($data['value']))
) {
return false;
}
$value = $data['value'];
if ($value instanceof Collection) {
$value = $value->getValues();
}
if (!is_array($value)) {
$value = array($value);
}
$data['type'] = isset($data['type']) ? $data['type'] : null;
$data['value'] = $value;
return $data;
}
/**
* Get operator string
*
* @param int $type
*
* @return string
*/
protected function getOperator($type)
{
$operatorTypes = array(
ChoiceFilterType::TYPE_CONTAINS => 'IN',
ChoiceFilterType::TYPE_NOT_CONTAINS => 'NOT IN',
FilterType::TYPE_EMPTY => 'EMPTY',
);
return isset($operatorTypes[$type]) ? $operatorTypes[$type] : 'IN';
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Pwdlyser_Enterprise
{
<summary>
Interaction logic for App.xaml
</summary>
public partial class App : Application
{
}
} |
# CornFlake
CornFlake is a small, interpreted programming language, written entirely in a Swift command line app. The language is inspired by the idea of a finite turing machine, where the number of cells is relatively small, and calculations exists with interactions between the slots. The interpreter can run on any Unix system.
##Installation
Download a zip version of the repo, and run the `CornFlake` executable under the `dist` folder.
##Usage
CornFlake uses a series of commands that can be written as a stream, seperated by spaces. These interact with the 3 slot array that powers the language.
#`close`:
The close command exits the program. It must be used as a singular command, no other commands can be present in the same line with it.
Moves the pointer to the right by one value. If the value is at the end of the array, at slot 3, it will move it back to slot 1. You can use repeated instances of this command to move the pointer more, such as `> > >`.
Moves the pointer to the left by one value. Will move back to the last slot if the pointer is currently at the first slot when this is used.
##Example Usage:
Here are some sample sessions, illustrating the different commands that can be used with the interpreter
CF> > + > + > +
CF> - - - -
CF> r
-3 1 1
CF> p
-3
CF> ++
fatal error: Can't form Range with end < start
Here, in this session, a `++` is used with a negative number. This cannot be done, because the natural sum of a number can't be computed with negative numbers in `CornFlake`. Here is a proper session showing the proper usage.
CF> + + +
CF> &
Unknown Command
CF> r
3 0 0
CF> ++
CF> r
6 0 0
CF> +> > +>
CF> r
6 6 6
CF> ++
CF> ++
CF> r
6 231 6
In this session, the `++` command is used succesfully, because it creates an internal swift range from 1 to a positive number, and doesn't incorporate negative numbers. Also here, the `+>` operators are used to pass a value from one position to another slot, by addition. This works for both the left and right direction. |
require_relative 'hang_man'
require_relative 'hangman_view'
require_relative 'random_word'
def get_letter
STDIN.gets.to_s[0]
end
random_word = RandomWord.new('words.txt').get_word
hangman = HangMan.new(random_word)
HangManView.display_hangman(hangman)
while !hangman.finished?
begin
hangman.play_turn(get_letter)
rescue HangMan::InvalidLetterError => e
puts "Not a valid alphabetical Letter :("
rescue HangMan::<API key> => e
puts "You've already tried that letter silly :P"
end
HangManView.display_hangman(hangman)
end |
package board;
public enum Color {
WHITE, BLACK
} |
#!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
from <API key> import <API key>
import string
import re
import datetime
import pyperclip
# Edit Me!
# Remember, this is during signup, so current month is not April, it's March.
<API key> = 31
currentMonthURL = "https:
currentMonthIndex = datetime.date.today().month
<API key> = <API key> - 1
currentMonthName = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}[currentMonthIndex]
nextMonthIndex = currentMonthIndex % 12 + 1
nextMonthName = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}[nextMonthIndex]
uppercaseMonth = string.upper(nextMonthName)
<API key> = datetime.date.today().day
<API key> = {1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth', 6: 'sixth', 7: 'seventh', 8: 'eighth', 9: 'ninth', 10: 'tenth', 11: 'eleventh', 12: 'twelfth', 13: 'thirteenth', 14: 'fourteenth', 15: 'fifteenth', 16: 'sixteenth', 17: 'seventeenth', 18: 'eighteenth', 19: 'nineteenth', 20: 'twentieth', 21: 'twenty-first', 22: 'twenty-second', 23: 'twenty-third', 24: 'twenty-fourth', 25: 'twenty-fifth', 26: 'twenty-sixth', 27: 'twenty-seventh', 28: 'twenty-eighth', 29: 'twenty-ninth', 30: 'thirtieth', 31: 'thirty-first'}[<API key>]
<API key> = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}[datetime.date.today().weekday()]
# TODO: testing
# <API key> = 28
participants = <API key>()
initialNumber = participants.size()
def <API key>():
answer = ""
answer += "Here are the **INITIAL_NUMBER participants** who have already signed up:\n\n"
for participant in participants.participants:
answer += "/u/" + participant.name
answer += "\n\n"
return answer
def templateForTooEarly():
answer = ""
answer += "(Too early. Come back on CURRENT_MONTH_NAME " + str(<API key> - 6) + ")\n"
return answer
def <API key>():
answer = ""
answer += "STAY CLEAN UPPERCASE_MONTH! Sign up here! (CURRENT_MONTH_NAME <API key>)\n"
answer += "Hey everybody, we had a great turnout for [Stay Clean CURRENT_MONTH_NAME](CURRENT_MONTH_URL) - let's see if we can knock it out of the park for NEXT_MONTH_NAME. Have you been clean for the month of CURRENT_MONTH_NAME? Great! Join us here, and let's keep our streak going. Did you slip in CURRENT_MONTH_NAME? Then NEXT_MONTH_NAME is your month to shine, and we will gladly fight the good fight along with you. Did you miss out on the CURRENT_MONTH_NAME challenge? Well then here is your opportunity to join us.\n"
answer += "\n"
answer += "If you would like to be included in this challenge, please post a brief comment to this thread, and I will include you. After midnight, NEXT_MONTH_NAME 1, the sign up window will close, and the challenge will begin."
return answer
def <API key>():
answer = ""
answer += "STAY CLEAN UPPERCASE_MONTH! Sign up here! (CURRENT_MONTH_NAME <API key>)\n"
answer += "Hey everybody, so far **INITIAL_NUMBER participants** have signed up. Have you been clean for **[the month of CURRENT_MONTH_NAME](CURRENT_MONTH_URL)**? Great! Join us here, and let's keep our streak going. Did you slip in CURRENT_MONTH_NAME? Then NEXT_MONTH_NAME is your month to shine, and we will gladly fight the good fight along with you. Did you miss out on the CURRENT_MONTH_NAME challenge? Well then here is your opportunity to join us.\n"
answer += "\n"
answer += "If you would like to be included in this challenge, please post a brief comment to this thread (if you haven't already done so on an earlier signup thread), and I will include you. After midnight, NEXT_MONTH_NAME 1, the sign up window will close, and the challenge will begin.\n"
answer += "\n"
answer += <API key>()
return answer
def <API key>():
answer = ""
answer += "LAST CHANCE TO SIGN UP FOR STAY CLEAN UPPERCASE_MONTH! Sign up here!\n"
answer += "The Stay Clean NEXT_MONTH_NAME challenge **begins tomorrow**! So far, we have **INITIAL_NUMBER participants** signed up. If you would like to be included in the challenge, please post a brief comment to this thread (if you haven't already done so on an earlier signup thread), and we will include you. After midnight tonight, we will not be accepting any more participants. I will create the official update post tomorrow.\n"
answer += "\n"
answer += <API key>()
return answer
def templateToUse():
if <API key> <= (<API key> - 7):
# if <API key> <= (<API key> - 8):
return templateForTooEarly()
elif <API key> == (<API key> - 6):
# elif <API key> == (<API key> - 7):
return <API key>()
elif (<API key> - 5) <= <API key> <= (<API key> - 1):
# elif (<API key> - 6) <= <API key> <= (<API key> - 1):
return <API key>()
elif <API key> == <API key>:
return <API key>()
def stringToPrint():
answer = templateToUse()
answer = re.sub('INITIAL_NUMBER', str(initialNumber), answer)
answer = re.sub('CURRENT_MONTH_INDEX', str(currentMonthIndex), answer)
answer = re.sub('<API key>', str(<API key>), answer)
answer = re.sub('<API key>', str(<API key>), answer)
answer = re.sub('CURRENT_MONTH_NAME', currentMonthName, answer)
answer = re.sub('CURRENT_MONTH_URL', currentMonthURL, answer)
answer = re.sub('NEXT_MONTH_INDEX', str(nextMonthIndex), answer)
answer = re.sub('NEXT_MONTH_NAME', nextMonthName, answer)
answer = re.sub('<API key>', str(<API key>), answer)
answer = re.sub('<API key>', <API key>, answer)
answer = re.sub('<API key>', <API key>, answer)
answer = re.sub('UPPERCASE_MONTH', uppercaseMonth, answer)
return answer
outputString = stringToPrint()
print "============================================================="
print outputString
print "============================================================="
pyperclip.copy(outputString) |
+ function($) {
'use strict';
// AFFIX CLASS DEFINITION
var Affix = function(element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.<API key>, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.2.0'
Affix.RESET = 'u-affix u-affix--top u-affix--bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function(scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && colliderTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function() {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('u-affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.<API key> = function() {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = $('body').height()
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'u-affix' + (affix ? '--' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
$.fn.affix.noConflict = function() {
$.fn.affix = old
return this
}
// AFFIX DATA-API
$(window).on('load', function() {
$('[data-spy="affix"]').each(function() {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery); |
using BehaviourTree.Decorators;
using BehaviourTree.Tests.Utils;
using NUnit.Framework;
namespace BehaviourTree.Tests
{
[TestFixture]
internal sealed class CooldownTests
{
[Test]
public void <API key>()
{
var child = new MockBehaviour { ReturnStatus = BehaviourStatus.Succeeded };
var sut = new Cooldown<MockContext>(child, 1000);
var behaviourStatus = sut.Tick(new MockContext());
Assert.That(behaviourStatus, Is.EqualTo(BehaviourStatus.Succeeded));
Assert.That(child.TerminateCallCount, Is.EqualTo(1));
Assert.That(sut.OnCooldown, Is.True);
}
[Test]
public void <API key>()
{
var child = new MockBehaviour { ReturnStatus = BehaviourStatus.Failed };
var sut = new Cooldown<MockContext>(child, 1000);
var behaviourStatus = sut.Tick(new MockContext());
Assert.That(behaviourStatus, Is.EqualTo(BehaviourStatus.Failed));
Assert.That(child.TerminateCallCount, Is.EqualTo(1));
Assert.That(sut.OnCooldown, Is.False);
}
[Test]
public void <API key>()
{
var child = new MockBehaviour { ReturnStatus = BehaviourStatus.Running };
var sut = new Cooldown<MockContext>(child, 1000);
var behaviourStatus = sut.Tick(new MockContext());
Assert.That(behaviourStatus, Is.EqualTo(BehaviourStatus.Running));
Assert.That(child.TerminateCallCount, Is.EqualTo(0));
Assert.That(sut.OnCooldown, Is.False);
}
[Test]
public void <API key>()
{
var child = new MockBehaviour { ReturnStatus = BehaviourStatus.Succeeded };
var sut = new Cooldown<MockContext>(child, 1000);
sut.Tick(new MockContext());
var behaviourStatus = sut.Tick(new MockContext());
Assert.That(behaviourStatus, Is.EqualTo(BehaviourStatus.Failed));
Assert.That(child.TerminateCallCount, Is.EqualTo(1));
Assert.That(sut.OnCooldown, Is.True);
}
[Test]
public void <API key>()
{
var child = new MockBehaviour { ReturnStatus = BehaviourStatus.Succeeded };
var sut = new Cooldown<MockContext>(child, 1000);
var context = new MockContext();
sut.Tick(context);
context.AddMilliseconds(2000);
var behaviourStatus = sut.Tick(context);
Assert.That(behaviourStatus, Is.EqualTo(BehaviourStatus.Succeeded));
Assert.That(child.TerminateCallCount, Is.EqualTo(2));
Assert.That(sut.OnCooldown, Is.True);
}
}
} |
// DSShareHelps.h
// DirectoryStructure
#import <Foundation/Foundation.h>
@interface DSShareHelps : NSObject
@end |
.PHONY: clean clean-test clean-pyc clean-build docs help
.DEFAULT_GOAL := help
define BROWSER_PYSCRIPT
import os, webbrowser, sys
try:
from urllib import pathname2url
except:
from urllib.request import pathname2url
webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
endef
export BROWSER_PYSCRIPT
define PRINT_HELP_PYSCRIPT
import re, sys
for line in sys.stdin:
match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
if match:
target, help = match.groups()
print("%-20s %s" % (target, help))
endef
export PRINT_HELP_PYSCRIPT
BROWSER := python -c "$$BROWSER_PYSCRIPT"
help:
@python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts
clean-build: ## remove build artifacts
rm -fr build/
rm -fr dist/
rm -fr .eggs/
find . -name '*.egg-info' -exec rm -fr {} +
find . -name '*.egg' -exec rm -f {} +
clean-pyc: ## remove Python file artifacts
find . -name '*.pyc' -exec rm -f {} +
find . -name '*.pyo' -exec rm -f {} +
find . -name '*~' -exec rm -f {} +
find . -name '__pycache__' -exec rm -fr {} +
clean-test: ## remove test and coverage artifacts
rm -fr .tox/
rm -f .coverage
rm -fr htmlcov/
lint: ## check style with flake8
flake8 sch_time_eq tests
test: ## run tests quickly with the default Python
python setup.py test
test-all: ## run tests on every Python version with tox
tox
coverage: ## check code coverage quickly with the default Python
coverage run --source sch_time_eq setup.py test
coverage report -m
coverage html
$(BROWSER) htmlcov/index.html
docs: ## generate Sphinx HTML documentation, including API docs
rm -f docs/sch_time_eq.rst
rm -f docs/modules.rst
sphinx-apidoc -o docs/ sch_time_eq
$(MAKE) -C docs clean
$(MAKE) -C docs html
$(BROWSER) docs/_build/html/index.html
servedocs: docs ## compile the docs watching for changes
watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D .
release: clean ## package and upload a release
python setup.py sdist upload
python setup.py bdist_wheel upload
dist: clean ## builds source and wheel package
python setup.py sdist
python setup.py bdist_wheel
ls -l dist
install: clean ## install the package to the active Python's site-packages
python setup.py install |
<
.Notes
NAME: Update-SCSMEnumList.ps1
AUTHOR: Stefan Johner
Website: http://blog.jhnr.ch
Twitter: http://twitter.com/JohnerStefan
Version: 1.1
CREATED: 11/04/2015
LASTEDIT:
11/04/2015 1.0
Initial Release
.Synopsis
This script updates Service Manager enums based on a MySQL query.
.Description
The script establishes a connection to a MySQL database and updates a defined enumeration list according to the defined MySQL query
The user which runs the script needs to be part of the "Author" role to update enum lists. Also the script needs to be executed on a
Service Manager management server where MySQL Connector/Net ADO.NET driver and SMLets are installed (see http://dev.mysql.com/downloads/connector/net/)
Do not forget to update credentials for SQL connection string.
.Example
.\Update-SCSMEnumList.ps1 -Verbose
.Link
http://github.com/sjohner/<API key>
[cmdletbinding()]
# Setup the script to stop on error
$<API key> = "Stop"
#Define MySQL query to get job titles
$MySqlQuery = "select title from jobtitles where deleted = 0"
#Define MySQL credentials and connection string
$MySQLUserName = 'mysqluser'
$MySQLPassword = 'p@ssword'
$MySQLDatabase = 'databasename'
$MySQLHost = 'mysql.scsmlab.com'
$ConnectionString = "server=" + $MySQLHost + "; port=3306; uid=" + $MySQLUserName + "; pwd=" + $MySQLPassword + "; database="+$MySQLDatabase
try
{
#Used to invoke MySQL query
Function Invoke-MySQL {
Param
(
[Parameter(Mandatory = $true,ParameterSetName = '',ValueFromPipeline = $true)][string]$Query
)
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
#Create new connection by using previousely defined connection string
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
#Excute query and close connection
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
$Connection.Close()
#Return query results
Return $DataSet.Tables[0]
}
#Get Job Titles from Tippps MySQL database
$Result = Invoke-MySQL -Query $MySqlQuery
Write-Verbose "Retreived data from MySQL database ($($Result.Rows.Count) rows)"
#Import SMLets
Import-Module smlets
#Get Management Pack to save enumerations and appropriate parent enum
$EnumManagementPack = <API key> -Name ^tph.listelements.library$
$ParentEnum = Get-SCSMEnumeration -Name ^<API key>$
#Get child enumsn using <API key> which is much faster
#PS C:\> (Measure-Command {<API key> -Enumeration $ParentEnum}).TotalMilliseconds
#1,3816
#PS C:\> (Measure-Command {(Get-SCSMEnumeration | where {$_.Parent -match $($ParentEnum.Id)})}).TotalMilliseconds
#242,5261
$ChildEnums = <API key> -Enumeration $ParentEnum
#Add new titles to enum list if not already in enum list
Foreach($Title in $Result.Title) {
if($($ChildEnums.DisplayName) -notcontains $Title) {
#Get highest ordinal value using Measure-Object. Seems to be much faster than sorting an getting last objects ordinal value
#PS C:\> (Measure-Command {($ChildEnums | Measure-Object -Property Ordinal -Maximum).Maximum}).TotalMilliseconds
#0,892
#PS C:\> (Measure-Command {($ChildEnums | Sort-Object Ordinal | select -Last 1).Ordinal}).TotalMilliseconds
#4,0093
$Ordinal = (($ChildEnums | Measure-Object -Property Ordinal -Maximum).Maximum) + 1
#Create child enum internal name (convert to lower case and remove spaces)
$ChildEnumName = "$($ParentEnum.Name)$Title".ToLower() -replace '\s',''
#Add new child enum as last element in list (increment hightest ordinal)
Add-SCSMEnumeration -Parent $ParentEnum -Name $ChildEnumName -DisplayName $Title -Ordinal $Ordinal -ManagementPack $EnumManagementPack
Write-Verbose "Added $Title to Enum List"
}
}
#Remove obsolete titles from enum list if not anymore in database
Foreach($ChildEnum in $ChildEnums) {
if($($Result.Title) -notcontains $($ChildEnum.DisplayName)) {
<API key> -Enumeration $ChildEnum
Write-Verbose "Removed $($ChildEnum.DisplayName) from Enum List"
}
}
# Remove smlets
Remove-module smlets -force
}
catch {
Throw "@
$error[0]
@"
} |
# macsetup
Script to setup my mac
## Step 1
To start the setup prosess, execute the following line:
curl https://raw.githubusercontent.com/rogerlysberg/macsetup/master/setup.sh | sh |
import markdown, datetime
from django import template
from django.template.base import (Node, NodeList, TemplateSyntaxError)
register = template.Library()
@register.filter(name='toHtml')
def toHtml(markdownfile):
return markdown.markdown(markdownfile)
@register.filter(name='toNowTime')
def toNowTime(black_hole):
return datetime.now() |
/**
* Datasource.js
*/
var Datasource=function(pParams) {};
/**
* Initializes the datasource
* @param pParams the parameters
* @param pCallback the callback to invoke on completion
*/
Datasource.prototype.init=function(pParams, pCallback) {
pCallback && pCallback();
};
/**
* Closes the datasource
* @param pParams the parameters
* @param pCallback the callback to invoke on completion
*/
Datasource.prototype.close=function(pParams, pCallback) {
pCallback && pCallback();
};
/**
* Gets the object used by DAOs
* @returns the object used by DAOs
*/
Datasource.prototype.getDaoParams=function() {
return null;
};
module.exports=Datasource; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name=viewport content="width=device-width, initial-scale=1, user-scalable=no">
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab:300,400|Roboto:300,400,700,300italic' rel='stylesheet' type='text/css'>
<title>DG | 707</title>
</head>
<body>
<div id="app" class="app"></div>
<script src="dev-bundle.js"></script>
</body>
</html> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.